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
umariqb/3D_Pose_Estimation_CVPR2016-master
grPlot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/synthesis/GrTheory/grPlot.m
7,525
utf_8
f359c5370461e7937b7b2498dc109cda
function h=grPlot(V,E,kind,vkind,ekind) % Function h=grPlot(V,E,kind,vkind,ekind) % draw the plot of the graph (digraph). % Input parameters: % V(n,2) or (n,3) - the coordinates of vertexes % (1st column - x, 2nd - y) and, maybe, 3rd - the weights; % n - number of vertexes. % If V(n,2), we write labels: numbers of vertexes, % if V(n,3), we write labels: the weights of vertexes. % If V=[], use regular n-angle. % E(m,2) or (m,3) - the edges of graph (arrows of digraph) % and their weight; 1st and 2nd elements of each row % is numbers of vertexes; % 3rd elements of each row is weight of arrow; % m - number of arrows. % If E(m,2), we write labels: numbers of edges (arrows); % if E(m,3), we write labels: weights of edges (arrows). % For disconnected graph use E=[] or h=PlotGraph(V). % kind - the kind of graph. % kind = 'g' (to draw the graph) or 'd' (to draw digraph); % (optional, 'g' default). % vkind - kind of labels for vertexes (optional). % ekind - kind of labels for edges or arrows (optional). % For vkind and ekind use the format of function FPRINTF, % for example, '%8.3f', '%14.10f' etc. Default value is '%d'. % Use '' (empty string) for don't draw labels. % Output parameter: % h - handle of figure (optional). % See also GPLOT. % Author: Sergiy Iglin % e-mail: [email protected] % personal page: http://iglin.exponenta.ru % Acknowledgements to Mr.Howard ([email protected]) % for testing of this algorithm. % ============= Input data validation ================== if nargin<1, error('There are no input data!') end if (nargin==1) & isempty(V), error('V is empty and E is not determined!') end if (nargin==2) & isempty(V) & isempty(E), error('V and E are empty!') end if ~isempty(V), if ~isnumeric(V), error('The array V must be numeric!') end sv=size(V); % size of array V if length(sv)~=2, error('The array V must be 2D!') end if (sv(2)<2), error('The array V must have 2 or 3 columns!'), end if nargin==1, % disconnected graph E=[]; end end if ~isempty(E), % for connected graph [m,n,newE]=grValidation(E); we=min(3,size(E,2)); % 3 for weighed edges E=newE; if isempty(V), % regular n-angle V=[cos(2*pi*[1:n]'/n) sin(2*pi*[1:n]'/n)]; sv=size(V); % size of array V end if n>sv(1), error('Several vertexes is not determined!'); end else m=0; end % ============= Other arguments ================== n=sv(1); % real number of vertexes wv=min(3,sv(2)); % 3 for weighted vertexes if nargin<3, % only 2 input parameters kind1='g'; else if isempty(kind), kind='g'; kind1='g'; end if ~ischar(kind), error('The argument kind must be a string!') else kind1=lower(kind(1)); end end if nargin<4, vkind1='%d'; else if ~ischar(vkind), error('The argument vkind must be a string!') else vkind1=lower(vkind); end end if nargin<5, ekind1='%d'; else if ~ischar(ekind), error('The argument ekind must be a string!') else ekind1=lower(ekind); end end md=inf; % the minimal distance between vertexes for k1=1:n-1, for k2=k1+1:n, md=min(md,sum((V(k1,:)-V(k2,:)).^2)^0.5); end end if md<eps, % identical vertexes error('The array V have identical rows!') else V(:,1:2)=V(:,1:2)/md; % normalization end r=0.1; % for multiple edges tr=linspace(pi/4,3*pi/4); xr=0.5-cos(tr)/2^0.5; yr=(sin(tr)-2^0.5/2)/(1-2^0.5/2); t=linspace(-pi/2,3*pi/2); % for loops xc=0.1*cos(t); yc=0.1*sin(t); % we sort the edges if ~isempty(E), E=[zeros(m,1),[1:m]',E]; % 1st column for change, 2nd column is edge number need2=find(E(:,4)<E(:,3)); % for replace v1<->v2 tmp=E(need2,3); E(need2,3)=E(need2,4); E(need2,4)=tmp; E(need2,1)=1; % 1, if v1<->v2 [e1,ie1]=sort(E(:,3)); % sort by 1st vertex E1=E(ie1,:); for k2=E1(1,3):E1(end,3), num2=find(E1(:,3)==k2); if ~isempty(num2), % sort by 2nd vertex E3=E1(num2,:); [e3,ie3]=sort(E3(:,4)); E4=E3(ie3,:); E1(num2,:)=E4; end end ip=find(E1(:,3)==E1(:,4)); % we find loops Ep=E1(ip,:); % loops E2=E1(setdiff([1:m],ip),:); % edges without loops end % we paint the graph hh=figure; hold on plot(V(:,1),V(:,2),'k.','MarkerSize',20) axis equal h1=get(gca); % handle of current figure if ~isempty(vkind1), % labels of vertexes for k=1:n, if wv==3, s=sprintf(vkind1,V(k,3)); else s=sprintf(vkind1,k); end hhh=text(V(k,1)+0.05,V(k,2)-0.07,s); % set(hhh,'FontName','Times New Roman Cyr','FontSize',18) end end % edges (arrows) if ~isempty(E), k=0; m2=size(E2,1); % number of edges without loops while k<m2, k=k+1; % current edge MyE=V(E2(k,3:4),1:2); % numbers of vertexes 1, 2 k1=1; % we find the multiple edges if k<m2, while all(E2(k,3:4)==E2(k+k1,3:4)), k1=k1+1; if k+k1>m2, break; end end end ry=r*[1:k1]; ry=ry-mean(ry); % radius l=norm(MyE(1,:)-MyE(2,:)); % lenght of line dx=MyE(2,1)-MyE(1,1); dy=MyE(2,2)-MyE(1,2); alpha=atan2(dy,dx); % angle of rotation cosa=cos(alpha); sina=sin(alpha); MyX=xr*l; for k2=1:k1, % we draw the edges (arrows) MyY=yr*ry(k2); MyXg=MyX*cosa-MyY*sina+MyE(1,1); MyYg=MyX*sina+MyY*cosa+MyE(1,2); plot(MyXg,MyYg,'k-'); if kind1=='d', % digraph with arrows if E2(k+k2-1,1)==1, [xa,ya]=CreateArrow(MyXg(1:2),MyYg(1:2)); fill(xa,ya,'k'); else [xa,ya]=CreateArrow(MyXg(end:-1:end-1),MyYg(end:-1:end-1)); fill(xa,ya,'k'); end end if ~isempty(ekind1), % labels of edges (arrows) if we==3, s=sprintf(ekind1,E2(k+k2-1,5)); else s=sprintf(ekind1,E2(k+k2-1,2)); end text(MyXg(length(MyXg)/2),MyYg(length(MyYg)/2),s); % set(hhh,'FontName','Times New Roman Cyr','FontSize',18) end end k=k+k1-1; end % we draw the loops k=0; ml=size(Ep,1); % number of loops while k<ml, k=k+1; % current loop MyV=V(Ep(k,3),1:2); % vertexes k1=1; % we find the multiple loops if k<ml, while all(Ep(k,3:4)==Ep(k+k1,3:4)), k1=k1+1; if k+k1>ml, break; end end end ry=[1:k1]+1; % radius for k2=1:k1, % we draw the loop MyX=xc*ry(k2)+MyV(1); MyY=(yc+r)*ry(k2)+MyV(2); plot(MyX,MyY,'k-'); if kind1=='d', [xa,ya]=CreateArrow(MyX([1 10]),MyY([1 10])); fill(xa,ya,'k'); end if ~isempty(ekind1), % labels of edges (arrows) if we==3, s=sprintf(ekind1,Ep(k+k2-1,5)); else s=sprintf(ekind1,Ep(k+k2-1,2)); end hhh=text(MyX(length(MyX)/2),MyY(length(MyY)/2),s); % set(hhh,'FontName','Times New Roman Cyr','FontSize',18) end end k=k+k1-1; end end hold off axis off if nargout==1, h=hh; end return function [xa,ya]=CreateArrow(x,y) % create arrow with length 0.1 with tip x(1), y(1) % and direction from x(2), y(2) xa1=[0 0.1 0.08 0.1 0]'; ya1=[0 0.03 0 -0.03 0]'; dx=diff(x); dy=diff(y); alpha=atan2(dy,dx); % angle of rotation cosa=cos(alpha); sina=sin(alpha); xa=xa1*cosa-ya1*sina+x(1); ya=xa1*sina+ya1*cosa+y(1); return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
motionTemplateDTWRetrievalWeightedForClassification.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/andreas_index/motionTemplateDTWRetrievalWeightedForClassification.m
6,951
utf_8
0614d3d29e83f4920081220ac178e43d
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Motion Retrieval via substring DTW based on motion templates % by Meinard Mueller, 10.11.2005 % % V n times p matrix, data stream of length n with p dimensional feature vectors % W m times p matrix, data stream of length n with p dimensional feature vectors % hits struct array, see below % costF 1 x p array containing the costs per feature % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hits,C,D,Delta, classificationDelta]=motionTemplateDTWRetrievalWeightedForClassification(V,Vweights,W,Wweights,parameter,varargin) di = [1 0 1]; dj = [1 1 0]; if (nargin>6) dj = varargin{2}; end if (nargin>5) di = varargin{1}; end if (nargin>7) dWeights = varargin{3}; else dWeights = ones(1,length(di)); end if (parameter.expandV==1) [V,Vweights] = expandWeightedVectorSequence(V,Vweights); end V = V'; W = W'; n = size(V,1); p = size(V,2); m = size(W,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Global cost matrix for matching i-th feature with j-th feature %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% V_0 = double(V==0)+double(V==0.5); V_1 = double(V==1)+double(V==0.5); C = V_1*W' + V_0*(1-W'); % #(concurrences) C = p-C; % #(disagreements) C = C/n; % disagreements per frame in V %C = C/(p*n); % disagreements per feature and frame in V %C = C_DTW_compute_C(V,W); % slower num_V_nonfuzzy = max(1,sum(V~=0.5,2)); C = C.*((repmat(Vweights',1,m)+repmat(Wweights,n,1))./(2*repmat(num_V_nonfuzzy,1,m))); %C = C.*((repmat(Vweights',1,m)+repmat(Wweights,n,1))/2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Computing optimal match by dynamic programming %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % tic; % D = zeros(n,m); % E = zeros(n,m); % % D(1,1) = C(1,1); % for i=2:n % D(i,1)=D(i-1,1)+C(i,1); % end % for j=2:m % D(1,j)=C(1,j); % end % % for i=2:n % for j=2:m % indices = sub2ind(size(D),max(i-di,1),max(j-dj,1)); % [val,E(i,j)] = min(D(indices)); % % D(i,j) = val + dWeights(E(i,j))*C(i,j); % end % end %%%%%%%% equivalent C code, improves efficiency by roughly a factor of 150 [D,E] = C_DTWpartial_compute_D_variablePathSteps(C,int32(di),int32(dj),dWeights); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %t=toc; fprintf('%f',t) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Matches %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Delta = D(n,:); match_numMax = parameter.match_numMax; match_thresh = parameter.match_thresh; hits = struct('file_id',0,... % file ID, index into idx.files 'file_name','',... 'cost',0,... 'match',0,... % num x 2 array encoding the matched indices 'frame_first_matched_all',0,... % the first frame of this hit (using a continuous frame count for the entire database) 'frame_last_matched_all',0,... % the last frame of this hit (using a continuous frame count for the entire database) 'frame_first_matched',0,... % the first frame of this hit 'frame_last_matched',0,... % the last frame of this hit 'frame_length',0); % the length of this hit measured in frames hits = repmat(hits,match_numMax,1); Delta_help = Delta; classificationDelta = inf*ones(1, length(Delta)); counter = 0; [cost,pos] = min(Delta_help); while counter<match_numMax && cost <= match_thresh i=n; j=pos; match_temp = zeros(max(n,m),2); k=0; while ((i>1) && (j>1)) k=k+1; match_temp(k,:)=[i j]; i2 = i - di(E(i,j)); j2 = j - dj(E(i,j)); i = i2; j = j2; end k = k+1; match_temp(k,:)=[i j]; while (i>1) i = i-1; k=k+1; match_temp(k,:)=[i j]; end match_temp = match_temp([1:k],:); match_temp = flipud(match_temp)'; %set all positions in the range of this hit to the value cost if %the value has not been set previously. positionsNotSet = (classificationDelta==inf); positionsMatch = false(1, length(positionsNotSet)); positionsMatch(match_temp(2,1):match_temp(2,end)) = true; % do a posewiese AND function of both masks to get the positions % where the new cost value may be set. classificationDelta(positionsNotSet & positionsMatch) = cost; counter = counter+1; %hits(counter).match = match_temp; hits(counter).frame_first_matched_all = match_temp(2,1); hits(counter).frame_last_matched_all = match_temp(2,end); hits(counter).cost = cost; current_match_length = match_temp(2,end)-match_temp(2,1)+1; % ind_start = match_temp(2,1); % ind_end = match_temp(2,end); %matches_length(ind_start:ind_end) = repmat(current_match_length,1,ind_end-ind_start+1); %matches_length(ind_start:ind_end) = counter; %pufferBackward = ceil(parameter.match_endExclusionBackward*current_match_length); %pufferForward = ceil(parameter.match_endExclusionForward*current_match_length); %ind_start = max(match_temp(2,end)-pufferBackward,1); %ind_end = min(match_temp(2,end)+pufferForward,m); pufferBackward = ceil(parameter.match_startExclusionBackward*current_match_length); pufferForward = ceil(parameter.match_endExclusionForward*current_match_length); ind_start = max(match_temp(2,1)-pufferBackward,1); ind_end = min(match_temp(2,end)+pufferForward,m); Delta_help(ind_start:ind_end)=Inf; [cost,pos] = min(Delta_help); end hits = hits(1:counter); if counter == match_numMax error('The maximum number of hits did not suffice.'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Visualizations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if parameter.visCost == 1 figure; set(gcf,'Position',[30 551 1210 398]); subplot(2,1,1) C_vis = C; C_vis(isnan(C_vis))=max(max(C_vis)); imagesc(C_vis); axis xy; colormap(hot); colorbar; D_vis = D; D_vis(isnan(D_vis))=max(max(D_vis)); subplot(2,1,2) imagesc(D_vis); axis xy; colormap(hot); colorbar; hold on; for k=1:length(hits) plot(hits(k).match(2,:),hits(k).match(1,:),'.c'); end % h=figure; % plot(Delta); % set(h,'position',[0 161 1275 229]); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
concatStringsInCell.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/andreas_index/concatStringsInCell.m
513
utf_8
5a8fec92a35f27858930bccd8617649a
% Thins function takes a cell array containing strings and conatenates the % strings using a '_' sign as a delemiter between the strings. % Example: Input: {'walkLeft', '4_30'} Output: 'walkLeft_4_30' function string = concatStringsInCell(stringcell) if (iscell(stringcell)) string = ''; for i=1:length(stringcell) if (i==1) string = stringcell{i}; else string = [string '_' stringcell{i}]; end end else string = stringcell; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
classifyDatabaseWithMotionTemplates.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/andreas_index/classifyDatabaseWithMotionTemplates.m
7,740
utf_8
d4a78f25c0effa86c848af83ad460228
% FUNCTION classifyDatabaseWithMotionTemplates searches the Motion Database % DB_name with the Feature set defined in feature_set for the motion % classes defined in motionClasses. It returns the positions in the % database where each motion class occurs. % INPUT: % DB_name: string: The name of the database that has previosly been calculated % with DB_index_precompute as a DB_concat_ file % feature_set: string: The name of the feature set that has been used to % extract the features for the DB_concat_ file. % motionClasses: A cell array containing strings. The strings are the % motion classes that this function searches for in the % DB_concat_ file. % indexbased: boolean value. If true, than the occurences of the % motion classes are determined on a database that has % previously been cut down by an indexing method. % maxHits: integer: don't return more than maxHits hits. % intendedTakeIndices: This is a vector containing the indices of all % files inside DB_name in which this function % should search for hits. Leave this argument out % of set it to [] if you want the whole DB_name % to be searched. % visualize: Set it to one if you want the database and results to be % visualized. Leave out or set to zero if no % visualization should be done. % % OUTPUT: % A cell array POSITIONS of dimension % size(POSITIONS)=[length(motionClasses),1]. % Each entry in POSITIONS is a vector v using the following contract: % v_n = POSITIONS(n,1) = [start1 end1 start2 end2 start3 end3 ... ] % The entries in v_n are the start- end end-frames of each occurence % of motionClasses{n} in the Database. function classPositions=classifyDatabaseWithMotionTemplates(DB_name, feature_set, motionClasses, indexbased, maxHits, intendedTakeIndices, visualize) global VARS_GLOBAL; % pre-allocate the cell array that will be returned classPositions=cell(length(motionClasses), 1); %define constants basedir_templates = fullfile('HDM05_EG08_cut_amc_training','_templates',''); downsampling_fac = 4; sampling_rate_string = num2str(120/downsampling_fac); settings = ['5_0_' sampling_rate_string]; %settings of the dtw-template feature_set_ranges = get_feature_set_ranges(feature_set); if nargin < 7 visualize = false; end % load the Database in which this function will search for the % motionClasses if (indexbased) [DB_concat,indexArray] = DB_index_load(DB_name,feature_set,downsampling_fac); else DB_concat = DB_index_load(DB_name,feature_set,downsampling_fac); % don't need index end % search the database for every motion class for k=1:length(motionClasses) category = motionClasses{k}; categoryName = concatStringsInCell(category); if indexbased %load the keyframes [motionTemplateKeyframes, motionTemplateKeyframePositions, motionTemplateKeyframesIndex, motionTemplateKeyframeDistances, stiffness, templateLength] = manualKeyframes(categoryName); extendLeft = 3*(motionTemplateKeyframePositions(1)); extendRight = 3*(templateLength - motionTemplateKeyframePositions(end) + 1); %cut down DB_concat using the keyframes %first find segments that fit to the keyframes if (visualize) [segments,framesTotalNum] = keyframeSearch(motionTemplateKeyframes,... motionTemplateKeyframesIndex,... diff(motionTemplateKeyframePositions),... stiffness,... indexArray, ... extendLeft, ... extendRight,... DB_concat); else [segments,framesTotalNum] = keyframeSearchEfficient(motionTemplateKeyframes,... motionTemplateKeyframesIndex,... diff(motionTemplateKeyframePositions),... stiffness,... indexArray, ... extendLeft, ... extendRight); end; %then cut down the database [DB_cut,segments_cut] = featuresCut(DB_concat,segments,indexArray,framesTotalNum,2); end %%%% load and threshold dtw-motion template [motionTemplateReal,motionTemplateWeights] = motionTemplateLoadMatfile(basedir_templates,categoryName,feature_set,settings); if (isempty(motionTemplateReal)) error(['Motion Template for category ' category ' could not be found.']); end param.thresh_lo = 0.1; param.thresh_hi = 1-param.thresh_lo; param.visBool = 0; param.visReal = 0; param.visBoolRanges = false; param.visRealRanges = false; param.feature_set_ranges = feature_set_ranges; param.feature_set = feature_set; param.flag = 0; [motionTemplate,weights] = motionTemplateBool(motionTemplateReal,motionTemplateWeights,param); %% compute matches with the motion template parameter.visCost = false; parameter.match_numMax = 500; parameter.match_thresh = 0.1; parameter.match_endExclusionForward = 0.1; parameter.match_endExclusionBackward = 0.5; parameter.match_startExclusionForward = 0.5; parameter.match_startExclusionBackward = 0.1; parameter.expandV = 1; if indexbased [hits,C,D,delta] = motionTemplateDTWRetrievalWeighted(... motionTemplate,weights,DB_cut.features,... ones(1,size(DB_cut.features,2)),... parameter,... [1 1 2],[1 2 1],[1 1 2]); %post process hits [hits_cut,hits] = hits_DTW_postprocessSegments(hits,DB_cut,segments_cut,DB_concat,segments); else [hits,C,D,delta] = motionTemplateDTWRetrievalWeighted(... motionTemplate,weights,DB_concat.features,... ones(1,size(DB_concat.features,2)),... parameter,... [1 1 2],[1 2 1],[1 1 2]); %post process hits hits = hits_DTW_postprocess(hits,DB_concat); end hits_num=(length(hits)); % now delete all hits that are outside of the intended takes if nargin > 5 && ~isempty(intendedTakeIndices) hitsIntended = zeros(1, hits_num); hitsIntendedCounter = 0; for h = 1:length(hits) if ~isempty(find(hits(h).file_id == intendedTakeIndices, 1)) hitsIntendedCounter = hitsIntendedCounter +1; hitsIntended(hitsIntendedCounter) = h; end end hitsIntended = hitsIntended(1:hitsIntendedCounter); if (indexbased) hits_cut = hits_cut(hitsIntended); end hits = hits(hitsIntended); end if (visualize) showHitsClickableRankingSegments(hits_cut,DB_cut,feature_set,feature_set_ranges,downsampling_fac); end hits_num = min(maxHits, length(hits)); positions=zeros(1, 2*hits_num); for n=1:hits_num positions(2*(n-1)+1) = hits(n).frame_first_matched_all; positions(2*n) = hits(n).frame_last_matched_all; end %classPositions{k} = positions; classPositions{k} = cell(hits_num,3); for n=1:hits_num classPositions{k}{n,1} = hits(n).file_name; classPositions{k}{n,2} = hits(n).frame_first_matched; classPositions{k}{n,3} = hits(n).frame_last_matched; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
subsets_all.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/andreas_index/subsets_all.m
968
utf_8
bfeb0bc672d4b913de565f8bfd730392
% FUNCTION SUBSETS_ALL: compute all subsets of a given set. % % subsets = subsets_all(set, max_subset_size) enerates all possible % subsets of the parameter set. % Set has to be an (1xN) cell array containing set elements. % Returned is a cell array subsets which contains all subsets % of set. Each subset is again encapsulated in an one-row cell array. % If max_subset_size is set only subsets of the length 1:max_subset_size % are computed. function subsets = subsets_all(set, max_subset_size) if (nargin < 2) max_subset_size = length(set); end subsets=cell(1,1); count = 1; for k=1:min(length(set), max_subset_size) combis=nchoosek(set, k); [num_combis,num_elements_per_combi]=size(combis); for l=1:num_combis combi=cell(1,num_elements_per_combi); for m=1:num_elements_per_combi combi{1,m}=combis{l,m}; end subsets{1,count}= combi; count = count+1; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
logical_and_sum.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/andreas_index/logical_and_sum.m
568
utf_8
f1057054570a5065e637754c4a09311a
%LOGICAL_AND_SUM And-sum of elemtens % S = LOGICAL_AND_SUM(X, DIM) is the sum of the elements of the vector X. % along the dimension DIM. X is a matrix, S is a row vector with the and-sum % over each column. % % Examples: % If X = [0 0 0 1 1 0.5; % 0 0.5 1 0.5 1 0.5] % % then logical_and_sum(X,1) is [0 0.5 0.5 0.5 1 0.5] % and sum(X,2) is [ 0.5; % 0.5 ] function res = logical_and_sum(input, dimension) res = sum(input, dimension)/size(input, dimension); res(res ~= 0 & res ~= 1) = 0.5;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
keyframesChooseLeastGrayValuesEquallyDistributed.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/andreas_index/keyframesChooseLeastGrayValuesEquallyDistributed.m
1,188
utf_8
69246bae9b424ce98751200c12b0b56a
% Divides the keyframe template into keyframesNumMax sections of equal % length. In each section the keyframe with the lease gray values will be % selected. function [keyframes,keyframesIndex] = keyframesChooseLeastGrayValuesEquallyDistributed(motionTemplate,motionTemplateWeights,par) irgnoreBorderPortion = 0.1; ignoredFrames = floor(size(motionTemplate, 2) * irgnoreBorderPortion); motionTemplate = motionTemplate(:,ignoredFrames+1:end-ignoredFrames); numFrames = size(motionTemplate,2); keyframes = zeros(1, par.keyframesNumMax); numGrayEntries = zeros(1,numFrames); numGrayEntries(1,:) = sum(motionTemplate==0.5,1); sectionLength = floor(numFrames / par.keyframesNumMax); currentFrame = 1; for k=1:par.keyframesNumMax-1 [numGrayEntriesSorted, sortIndex] = sort(numGrayEntries(currentFrame:currentFrame + (sectionLength-1))); keyframes(1, k) = currentFrame-1 + sortIndex(1) + ignoredFrames; currentFrame = currentFrame + sectionLength + 1; end [numGrayEntriesSorted, sortIndex] = sort(numGrayEntries(currentFrame:end)); keyframes(1, end) = currentFrame-1 + sortIndex(1) + ignoredFrames; keyframesIndex = ones(size(keyframes));
github
umariqb/3D_Pose_Estimation_CVPR2016-master
getRotation.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/skelfit/aguiarJointPos/getRotation.m
2,804
utf_8
41f226921f8d8c4830728f4c83ff0558
function A = getRotation( points1, points2) % % gives the rotation that maps p2 to p1 and q2 to q1 by rotating around rotCenter global VARS_GLOBAL; if isfield(VARS_GLOBAL, 'getRotationLastResult') lastResult = VARS_GLOBAL.getRotationLastResult; else lastResult = []; end startValue = [0 0 0]; LB = [0 0 0]; UB = [2*pi 2*pi 2*pi]; % OPTIONS = optimset('Diagnostics', 'off', 'Display', 'off', 'MaxIter', 10000, 'MaxFunEvals', 10000); OPTIONS = optimset('MaxFunEvals', 1500); % OPTIONS = []; % x = fmincon(@costFun, startValue, [], [], [], [], LB,UB, [], OPTIONS, [p1 q1 r1], [p2 q2 r2]); x = FMINSEARCH(@costFun, startValue, OPTIONS, points1, points2, lastResult); VARS_GLOBAL.getRotationLastResult = x; finalCosts = costFun(x, points1, points2, lastResult, true); A = buildRotMatrixXYZ(x(1), x(2), x(3)); % ------------------------------------------------------------------------------------------------------- function costs = costFun(x, points1, points2, lastResult, trackCosts) if nargin < 5 trackCosts = false; end if isempty(lastResult) devPenalty = 0; else devPenalty = 5*norm(lastResult - x); end % disp(devPenalty); A = buildRotMatrixXYZ(x(1), x(2), x(3)); p = A*points1; t = mean(points2 - p, 2); dist = 0; for i=1:size(points1,2) dist = dist + norm( p(:,i) + t - points2(:,i) ); end % dist = norm( p(:,1) + t - points2(:,1) ) + norm( p(:,2) + t - points2(:,2) ) + norm( p(:,3) + t - points2(:,3) ); costs = 0; for i=1:size(points1,2)-1 v = points2(:,i) - points2(:,i+1); w = p(:,i) - p(:,i+1); costs = costs - dot( v, w ) / norm(v) / norm(w); end % v1 = points2(:,1) - points2(:,2); % w1 = p(:,1) - p(:,2); % v2 = points2(:,1) - points2(:,3); % w2 = p(:,1) - p(:,3); % costs = - dot( v1, w1 ) / norm(v1) / norm(w1) - dot( v2, w2 ) / norm(v2) / norm(w2); global VARS_GLOBAL; if trackCosts if isfield(VARS_GLOBAL, 'getRotation_devPenalties') VARS_GLOBAL.getRotation_devPenalties(end+1) = devPenalty; else VARS_GLOBAL.getRotation_devPenalties = devPenalty; end if isfield(VARS_GLOBAL, 'getRotation_distCosts') VARS_GLOBAL.getRotation_distCosts(end+1) = dist; else VARS_GLOBAL.getRotation_distCosts = dist; end if isfield(VARS_GLOBAL, 'getRotation_angleCosts') VARS_GLOBAL.getRotation_angleCosts(end+1) = costs; else VARS_GLOBAL.getRotation_angleCosts = costs; end end if isfield(VARS_GLOBAL, 'getRotation_devPenaltyWeight') devPenaltyWeight = VARS_GLOBAL.getRotation_devPenaltyWeight; else devPenaltyWeight = 1.5; end costs = costs + 2*dist; costs = costs + devPenaltyWeight*devPenalty; % costs = - dot( points2(:,1) - points2(:,2), p(:,1) - p(:,2) ) - dot( points2(:,1) - points2(:,3), p(:,1) - p(:,3) ); % if costs < -1.5 % disp(costs); % end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
corcond.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/corcond.m
7,557
utf_8
ffe807511623eea9d4946f74601760ea
function [Consistency,G,stdG,Target]=corcond(X,Factors,Weights,Plot); %CORCOND Core consistency for PARAFAC model % % See also: % 'unimodal' 'monreg' 'fastnnls' % % CORe CONsistency DIAgnostics (corcondia) % Performs corcondia of a PARAFAC model and returns the cocote plot % as well as the degree of consistency (100 % is max). % % Consistency=corcond(X,Factors,Weights,Plot); % % INPUT % X : Data array % Factors : Factors given in standard format as a cell array % Weights : Optional weights (otherwise skip input or give an empty array []) % Plot = 0 or not given => no plots are produced % = 1 => normal corcondia plot % = 2 => corcondia plot with standard deviations % % OUTPUT % The core consistency given as the percentage of variation in a Tucker3 core % array consistent with the theoretical superidentity array. Max value is 100% % Consistencies well below 70-90% indicates that either too many components % are used or the model is otherwise mis-specified. % % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. % $ Version 1.02 $ Date 28. July 1998 $ Not compiled $ % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.01 $ Feb 2003 $ replaced regg with t3core when weights are used $ RB $ Not compiled $ DimX = size(X); X = reshape(X,DimX(1),prod(DimX(2:end))); Fac = size(Factors{1},2); if nargin<4 Plot=0; end if nargin<3 Weights=0; end ord=length(DimX); l_idx=0; for i=1:ord l_idx=[l_idx sum(DimX(1:i))*Fac]; end % Scale all loadings to same magnitude magn=ones(Fac,1); for i=1:ord L=Factors{i}; for f=1:Fac magn(f)=magn(f)*norm(L(:,f)); L(:,f)=L(:,f)/norm(L(:,f)); end Factors{i}=L; end % Magn holds the singular value of each component. Scale each loading vector by % the cubic root (if three-way) so all loadings of a component have the same variance magn = magn.^(1/ord); for i=1:ord L=Factors{i}; for f=1:Fac L(:,f)=L(:,f)*magn(f); end Factors{i}=L; end % Make diagonal array holding the magnitudes Ident=nident(Fac,ord); if Fac>1 DimIdent=ones(1,ord)*Fac; Ident=nshape(reshape(Ident,DimIdent),ord); end % Make matrix of Kronecker product of all loadings expect the large; Z = kron(C,B ... ) NewFac=[]; NewFacNo=[]; for i=ord:-1:1 Z=Factors{i}; % Check its of full rank or adjust core and use less columns rankZ=rank(Z); if rankZ<Fac %OLD out=Z(:,rankZ+1:Fac);Z=Z(:,1:rankZ);H=[[eye(rankZ)] pinv(Z)*out];Ident=H*Ident; [q,r]=qr(Z); Ident=r*Ident; Z=q; DimIdent(i)=size(r,1); end if i>1&Fac>1 Ident=nshape(reshape(Ident,DimIdent([i:ord 1:i-1])),ord); end NewFac{i}=Z; NewFacNo=[rankZ NewFacNo]; end Factors=NewFac; Fac=NewFacNo; if nargin<3 [G,stdG]=regg(reshape(X,DimX),Factors,Weights); %Doesn't work with weights else G=t3core(reshape(X,DimX),Factors,Weights); stdG = G; % Arbitrary (not used) end DimG = size(G); G = G(:); Ident=Ident(:); Target=Ident; [a,b]=sort(abs(Ident)); b=flipud(b); Ident=Ident(b); GG=G(b); stdGG=stdG(b); bNonZero=find(Ident); bZero=find(~Ident); ssG=sum(G(:).^2); Consistency=100*(1-sum((Target-G).^2)/ssG); if Plot clf Ver=version; Ver=Ver(1); if Fac>1 eval(['set(gcf,''Name'',''Diagonality test'');']); if Ver>4 plot([Ident(bNonZero);Ident(bZero)],'y','LineWidth',3) hold on plot(GG(bNonZero),'ro','LineWidth',3) plot(length(bNonZero)+1:prod(Fac),GG(bZero),'gx','LineWidth',3) if Plot==2 line([[1:length(G)];[1:length(G)]],[GG GG+stdGG]','LineWidth',1,'Color',[0 0 0]) line([[1:length(G)];[1:length(G)]],[GG GG-stdGG]','LineWidth',1,'Color',[0 0 0]) end hold off title(['Core consistency ',num2str(Consistency),'% (yellow target)'],'FontWeight','bold','FontSize',12) else plot([Ident(bNonZero);Ident(bZero)],'y') hold on plot(GG(bNonZero),'ro') plot(length(bNonZero)+1:prod(Fac),GG(bZero),'gx') if Plot==2 line([[1:length(G)];[1:length(G)]],[GG GG+stdGG]','LineWidth',1,'Color',[0 0 1]) line([[1:length(G)];[1:length(G)]],[GG GG-stdGG]','LineWidth',1,'Color',[0 0 1]) end hold off title(['Core consistency ',num2str(Consistency),'% (yellow target)']) end xlabel('Core elements (green should be zero/red non-zero)') ylabel('Core Size') else eval(['set(gcf,''Name'',''Diagonality test'');']); title(['Core consistency ',num2str(Consistency),'% (yellow target)']) xlabel('Core elements (green should be zero/red non-zero)') ylabel('Size') plot(GG(bNonZero),'ro') title(['Core consistency ',num2str(Consistency),'%']) xlabel('Core elements (red non-zero)') ylabel('Core Size') end end G = reshape(G,DimG); function [G,stdG]=regg(X,Factors,Weights); %REGG Calculate Tucker core % % Calculate Tucker3 core % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ DimX = size(X); X = reshape(X,DimX(1),prod(DimX(2:end))); Fac = size(Factors{1},2); ord=length(DimX); if ord<3 disp(' ') disp(' !!Corcondia only applicable for three- and higher-way arrays!!') return end if length(Fac)==1 for i=1:length(Factors) Fac(i) = size(Factors{i},2); end end vecX=X(:); % Vectorize X % Make sure Weights are defined (as ones if none given) if nargin<3 Weights=ones(size(X)); end if length(Weights(:))~=length(X(:)); Weights=ones(size(X)); end Weights=Weights(:); % Set weights of missing elements to zero id=find(isnan(vecX)); Weights(id)=zeros(size(id)); vecX(id)=zeros(size(id)); % Create Kronecker product of all but the last mode loadings L2 = Factors{end-1}; L1 = Factors{end-2}; Z = kron(L2,L1); for o=ord-3:-1:1 Z = kron(Z,Factors{o}); end % Make last mode loadings, L L=Factors{end}; % We want to fit the model ||vecX - Y*vecG||, where Y = kron(L,Z), but % we calculate Y'Y and Y'vecX by summing over k J=prod(DimX(1:ord-1)); Ytx = 0; YtY = 0; for k=1:DimX(ord) W=Weights((k-1)*J+1:k*J); WW=(W.^2*ones(1,prod(Fac))); Yk = kron(L(k,:),Z); Ytx = Ytx + Yk'*(W.*vecX((k-1)*J+1:k*J)); YtY = YtY + (Yk.*WW)'*Yk; end G=pinv(YtY)*Ytx; if nargout>1 se = (sum(vecX.^2) + G'*YtY*G -G'*Ytx); mse = se/(length(vecX)-length(G)); stdG=sqrt(diag(pinv(YtY))*mse); end G = reshape(G,Fac);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
npls.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/npls.m
47,188
utf_8
76fd53f195d27828c12b6d2e58d32537
function [Xfactors,Yfactors,Core,B,ypred,ssx,ssy,reg] = npls(X,Y,Fac,show); %NPLS multilinear partial least squares regression % % See also: % 'parafac' 'tucker' % % % MULTILINEAR PLS - N-PLS % % INPUT % X Array of independent variables % Y Array of dependent variables % Fac Number of factors to compute % % OPTIONAL % show If show = NaN, no outputs are given % % % OUTPUT % Xfactors Holds the components of the model of X in a cell array. % Use fac2let to convert the parameters to scores and % weight matrices. I.e., for a three-way array do % [T,Wj,Wk]=fac2let(Xfactors); % Yfactors Similar to Xfactors but for Y % Core Core array used for calculating the model of X % B The regression coefficients from which the scores in % the Y-space are estimated from the scores in the X- % space (U = TB); % ypred The predicted values of Y for one to Fac components % (array with dimension Fac in the last mode) % ssx Variation explained in the X-space. % ssx(f+1,1) is the sum-squared residual after first f factors. % ssx(f+1,2) is the percentage explained by first f factors. % ssy As above for the Y-space % reg Cell array with regression coefficients for raw (preprocessed) X % % % AUXILIARY % % If missing elements occur these must be represented by NaN. % % % [Xfactors,Yfactors,Core,B,ypred,ssx,ssy,reg] = npls(X,y,Fac); % or short % [Xfactors,Yfactors,Core,B] = npls(X,y,Fac); % % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. % $ Version 1.02 $ Date July 1998 $ Not compiled $ % $ Version 1.03 $ Date 4. December 1998 $ Not compiled $ Cosmetic changes % $ Version 1.04 $ Date 4. December 1999 $ Not compiled $ Cosmetic changes % $ Version 1.05 $ Date July 2000 $ Not compiled $ error caused weights not to be normalized for four-way and higher % $ Version 1.06 $ Date November 2000 $ Not compiled $ increase max it and decrease conv crit to better handle difficult data % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.01 $ June 2001 $ Changed to handle new core in X $ RB $ Not compiled $ % $ Version 2.02 $ January 2002 $ Outputs all predictions (1 - LV components) $ RB $ Not compiled $ % $ Version 2.03 $ March 2004 $ Changed initialization of u $ RB $ Not compiled $ % $ Version 2.04 $ Jan 2005 $ Modified sign conventions of scores and loads $ RB $ Not compiled $ if nargin==0 disp(' ') disp(' ') disp(' THE N-PLS REGRESSION MODEL') disp(' ') disp(' Type <<help npls>> for more info') disp(' ') disp(' [Xfactors,Yfactors,Core,B,ypred,ssx,ssy] = npls(X,y,Fac);') disp(' or short') disp(' [Xfactors,Yfactors,Core,B] = npls(X,y,Fac);') disp(' ') return elseif nargin<3 error(' The inputs X, y, and Fac must be given') end if ~exist('show')==1|nargin<4 show=1; end maxit=120; DimX = size(X); X = reshape(X,DimX(1),prod(DimX(2:end))); ordX = length(DimX);if ordX==2&size(X,2)==1;ordX = 1;end DimY = size(Y); Y = reshape(Y,DimY(1),prod(DimY(2:end))); ordY = length(DimY);if ordY==2&size(Y,2)==1;ordY = 1;end [I,Jx]=size(X); [I,Jy]=size(Y); missX=0; missy=0; MissingX = 0; MissingY = 0; if any(isnan(X(:)))|any(isnan(Y(:))) if any(isnan(X(:))) MissingX=1; else MissingX=0; end if any(isnan(Y(:))) MissingY=1; else MissingY=0; end if show~=0&~isnan(show) disp(' ') disp(' Don''t worry, missing values will be taken care of') disp(' ') end missX=abs(1-isnan(X)); missy=abs(1-isnan(Y)); end crit=1e-10; B=zeros(Fac,Fac); T=[]; U=[]; Qkron =[]; if MissingX SSX=sum(sum(X(find(missX)).^2)); else SSX=sum(sum(X.^2)); end if MissingY SSy=sum(sum(Y(find(missy)).^2)); else SSy=sum(sum(Y.^2)); end ssx=[]; ssy=[]; Xres=X; Yres=Y; xmodel=zeros(size(X)); Q=[]; W=[]; for num_lv=1:Fac %init % u=rand(DimX(1),1); Old version if size(Yres,2)==1 u = Yres; else [u] = pcanipals(Yres,1,0); end t=rand(DimX(1),1); tgl=t+2;it=0; while (norm(t-tgl)/norm(t))>crit&it<maxit tgl=t; it=it+1; % w=X'u [wloads,wkron] = Xtu(X,u,MissingX,missX,Jx,DimX,ordX); % t=Xw if MissingX for i=1:I, m = find(missX(i,:)); t(i)=X(i,m)*wkron(m)/(wkron(m)'*wkron(m)); end else t=X*wkron; end % w=X'u [qloads,qkron] = Xtu(Yres,t,MissingY,missy,Jy,DimY,ordY); % u=yq if MissingY for i=1:I m = find(missy(i,:)); u(i)=Yres(i,m)*qkron(m)/(qkron(m)'*qkron(m)); end else u=Yres*qkron; end end % % Fix signs % [Factors] = signswtch({t,wloads{:}},X); % t = Factors{1}; % wloads = Factors(2:end); % % Fix signs % [Factors] = signswtch({u,qloads{:}},X); % u = Factors{1}; % qloads = Factors(2:end); % Arrange t scores so they positively correlated with u cc = corrcoef([t u]); if sign(cc(2,1))<0 t = -t; for ii=1:length(wloads) wloads{ii}=-wloads{ii}; end end T=[T t]; for i = 1:ordX-1 if num_lv == 1 W{i} = wloads{i}; else W{i} = [W{i} wloads{i}]; end end U=[U u]; for i = 1:max(ordY-1,1) if num_lv == 1 Q{i} = qloads{i}; else Q{i} = [Q{i} qloads{i}]; end end Qkron = [Qkron qkron]; % Make core arrays if ordX>1 Xfac{1}=T;Xfac(2:ordX)=W; Core{num_lv} = calcore(reshape(X,DimX),Xfac,[],0,1); else Core{num_lv} = 1; end % if ordY>1 % Yfac{1}=U;Yfac(2:ordY)=Q; % Ycore{num_lv} = calcore(reshape(Y,DimY),Yfac,[],0,1); % else % Ycore{num_lv} = 1; % end B(1:num_lv,num_lv)=inv(T'*T)*T'*U(:,num_lv); if Jy > 1 if show~=0&~isnan(show) disp(' ') fprintf('number of iterations: %g',it); disp(' ') end end % Make X model if ordX>2 Wkron = kron(W{end},W{end-1}); else Wkron = W{end}; end for i = ordX-3:-1:1 Wkron = kron(Wkron,W{i}); end if num_lv>1 xmodel=T*reshape(Core{num_lv},num_lv,num_lv^(ordX-1))*Wkron'; else xmodel = T*Core{num_lv}*Wkron'; end % Make Y model % if ordY>2 % Qkron = kron(Q{end},Q{end-1}); % else % Qkron = Q{end}; % end % for i = ordY-3:-1:1 % Qkron = kron(Qkron,Q{i}); % end % if num_lv>1 % ypred=T*B(1:num_lv,1:num_lv)*reshape(Ycore{num_lv},num_lv,num_lv^(ordY-1))*Qkron'; % else % ypred = T*B(1:num_lv,1:num_lv)*Ycore{num_lv}*Qkron'; % end ypred=T*B(1:num_lv,1:num_lv)*Qkron'; Ypred(:,num_lv) = ypred(:); % Vectorize to avoid problems with different orders and the de-vectorize later on Xres=X-xmodel; Yres=Y-ypred; if MissingX ssx=[ssx;sum(sum(Xres(find(missX)).^2))]; else ssx=[ssx;sum(sum(Xres.^2))]; end if MissingY ssy=[ssy;sum(sum((Y(find(missy))-ypred(find(missy))).^2))]; else ssy=[ssy;sum(sum((Y-ypred).^2))]; end end ypred = reshape(Ypred',[size(Ypred,2) DimY]); ypred = permute(ypred,[2:ordY+1 1]); ssx= [ [SSX(1);ssx] [0;100*(1-ssx/SSX(1))]]; ssy= [ [SSy(1);ssy] [0;100*(1-ssy/SSy(1))]]; if show~=0&~isnan(show) disp(' ') disp(' Percent Variation Captured by N-PLS Model ') disp(' ') disp(' LV X-Block Y-Block') disp(' ---- ------- -------') ssq = [(1:Fac)' ssx(2:Fac+1,2) ssy(2:Fac+1,2)]; format = ' %3.0f %6.2f %6.2f'; for i = 1:Fac tab = sprintf(format,ssq(i,:)); disp(tab) end end Xfactors{1}=T; for j = 1:ordX-1 Xfactors{j+1}=W{j}; end Yfactors{1}=U; for j = 1:max(ordY-1,1) Yfactors{j+1}=Q{j}; end % Calculate regression coefficients that apply directly to X if nargout>7 if length(DimY)>2 error(' Regression coefficients are only calculated for models with vector Y or multivariate Y (not multi-way Y)') end R = outerm(W,0,1); for iy=1:size(Y,2) if length(DimX) == 2 dd = [DimX(2) 1]; else dd = DimX(2:end); end for i=1:Fac sR = R(:,1:i)*B(1:i,1:i)*diag(Q{1}(iy,1:i)); ssR = sum( sR',1)'; reg{iy,i} = reshape( ssR ,dd); end end end function [wloads,wkron] = Xtu(X,u,Missing,miss,J,DimX,ord); % w=X'u if Missing for i=1:J m = find(miss(:,i)); if (u(m)'*u(m))~=0 ww=X(m,i)'*u(m)/(u(m)'*u(m)); else ww=X(m,i)'*u(m); end if length(ww)==0 w(i)=0; else w(i)=ww; end end else w=X'*u; end % Reshape to array if length(DimX)>2 w_reshaped=reshape(w,DimX(2),prod(DimX(3:length(DimX)))); else w_reshaped = w(:); end % Find one-comp decomposition if length(DimX)==2 wloads{1} = w_reshaped/norm(w_reshaped); elseif length(DimX)==3&~any(isnan(w_reshaped)) [w1,s,w2]=svd(w_reshaped); wloads{1}=w1(:,1); wloads{2}=w2(:,1); else wloads=parafac(reshape(w_reshaped,DimX(2:length(DimX))),1,[0 2 0 0 NaN]'); for j = 1:length(wloads); wloads{j} = wloads{j}/norm(wloads{j}); end end % Apply sign convention for i = 1:length(wloads) sq = (wloads{i}.^2).*sign(wloads{i}); wloads{i} = wloads{i}*sign(sum(sq)); end % Unfold solution if length(wloads)==1 wkron = wloads{1}; else wkron = kron(wloads{end},wloads{end-1}); for o = ord-3:-1:1 wkron = kron(wkron,wloads{o}); end end function [Factors,it,err,corcondia]=parafac(X,Fac,Options,const,OldLoad,FixMode,Weights); % PARAFAC multiway parafac model % % See also: % 'npls' 'tucker' 'dtld' 'gram' % % % ___________________________________________________ % % THE PARAFAC MODEL % ___________________________________________________ % % [Factors,it,err,corcondia,Weights] = parafac(X,Fac,Options,const,OldLoad,FixMode,Weights); % % or skipping optional in/outputs % % Factors = parafac(X,Fac); % % Algorithm for computing an N-way PARAFAC model. Optionally % constraints can be put on individual modes for obtaining % orthogonal, nonnegative, or unimodal solutions. The algorithm % also handles missing data. For details of PARAFAC % modeling see R. Bro, Chemom. Intell. Lab. Syst., 1997. % % Several possibilities exist for speeding up the algorithm. % Compressing has been incorporated, so that large arrays can be % compressed by using Tucker (see Bro & Andersson, Chemom. % Intell. Lab. Syst., 1998). % Another acceleration method incorporated here is to % extrapolate the individual loading elements a number of % iterations ahead after a specified number of iterations. % % A temporary MAT-file called TEMP.mat is saved for every % 50 iterations. IF the computer breaks down or the model % seems to be good enough, one can break the program and % load the last saved estimate. The loadings in TEMP.MAT % are given a cell array as described below and can be % converted to A, B, C etc. by FAC2LET.M % % All loading vectors except in first mode are normalized, % so that all variance is kept in the first mode (as is % common in two-way PCA). The components are arranged as % in PCA. After iterating, the most important component is % made the first component etc. % % % % ----------------------INPUT--------------------- % % X X is the input array, which can be from three- to N-way (also % twoway if the third mode is interpreted as a onedimensional % mode). % % Fac No of factors/components sought. % % % ----------------OPTIONAL INPUT--------------------- % % Options Optional parameters. If not given or set to zero or [], % defaults will be used. If you want Options(5) to be 2 and % not change others, simply write Options(5)=2. Even if Options % hasn't been defined Options will contain zeros except its % fifth element. % % Options(1) - Convergence criterion % The relative change in fit for which the algorithm stops. % Standard is 1e-6, but difficult data might require a lower value. % % Options(2) - Initialization method % This option is ignored if PARAFAC is started with old values. % If no default values are given the default Options(2) is 0. % The advantage of using DTLD or SVD for initialization is that % they often provide good starting values. However, since the % initial values are then fixed, repeating the fitting will give % the exact same solution. Therefore it is not possible to substantiate % if a local minimum has been reached. To avoid that use an initialization % based on random values (2). % % 0 = fit using DTLD/GRAM for initialization (default if three-way and no missing) % 1 = fit using SVD vectors for initialization (default if higher than three-way or missing) % 2 = fit using random orthogonalized values for initialization % 10 = fit using the best-fitting models of several models % fitted using a few iterations % % Options(3) - Plotting options % 2=produces several graphical outputs (loadings shown during iterations) % 1=as above, but graphics only shown after convergence % 0=no plots % % Options(4) - Not user-accesible % % Options(5) - How often to show fit % Determines how often the deviation between the model and the data % is shown. This is helpful for adjusting the output to the number % of iterations. Default is 10. If showfit is set to NaN, almost no % outputs are given % % Options(6) - Maximal number of iterations % Maximal number of iterations allowed. Default is 2500. % % const A vector telling type of constraints put on the loadings of the % different modes. Same size as DimX but the i'th element tells % what constraint is on that mode. % 0 => no constraint, % 1 => orthogonality % 2 => nonnegativity % 3 => unimodality (and nonnegativitiy) % If const is not defined, no constraints are used. % For no constraints in a threeway problem const = [0 0 0] % % OldLoad If initial guess of the loadings is available. OldLoad should be % given a cell array where OldLoad{1}=A,OldLoad{2}=B etc. % % FixMode FixMode is a binary vector of same sixe as DimX. If % FixMode(i) = 1 => Mode i is fixed (requires old values given) % FixMode(i) = 0 => Mode i is not fixed hence estimated % Ex.: FixMode = [0 1 1] find the scores of a data set given the loadings. % When some modes are fixed, the numbering of the components will % also be fixed. Normally components are sorted according to variance % as in PCA, but this will not be performed if some modes are fixed. % % Weights If a matrix of the same size as X is given, weighted regression % is performed using the weights in the matrix Weights. % % ---------------------OUTPUT--------------------- % % Factors PARAFAC estimate of loadings in one matrix. For a 3 component % solution to a 4 x 3 x 3 array the loadings A, B & C will be % stored in a 3 element cell vector: % Factors{1}=A, % Factors{2}=B % Factors{3}=C % etc. % % Use FAC2LET.M for converting to "normal" output. % % it Number of iterations used. Can be helpful for checking if the algorithm % has converged or simply hit the maximal number of iterations (default 2500). % % err The fit of the model = the sum of squares of errors (not including missing % elements). % % Corcondia Core consistency test. Should ideally be 100%. If significantly below % 100% the model is not valid % % % % OTHER STUFF % % Missing values are handled by expectation maximization only. Set all % missing values to NaN % % COMMAND LINE (SHORT) % % Factors = parafac(X,Fac); % % Copyright, 1998 - % This M-file and the code in it belongs to the holder of the % copyrights and is made public under the following constraints: % It must not be changed or modified and code cannot be added. % The file must be regarded as read-only. Furthermore, the % code can not be made part of anything but the 'N-way Toolbox'. % In case of doubt, contact the holder of the copyrights. % % Rasmus Bro % Chemometrics Group, Food Technology % Department of Food and Dairy Science % Royal Veterinary and Agricultutal University % Rolighedsvej 30, DK-1958 Frederiksberg, Denmark % Phone +45 35283296 % Fax +45 35283245 % E-mail [email protected] % $ Version 1.03 $ Date 1. October 1998 $ Not compiled $ Changed sign-convention because of problems with centered data % $ Version 1.04 $ Date 18. February 1999 $ Not compiled $ Removed auxiliary line % $ Version 1.06 $ Date 1. December 1999 $ Not compiled $ Fixed bug in low fit error handling % $ Version 1.07 $ Date 17. January 2000 $ Not compiled $ Fixed bug in nnls handling so that the algorithm is not stopped until nonnegative appear % $ Version 1.08 $ Date 21. January 2000 $ Not compiled $ Changed init DTLD so that primarily negative loadings are reflected if possible % $ Version 1.09 $ Date 30. May 2000 $ Not compiled $ changed name noptioPF to noptiopf % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.001 $ June 2001 $ Fixed error in weighted regression $ RB $ Not compiled $ NumbIteraInitia=20; if nargin==0 disp(' ') disp(' ') disp(' THE PARAFAC MODEL') disp(' ') disp(' Type <<help parafac>> for more info') disp(' ') disp(' [Factors,it,err,Corcondia] = parafac(X,Fac,Options,const,OldLoad,FixMode,Weights);') disp(' or short') disp(' Factors = parafac(X,Fac);') disp(' ') disp(' Options=[Crit Init Plot NotUsed ShowFit MaxIt]') disp(' ') disp(' ') disp(' EXAMPLE:') disp(' To fit a four-component PARAFAC model to X of size 6 x 2 x 200 x 3 type') disp(' Factors=parafac(X,4)') disp(' and to obtain the scores and loadings from the output type') disp(' [A,B,C,D]=fac2let(Factors);') return elseif nargin<2 error(' The inputs X, and Fac must be given') end DimX = size(X); X = reshape(X,DimX(1),prod(DimX(2:end))); if nargin<3 load noptiopf OptionsDefault=Options; else % Call the current Options OptionsHere and load default to use if some of the current settings should be default Options=Options(:); I=length(Options); if I==0 Options=zeros(8,1); end I=length(Options); if I<8 Options=[Options;zeros(8-I,1)]; end OptionsHere=Options; load noptiopf OptionsDefault=Options; Options=OptionsHere; end if ~exist('OldLoad')==1 OldLoad=0; elseif length(OldLoad)==0 OldLoad=0; end % Convergence criteria if Options(1,1)==0 Options(1,1)=OptionsDefault(1,1); end crit=Options(1); % Initialization if ~any(Options(2)) Options(2)=OptionsDefault(2); end Init=Options(2); % Interim plotting Plt=Options(3,1); if ~any([0 1 2]==Plt) error(' Options(3,1) - Plotting - not set correct; must be 0,1, or 2') end if Options(5,1)==0 Options(5,1)=OptionsDefault(5,1); end showfit=Options(5,1); if isnan(showfit) showfit=-1; end if showfit<-1|round(showfit)~=showfit error(' Options(5,1) - How often to show fit - not set correct; must be positive integer or -1') end if Options(6,1)==0 Options(6,1)=OptionsDefault(6,1); maxit=Options(6,1); elseif Options(6)>0&round(Options(6))==Options(6) maxit=Options(6,1); else error(' Options(6,1) - Maximal number of iterations - not set correct; must be positive integer') end ShowPhi=0; % Counter. Tuckers congruence coef/Multiple cosine/UUC shown every ShowPhiWhen'th time the fit is shown ShowPhiWhen=10; MissConvCrit=1e-4; % Convergence criterion for estimates of missing values NumberOfInc=0; % Counter for indicating the number of iterations that increased the fit. ALS algorithms ALLWAYS decrease the fit, but using outside knowledge in some sense (approximate equality or iteratively reweighting might cause the algorithm to diverge % INITIALIZE if showfit~=-1 disp(' ') disp(' PRELIMINARY') disp(' ') end ord=length(DimX); if showfit~=-1 disp([' A ',num2str(Fac),'-component model will be fitted']) end if exist('const')~=1 const=zeros(size(DimX)); elseif length(const)~=ord const=zeros(size(DimX)); if showfit~=-1 disp(' Constraints are not given properly') end end if showfit~=-1 for i=1:ord if const(i)==0 disp([' No constraints on mode ',num2str(i)]) elseif const(i)==1 disp([' Orthogonality on mode ',num2str(i)]) elseif const(i)==2 disp([' Nonnegativity on mode ',num2str(i)]) elseif const(i)==3 disp([' Unimodality on mode ',num2str(i)]) end end end % Check if orthogonality required on all modes if max(max(const))==1 if min(min(const))==1,disp(' ') disp(' Not possible to orthogonalize all modes in this implementation.') error(' Contact the authors for further information') end end if exist('FixMode')==1 if length(FixMode)~=ord FixMode = zeros(1,ord); end else FixMode = zeros(1,ord); end if showfit~=-1 if any(FixMode) disp([' The loadings of mode : ',num2str(find(FixMode(:)')),' are fixed']) end end if exist('Weights')~=1 Weights=[]; end % Display convergence criterion if showfit~=-1 disp([' The convergence criterion is ',num2str(crit)]) end % Define loading as one ((r1*r2*r3*...*r7)*Fac x 1) vector [A(:);B(:);C(:);...]. % The i'th loading goes from lidx(i,1) to lidx(i,2) lidx=[1 DimX(1)*Fac]; for i=2:ord lidx=[lidx;[lidx(i-1,2)+1 sum(DimX(1:i))*Fac]]; end % Check if weighted regression required if size(Weights,1)==size(X,1)&prod(size(Weights))/size(X,1)==size(X,2) Weights = reshape(Weights,size(Weights,1),prod(size(Weights))/size(X,1)); if showfit~=-1 disp(' Given weights will be used for weighted regression') end DoWeight=1; else if showfit~=-1 disp(' No weights given') end DoWeight=0; end % Make idx matrices if missing values if any(isnan(X(:))) MissMeth=1; else MissMeth=0; end if MissMeth id=sparse(find(isnan(X))); idmiss2=sparse(find(~isnan(X))); if showfit~=-1 disp([' ', num2str(100*(length(id)/prod(DimX))),'% missing values']); disp(' Expectation maximization will be used for handling missing values') end SSX=sum(sum(X(idmiss2).^2)); % To be used for evaluating the %var explained % If weighting to zero should be used % Replace missing with mean values or model estimates initially if length(OldLoad)==sum(DimX)*Fac model=nmodel(OldLoad); model = reshape(model,DimX); X(id)=model(id); else meanX=mean(X(find(~isnan(X)))); meanX=mean(meanX); X(id)=meanX*ones(size(id)); end else if showfit~=-1 disp(' No missing values') end SSX=sum(sum(X.^2)); % To be used for evaluating the %var explained end % Check if weighting is tried used together with unimodality or orthogonality if any(const==3)|any(const==1) if DoWeight==1 disp(' ') disp(' Weighting is not possible together with unimodality and orthogonality.') disp(' It can be done using majorization, but has not been implemented here') disp(' Please contact the authors for further information') error end end % Acceleration acc=-5; do_acc=1; % Do acceleration every do_acc'th time acc_pow=2; % Extrapolate to the iteration^(1/acc_pow) ahead acc_fail=0; % Indicate how many times acceleration have failed max_fail=4; % Increase acc_pow with one after max_fail failure if showfit~=-1 disp(' Line-search acceleration scheme initialized') end % Find initial guesses for the loadings if no initial values are given % Use old loadings if length(OldLoad)==ord % Use old values if showfit~=-1 disp(' Using old values for initialization') end Factors=OldLoad; % Use DTLD elseif Init==0 if min(DimX)>1&ord==3&MissMeth==0 if showfit~=-1 disp(' Using direct trilinear decomposition for initialization') end [A,B,C]=dtld(reshape(X,DimX),Fac); A=real(A);B=real(B);C=real(C); % Check for signs and reflect if appropriate for f=1:Fac if sign(sum(A(:,f)))<0 if sign(sum(B(:,f)))<0 B(:,f)=-B(:,f); A(:,f)=-A(:,f); elseif sign(sum(C(:,f)))<0 C(:,f)=-C(:,f); A(:,f)=-A(:,f); end end if sign(sum(B(:,f)))<0 if sign(sum(C(:,f)))<0 C(:,f)=-C(:,f); B(:,f)=-B(:,f); end end end Factors{1}=A;Factors{2}=B;Factors{3}=C; else if showfit~=-1 disp(' Using singular values for initialization') end Factors=ini(X,Fac,2); end % Use SVD elseif Init==1 if showfit~=-1 disp(' Using singular values for initialization') end Factors=ini(X,Fac,2); % Use random (orthogonal) elseif Init==2 if showfit~=-1 disp(' Using orthogonal random for initialization') end Factors=ini(X,Fac,1); elseif Init==3 error(' Initialization option set to three has been changed to 10') % Use several small ones of the above elseif Init==10 if showfit~=-1 disp(' Using several small runs for initialization') end Opt=Options; Opt(5) = NaN; Opt(6) = NumbIteraInitia; Opt(2) = 0; ERR=[]; [Factors,it,err] = parafac(X,Fac,Opt,const,[],[],Weights); ERR = [ERR;err]; Opt(2) = 1; [F,it,Err] = parafac(X,Fac,Opt,const,[],[],Weights); ERR=[ERR;Err]; if Err<err Factors=F; err=Err; end Opt(2)=2; for rep=1:3 [F,it,Err]=parafac(X,Fac,Opt,const,[],[],Weights); ERR=[ERR;Err]; if Err<err Factors=F; err=Err; end end if showfit~=-1 disp(' ') disp(' Obtained fit-values') disp([' Method Fit']) disp([' DTLD ',num2str(ERR(1))]) disp([' SVD ',num2str(ERR(2))]) disp([' RandOrth ',num2str(ERR(3))]) disp([' RandOrth ',num2str(ERR(4))]) disp([' RandOrth ',num2str(ERR(5))]) end else error(' Problem in PARAFAC initialization - Not set correct') end % Convert to old format ff = []; for f=1:length(Factors) ff=[ff;Factors{f}(:)]; end Factors = ff; % ALTERNATING LEAST SQUARES err=SSX; f=2*crit; it=0; connew=2;conold=1; % for missing values ConstraintsNotRight = 0; % Just to ensure that iterations are not stopped if constraints are not yet fully imposed if showfit~=-1 disp(' ') disp(' Sum-of-Squares Iterations Explained') disp(' of residuals variation') end while ((f>crit) | (norm(connew-conold)/norm(conold)>MissConvCrit) | ConstraintsNotRight) & it<maxit conold=connew; % for missing values it=it+1; acc=acc+1; if acc==do_acc; Load_o1=Factors; end if acc==do_acc+1; acc=0;Load_o2=Factors; Factors=Load_o1+(Load_o2-Load_o1)*(it^(1/acc_pow)); % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end model=nmodel(ff); model = reshape(model,DimX(1),prod(DimX(2:end))); if MissMeth connew=model(id); errX=X-model; if DoWeight==0 nerr=sum(sum(errX(idmiss2).^2)); else nerr=sum(sum((Weights(idmiss2).*errX(idmiss2)).^2)); end else if DoWeight==0 nerr=sum(sum((X-model).^2)); else nerr=sum(sum((X.*Weights-model.*Weights).^2)); end end if nerr>err acc_fail=acc_fail+1; Factors=Load_o2; if acc_fail==max_fail, acc_pow=acc_pow+1+1; acc_fail=0; if showfit~=-1 disp(' Reducing acceleration'); end end else if MissMeth X(id)=model(id); end end end if DoWeight==0 for ii=ord:-1:1 if ii==ord; i=1; else i=ii+1; end idd=[i+1:ord 1:i-1]; l_idx2=lidx(idd,:); dimx=DimX(idd); if ~FixMode(i) L1=reshape(Factors(l_idx2(1,1):l_idx2(1,2)),dimx(1),Fac); if ord>2 L2=reshape(Factors(l_idx2(2,1):l_idx2(2,2)),dimx(2),Fac); Z=kr(L2,L1); else Z = L1; end for j=3:ord-1 L1=reshape(Factors(l_idx2(j,1):l_idx2(j,2)),dimx(j),Fac); Z=kr(L1,Z); end ZtZ=Z'*Z; ZtX=Z'*X'; OldLoad=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); L=pfls(ZtZ,ZtX,DimX(i),const(i),OldLoad,DoWeight,Weights); Factors(lidx(i,1):lidx(i,2))=L(:); end x=zeros(prod(DimX([1:ii-1 ii+1:ord])),DimX(ii)); % Rotate X so the current last mode is the first x(:)=X; X=x'; end else for ii=ord:-1:1 if ii==ord; i=1; else i=ii+1; end idd=[i+1:ord 1:i-1]; l_idx2=lidx(idd,:); dimx=DimX(idd); if ~FixMode(i) L1=reshape(Factors(l_idx2(1,1):l_idx2(1,2)),dimx(1),Fac); if ord>2 L2=reshape(Factors(l_idx2(2,1):l_idx2(2,2)),dimx(2),Fac); Z=kr(L2,L1); else Z = L1; end for j=3:ord-1 L1=reshape(Factors(l_idx2(j,1):l_idx2(j,2)),dimx(j),Fac); Z=kr(L1,Z); end OldLoad=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); L=pfls(Z,X,DimX(i),const(i),OldLoad,DoWeight,Weights); Factors(lidx(i,1):lidx(i,2))=L(:); end x=zeros(prod(DimX([1:ii-1 ii+1:ord])),DimX(ii)); x(:)=X; X=x'; x(:)=Weights; Weights=x'; end end % EVALUATE SOFAR % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac); ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac); id1 = id2; end model=nmodel(ff); model = reshape(model,DimX(1),prod(DimX(2:end))); if MissMeth % Missing values present connew=model(id); X(id)=model(id); errold=err; errX=X-model; if DoWeight==0 err=sum(sum(errX(idmiss2).^2)); else err=sum(sum((Weights(idmiss2).*errX(idmiss2)).^2)); end else errold=err; if DoWeight==0 err=sum(sum((X-model).^2)); else err=sum(sum((Weights.*(X-model)).^2)); end end if err<1000*eps, % Getting close to the machine uncertainty => stop disp(' WARNING') disp(' The misfit is approaching the machine uncertainty') disp(' If pure synthetic data is used this is OK, otherwise if the') disp(' data elements are very small it might be appropriate ') disp(' to multiply the whole array by a large number to increase') disp(' numerical stability. This will only change the solution ') disp(' by a scaling constant') f = 0; else f=abs((err-errold)/err); if f<crit % Convergence: then check that constraints are fulfilled if any(const==2)|any(const==3) % If nnls or unimodality imposed for i=1:ord % Extract the if const(i)==2|const(i)==3 % If nnls or unimodality imposed Loadd = Factors(sum(DimX(1:i-1))*Fac+1:sum(DimX(1:i))*Fac); if any(Loadd<0) ConstraintsNotRight=1; else ConstraintsNotRight=0; end end end end end end if it/showfit-round(it/showfit)==0 if showfit~=-1, ShowPhi=ShowPhi+1; if ShowPhi==ShowPhiWhen, ShowPhi=0; if showfit~=-1, disp(' '), disp(' Tuckers congruence coefficient'), % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end [phi,out]=ncosine(ff,ff); disp(phi), if MissMeth fprintf(' Change in estim. missing values %12.10f',norm(connew-conold)/norm(conold)); disp(' ') disp(' ') end disp(' Sum-of-Squares Iterations Explained') disp(' of residuals variation') end end if DoWeight==0 PercentExpl=100*(1-err/SSX); else PercentExpl=100*(1-sum(sum((X-model).^2))/SSX); end fprintf(' %12.10f %g %3.4f \n',err,it,PercentExpl); if Plt==2 % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end pfplot(reshape(X,DimX),ff,Weights',[0 0 0 0 0 0 0 1]); drawnow end end end % Make safety copy of loadings and initial parameters in temp.mat if it/50-round(it/50)==0 save temp Factors end % JUDGE FIT if err>errold NumberOfInc=NumberOfInc+1; end end % while f>crit % CALCULATE TUCKERS CONGRUENCE COEFFICIENT if showfit~=-1 & DimX(1)>1 disp(' '),disp(' Tuckers congruence coefficient') % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end [phi,out]=ncosine(ff,ff); disp(phi) disp(' ') if max(max(abs(phi)-diag(diag(phi))))>.85 disp(' ') disp(' ') disp(' WARNING, SOME FACTORS ARE HIGHLY CORRELATED.') disp(' ') disp(' You could decrease the number of components. If this') disp(' does not help, try one of the following') disp(' ') disp(' - If systematic variation is still present you might') disp(' wanna decrease your convergence criterion and run') disp(' one more time using the loadings as initial guess.') disp(' ') disp(' - Or use another preprocessing (check for constant loadings)') disp(' ') disp(' - Otherwise try orthogonalising some modes,') disp(' ') disp(' - Or use Tucker3/Tucker2,') disp(' ') disp(' - Or a PARAFAC with some modes collapsed (if # modes > 3)') disp(' ') end end % SHOW FINAL OUTPUT if DoWeight==0 PercentExpl=100*(1-err/SSX); else PercentExpl=100*(1-sum(sum((X-model).^2))/SSX); end if showfit~=-1 fprintf(' %12.10f %g %3.4f \n',err,it,PercentExpl); if NumberOfInc>0 disp([' There were ',num2str(NumberOfInc),' iterations that increased fit']); end end % POSTPROCES LOADINGS (ALL VARIANCE IN FIRST MODE) A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); for i=2:ord B=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); for ff=1:Fac A(:,ff)=A(:,ff)*norm(B(:,ff)); B(:,ff)=B(:,ff)/norm(B(:,ff)); end Factors(lidx(i,1):lidx(i,2))=B(:); end Factors(lidx(1,1):lidx(1,2))=A(:); if showfit~=-1 disp(' ') disp(' Components have been normalized in all but the first mode') end % PERMUTE SO COMPONENTS ARE IN ORDER AFTER VARIANCE DESCRIBED (AS IN PCA) IF NO FIXED MODES if ~any(FixMode) A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); [out,order]=sort(diag(A'*A)); order=flipud(order); A=A(:,order); Factors(lidx(1,1):lidx(1,2))=A(:); for i=2:ord B=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); B=B(:,order); Factors(lidx(i,1):lidx(i,2))=B(:); end if showfit~=-1 disp(' Components have been ordered according to contribution') end elseif showfit ~= -1 disp(' Some modes fixed hence no sorting of components performed') end % APPLY SIGN CONVENTION IF NO FIXED MODES % FixMode=1 if ~any(FixMode)&~(any(const==2)|any(const==3)) Sign = ones(1,Fac); for i=ord:-1:2 A=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); Sign2=ones(1,Fac); for ff=1:Fac [out,sig]=max(abs(A(:,ff))); Sign(ff) = Sign(ff)*sign(A(sig,ff)); Sign2(ff) = sign(A(sig,ff)); end A=A*diag(Sign2); Factors(lidx(i,1):lidx(i,2))=A(:); end A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); A=A*diag(Sign); Factors(lidx(1,1):lidx(1,2))=A(:); if showfit~=-1 disp(' Components have been reflected according to convention') end end % TOOLS FOR JUDGING SOLUTION if nargout>3 x=X; if MissMeth x(id)=NaN*id; end % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end corcondia=corcond(reshape(x,DimX),ff,Weights,1); end if Plt==1|Plt==2 % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end pfplot(reshape(X,DimX),ff,Weights,ones(1,8)); end % Show which criterion stopped the algorithm if showfit~=-1 if ((f<crit) & (norm(connew-conold)/norm(conold)<MissConvCrit)) disp(' The algorithm converged') elseif it==maxit disp(' The algorithm did not converge but stopped because the') disp(' maximum number of iterations was reached') elseif f<eps disp(' The algorithm stopped because the change in fit is now') disp(' smaller than the machine uncertainty.') else disp(' Algorithm stopped for some mysterious reason') end end % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end Factors = ff; function [A,B,C,fit]=dtld(X,F,SmallMode); %DTLD direct trilinear decomposition % % See also: % 'gram', 'parafac' % % Copyright, 1998 - % This M-file and the code in it belongs to the holder of the % copyrights and is made public under the following constraints: % It must not be changed or modified and code cannot be added. % The file must be regarded as read-only. Furthermore, the % code can not be made part of anything but the 'N-way Toolbox'. % In case of doubt, contact the holder of the copyrights. % % Rasmus Bro % Chemometrics Group, Food Technology % Department of Food and Dairy Science % Royal Veterinary and Agricultutal University % Rolighedsvej 30, DK-1958 Frederiksberg, Denmark % Phone +45 35283296 % Fax +45 35283245 % E-mail [email protected] % % % DIRECT TRILINEAR DECOMPOSITION % % calculate the parameters of the three- % way PARAFAC model directly. The model % is not the least-squares but will be close % to for precise data with little model-error % % This implementation works with an optimal % compression using least-squares Tucker3 fitting % to generate two pseudo-observation matrices that % maximally span the variation of all samples. per % default the mode of smallest dimension is compressed % to two samples, while the remaining modes are % compressed to dimension F. % % For large arrays it is fastest to have the smallest % dimension in the first mode % % INPUT % [A,B,C]=dtld(X,F); % X is the I x J x K array % F is the number of factors to fit % An optional parameter may be given to enforce which % mode is to be compressed to dimension two % % Copyright 1998 % Rasmus Bro, KVL % [email protected] % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 1.02 $ Date 28. July 1998 $ Not compiled $ % $ Version 1.03 $ Date 25. April 1999 $ Not compiled $ DimX = size(X); X = reshape(X,DimX(1),prod(DimX(2:end))); DontShowOutput = 1; %rearrange X so smallest dimension is in first mode if nargin<4 [a,SmallMode] = min(DimX); X = nshape(reshape(X,DimX),SmallMode); DimX = DimX([SmallMode 1:SmallMode-1 SmallMode+1:3]); Fac = [2 F F]; else X = nshape(reshape(X,DimX),SmallMode); DimX = DimX([SmallMode 1:SmallMode-1 SmallMode+1:3]); Fac = [2 F F]; end f=F; if F==1; Fac = [2 2 2]; f=2; end if DimX(1) < 2 error(' The smallest dimension must be > 1') end if any(DimX(2:3)-Fac(2:3)<0) error(' This algorithm requires that two modes are of dimension not less the number of components') end % Compress data into a 2 x F x F array. Only 10 iterations are used since exact SL fit is insignificant; only obtaining good truncated bases is important [Factors,Gt]=tucker(reshape(X,DimX),Fac,[0 0 0 0 NaN 10]); % Convert to old format Gt = reshape(Gt,size(Gt,1),prod(size(Gt))/size(Gt,1)); [At,Bt,Ct]=fac2let(Factors); % Fit GRAM to compressed data [Bg,Cg,Ag]=gram(reshape(Gt(1,:),f,f),reshape(Gt(2,:),f,f),F); % De-compress data and find A BB = Bt*Bg; CC = Ct*Cg; AA = X*pinv(kr(CC,BB)).'; if SmallMode == 1 A=AA; B=BB; C=CC; elseif SmallMode == 2 A=BB; B=AA; C=CC; elseif SmallMode == 3 A=BB; B=CC; C=AA; end fit = sum(sum(abs(X - AA*kr(CC,BB).').^2)); if ~DontShowOutput disp([' DTLD fitted raw data with a sum-squared error of ',num2str(fit)]) end function mwa = outerm(facts,lo,vect) if nargin < 2 lo = 0; end if nargin < 3 vect = 0; end order = length(facts); if lo == 0 mwasize = zeros(1,order); else mwasize = zeros(1,order-1); end k = 0; for i = 1:order if i ~= lo [m,n] = size(facts{i}); k = k + 1; mwasize(k) = m; if k > 1 if nofac ~= n error('All orders must have the same number of factors') end else nofac = n; end end end mwa = zeros(prod(mwasize),nofac); for j = 1:nofac if lo ~= 1 mwvect = facts{1}(:,j); for i = 2:order if lo ~= i %mwvect = kron(facts{i}(:,j),mwvect); mwvect = mwvect*facts{i}(:,j)'; mwvect = mwvect(:); end end elseif lo == 1 mwvect = facts{2}(:,j); for i = 3:order %mwvect = kron(facts{i}(:,j),mwvect); mwvect = mwvect*facts{i}(:,j)'; mwvect = mwvect(:); end end mwa(:,j) = mwvect; end % If vect isn't one, sum up the results of the factors and reshape if vect ~= 1 mwa = sum(mwa,2); mwa = reshape(mwa,mwasize); end function [t,p,Mean,Fit,RelFit] = pcanipals(X,F,cent); % NIPALS-PCA WITH MISSING ELEMENTS % 20-6-1999 % % Calculates a NIPALS PCA model. Missing elements % are denoted NaN. The solution is nested % % Comparison for data with missing elements % NIPALS : Nested , not least squares, not orthogonal solutoin % LSPCA : Non nested, least squares , orthogonal solution % % I/O % [t,p,Mean,Fit,RelFit] = pcanipals(X,F,cent); % % X : Data with missing elements set to NaN % F : Number of componets % cent: One if centering is to be included, else zero % % Copyright % Rasmus Bro % KVL 1999 % [email protected] % [I,J]=size(X); if any(sum(isnan(X))==I)|any(sum(isnan(X)')==J) error(' One column or row only contains missing') end Xorig = X; Miss = isnan(X); NotMiss = ~isnan(X); ssX = sum(X(find(NotMiss)).^2); Mean = zeros(1,J); if cent Mean = nanmean(X); end X = X - ones(I,1)*Mean; t=[]; p=[]; for f=1:F Fit = 3; OldFit = 6; it = 0; T = nanmean(X')'; P = nanmean(X)'; Fit = 2; FitOld = 3; while abs(Fit-FitOld)/FitOld>1e-7 & it < 1000; FitOld = Fit; it = it +1; for j = 1:J id=find(NotMiss(:,j)); P(j) = T(id)'*X(id,j)/(T(id)'*T(id)); end P = P/norm(P); for i = 1:I id=find(NotMiss(i,:)); T(i) = P(id)'*X(i,id)'/(P(id)'*P(id)); end Fit = X-T*P'; Fit = sum(Fit(find(NotMiss)).^2); end t = [t T]; p = [p P]; X = X - T*P'; end Model = t*p' + ones(I,1)*Mean; Fit = sum(sum( (Xorig(find(NotMiss)) - Model(find(NotMiss))).^2)); RelFit = 100*(1-Fit/ssX); function y = nanmean(x) if isempty(x) % Check for empty input. y = NaN; return end nans = isnan(x); i = find(nans); x(i) = zeros(size(i)); if min(size(x))==1, count = length(x)-sum(nans); else count = size(x,1)-sum(nans); end i = find(count==0); count(i) = ones(size(i)); y = sum(x)./count; y(i) = i + NaN;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
ncrossreg.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/ncrossreg.m
10,030
utf_8
c21e18a1fc80e44cb6fd7fcc43873fdb
function [XValResult,Model]=ncrossreg(X,y,MaxFac,Centering,SegmentsID); %NCROSSREG cross-validation of regression model % % See also: % 'ncrossdecomp' % % CROSS-VALIDATION OF BI- & MULTILINEAR REGRESSION MODELS % Performs cross-validation of % - NPLS Input multi-way array X % - PLS Input two-way X % % The data are by default centered across the first mode, but no scaling % is applied (this must be done beforehand) % % I/O % [XValResult,Model]=ncrossreg(X,y,MaxFac,Centering); % % INPUT % X : X array % y : y array % MaxFac : Maximal number of factors (from one to MaxFac factors will be investigated) % % OPTIONAL INPUT % Centering : If not zero, centering is performed on every segment % SegmentsID: Optional binary matrix. Rows as rows in X and i'th column defines i'th segment % Rows in i'th column set to one are left out at % % OUTPUT % XValResult % Structured array with the following elements % ypred : Cross-validated predictions % ssX_Xval : Cross-validated sum of squares of residuals in X (f'th element for f-component model) % ssX_Fit : Fitted sum of squares of residuals in X (f'th element for f-component model) % ssY_Xval : Cross-validated sum of squares of residuals in Y (f'th element for f-component model) % ssY_Fit : Fitted sum of squares of residuals in Y (f'th element for f-component model) % Percent : Structured array holding Xexp and Yexp, each with fitted and X-validated % Variance captured. % PRESS : Predicted REsidual Sum of Squares in Y % RMSEP : Root Mean Square Error of Prediction (cross-validation) % % Model % Structured array holding the NPLS model % $ Version 1.0301 $ Date 26. June 1999 % $ Version 1.0302 $ Date 1. January 2000 % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.01 $ jan 2003 $ Added option for skipping centering and added percentages in output $ RB $ Not compiled $ % $ Version 2.02 $ Sep 2003 $ Fixed bug in non-center option $ RB $ Not compiled $ % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. I = size(X,1); DimX = size(X); DimY = size(y); X = reshape(X,DimX(1),prod(DimX(2:end))); y = reshape(y,DimY(1),prod(DimY(2:end))); Ypred = zeros([MaxFac DimY]); Ex = zeros([MaxFac DimX]); Ey = zeros([MaxFac DimY]); if nargin<4 Centering = 1; elseif isempty(Centering) Centering = 1; end %%%%%%%%%%%%%%%%% %%MAKE SEGMENTS%% %%%%%%%%%%%%%%%%% if exist('SegmentsID')~=1 SegmentsID = MakeSegments(I); end %%%%%%%%%%%%%%%%%%% %%MAKE SUB-MODELS%% %%%%%%%%%%%%%%%%%%% for i=1:size(SegmentsID,2) In = find(~SegmentsID(:,i)); Out = find(SegmentsID(:,i)); % Offsets if Centering Mx = nanmean(X(In,:)); My = nanmean(y(In,:)); else Mx = zeros(1,prod(DimX(2:end))); My = zeros(1,prod(DimY(2:end))); end %Centered data Xc = X(In,:)-repmat(Mx,length(In),1); yc = y(In,:)-repmat(My,length(In),1); % %Centered data % Xc = X(In,:)-ones(length(In),1)*Mx; % yc = y(In,:)-ones(length(In),1)*My; % Calculate model DimXc = DimX;DimXc(1)=size(Xc,1); Xc = reshape(Xc,DimXc); DimYc = DimY;DimYc(1)=size(yc,1); yc = reshape(yc,DimYc); [Xfactors,Yfactors,Core,B] = npls(Xc,yc,MaxFac,NaN); %Predict left-out samples for f=1:MaxFac Xc = X(Out,:)-ones(length(Out),1)*Mx; DimXc = DimX; DimXc(1)=size(Xc,1); Xc = reshape(Xc,DimXc); [ypr,T,ssx,Xres] = npred(Xc,f,Xfactors,Yfactors,Core,B,NaN); Ex(f,Out,:) = reshape(Xres,DimXc(1),prod(DimXc(2:end))); Ypred(f,Out,:) = ypr+ones(length(Out),1)*My; Ypredf = squeeze(Ypred(f,:,:)); if size(y,2) == 1 YpredfOut=Ypredf(Out); else YpredfOut=Ypredf(Out,:); end %size(Ey(f,Out,:)),size(y(Out,:)),size(YpredfOut) if size(y,2)==1 Ey(f,Out,:) = squeeze(y(Out,:))'-squeeze(YpredfOut); else Ey(f,Out,:) = squeeze(y(Out,:))-squeeze(YpredfOut); end end end if Centering Mx = nanmean(X(In,:)); My = nanmean(y(In,:)); else Mx = zeros(1,prod(DimX(2:end))); My = zeros(1,prod(DimY(2:end))); end %Centered data Xc = X-repmat(Mx,size(X,1),1); yc = y-repmat(My,size(y,1),1); %%Centered data %Xc = X-ones(I,1)*Mx; %yc = y-ones(I,1)*My; [Xfactors,Yfactors,Core,B,ypred,ssx,ssy] = npls(reshape(Xc,DimX),reshape(yc,DimY),MaxFac,NaN); Model.Xfactors = Xfactors; Model.Yfactors = Yfactors; Model.Core = Core; Model.B = B; Model.Yfitted = ypred; Model.MeanX = Mx; Model.MeanY = My; sseX_fit = ssx(2:end,1); sseY_fit = ssy(2:end,1); for f=1:MaxFac id=find(~isnan(Ex(f,:)));sseX_xval(f) = sum(Ex(f,id).^2); id=find(~isnan(Ey(f,:)));sseY_xval(f) = sum(Ey(f,id).^2); PRESS(f) = sum(Ey(f,id).^2); end RMSEP = sqrt(PRESS/I); Xval = [sseX_fit sseX_xval']; Yval = [sseY_fit sseY_xval']; Xval = 100*(1-Xval/sum(Xc(find(~isnan(X))).^2)); Yval = 100*(1-Yval/sum(yc(find(~isnan(y))).^2)); XValResult.ypred = Ypred; XValResult.ssX_Xval = sseX_xval; XValResult.ssX_Fit = sseX_fit'; XValResult.ssY_Xval = sseY_xval; XValResult.ssY_Fit = sseY_fit'; XValResult.Percent.Xexp = Xval; XValResult.Percent.Yexp = Yval; XValResult.PRESS = PRESS; XValResult.RMSEP = RMSEP; XValResult.DefSegments = sparse(SegmentsID); disp(' ') disp(' Percent Variance Captured by N-PLS Model ') disp(' ') disp(' -----X-Block----- -----Y-Block-----') disp(' LV # Fitted Xval Fitted Xval RMSEP') disp(' ---- ------- ------- ------- ------- ---------') format = ' %3.0f %6.2f %6.2f %6.2f %6.2f %6.4f'; for f = 1:MaxFac tab = sprintf(format,[f Xval(f,:) Yval(f,:) RMSEP(f)]); disp(tab) end disp(' ') function SegmentsID = MakeSegments(I); XvalMeth=questdlg('Which type of validation do you want to perform (ENTER => full Xval)?','Choose validation','Full X-validation','Segmented','Prespecified','Full X-validation'); switch XvalMeth case 'Full X-validation' SegmentsID = speye(I); case 'Segmented' prompt={'Enter the number of segments:'}; eval(['def={''',num2str(min(I,max(3,round(I/7)))),'''};']) dlgTitle='Number of segments'; lineNo=1; answer=inputdlg(prompt,dlgTitle,lineNo,def); NumbSegm=eval(answer{1}); % Make sure the number of segments is OK while NumbSegm<2|NumbSegm>I prompt={'INCONSISTENT NUMBER CHOSEN (must be > 1 and <= samples)'}; eval(['def={''',num2str(min(I,max(3,round(I/7)))),'''};']) dlgTitle='Number of segments'; lineNo=1; answer=inputdlg(prompt,dlgTitle,lineNo,def); NumbSegm=eval(answer{1}) NumbSegm<2|NumbSegm>I end XvalSegm=questdlg('How should segments be chosen?','Choose segmentation','111222333...','123123123...','Random','123123123...'); switch XvalSegm case '111222333...' SegmentsID = sparse(I,NumbSegm); NumbInEachSegm = floor(I/NumbSegm); Additional = I-NumbInEachSegm*NumbSegm; currentsample = 1; for i=1:NumbSegm if i <=Additional add = NumbInEachSegm+1; elseif i<NumbSegm add = NumbInEachSegm; else add = I-currentsample+1; end SegmentsID(currentsample:currentsample+add-1,i)=1; currentsample = currentsample + add; end case '123123123...' SegmentsID = sparse(I,NumbSegm); NumbInEachSegm = floor(I/NumbSegm); for i=1:NumbSegm SegmentsID(i:NumbSegm:end,i)=1; end case 'Random' % Make nonrandom and then randomize order SegmentsID = sparse(I,NumbSegm); NumbInEachSegm = floor(I/NumbSegm); for i=1:NumbSegm SegmentsID(i:NumbSegm:end,i)=1; end rand('state',sum(100*clock)) %Randomize randomizer [a,b] = sort(rand(I,1)) SegmentsID = SegmentsID(b,:); end case 'Prespecified' prompt={'Enter the name of the file defining the subsets'}; def={'SegmentsID'}; dlgTitle='Import definition'; lineNo=1; answer=inputdlg(prompt,dlgTitle,lineNo,def); SegmentsID=eval(answer{1}); end % switch function y = nanmean(x) %NANMEAN Average or mean ignoring NaNs. % NANMEAN(X) returns the average treating NaNs as missing values. % For vectors, NANMEAN(X) is the mean value of the non-NaN % elements in X. For matrices, NANMEAN(X) is a row vector % containing the mean value of each column, ignoring NaNs. % % See also NANMEDIAN, NANSTD, NANMIN, NANMAX, NANSUM. % Copyright (c) 1993-98 by The MathWorks, Inc. % $Revision: 2.8 $ $Date: 1997/11/29 01:45:53 $ if isempty(x) % Check for empty input. y = NaN; return end % Replace NaNs with zeros. nans = isnan(x); i = find(nans); x(i) = zeros(size(i)); if min(size(x))==1, count = length(x)-sum(nans); else count = size(x,1)-sum(nans); end % Protect against a column of all NaNs i = find(count==0); count(i) = ones(size(i)); y = sum(x)./count; y(i) = i + NaN;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
ncrossdecomp.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/ncrossdecomp.m
15,317
utf_8
aa69c33f01ff76b0ed5fc30a7729b342
function XvalResult = ncrossdecomp(Method,X,FacMin,FacMax,Segments,Cent,Show); %NCROSSDECOMP crossvalidation of PARAFAC/Tucker/PCA % % See also: % 'ncrossreg' % % This file performs cross-validation of decomposition models % PARAFAC, PCA, and Tucker. The cross-validation is performed % such that part of the data are set to missing, the model is % fitted to the remaining data, and the residuals between fitted % and true left-out elements is calculated. This is performed % 'Segments' times such that all elements are left out once. % The segments are chosen by taking every 'Segments' element of % X(:), i.e. from the vectorized array. If X is of size 5 x 7, % and three segemnts are chosen ('Segments' = 3), then in the % first of three models, the model is fitted to the matrix % % |x 0 0 x 0 0 x| % |0 x 0 0 x 0 0| % |0 0 x 0 0 x 0| % |x 0 0 x 0 0 x| % |0 x 0 0 x 0 0| % % where x's indicate missing elements. After fitting the residuals % in the locations of missing values are calculated. After fitting % all three models, all residuals have been calculated. % % Note that the number of segments must be chosen such that no columns % or rows contain only missing elements (the algorithm will check this). % Using 'Segments' = 7, 9, or 13 will usually achieve that. % % I/O % XvalResult = ncrossdecomp(Method,X,FacMin,FacMax,Segments,Cent,Show); % % INPUT % Method : 'parafac', 'tucker', 'pca', or 'nipals' % For PCA the least squares model is calculated. % Thus, offsets and parameters are calculated in % a least squares sense unlike the method NIPALS, % which calculates the PCA model using an ad hoc % approach for handling missing data (as in % standard chemometric software). % X : Multi-way array of data % FacMin : Lowest number of factors to use % FacMax : Highest number of factors (note that for Tucker only models % with the same number of components in each mode are % calculated currently % Segments : The number of segments to use. Try many! % Cent : If set of one, the data are centered across samples, % i.e. ordinary centering. Note, however, that the centering % is not performed in a least squares sense but as preprocessing. % This is not optimal because the data have missing data because % of the way the elements are left out. This can give % significantly lower fit than reasonable if you have few samples % or use few segments. Alternatively, you can center the data % beforehand and perform cross-validation on the centered data % Show : If set to 0, no plot is given % % OUTPUT % Structure XvalResult holding: % Fit: The fitted percentage of variation explaind (as a % function of component number) % Xval: The cross-validated percentage of variation explaind % (as a function of component number) % FittedModel: The fitted model (as a function of component number) % XvalModel: The cross-validated model (as a function of component number) % % To visualize the output type "tucktest(XvalResult);" % $ Version 1.0301 $ Date 28. June 1999 $ Not compiled $ % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.01 $ Mar 2002 $ Fixed error in segmentation check $ RB $ Not compiled $ % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. % uses NANSUM, DimX = size(X); ord = length(DimX); X = reshape(X,DimX(1),prod(DimX(2:end))); [I,J] = size(X); if exist('Show')~=1 Show = 1; end if strcmp(lower(Method(1:3)),'tuc') if length(FacMin)==1 FacMin = ones(1,ord)*FacMin; elseif length(FacMin)~=ord error('Error in FacMin: When fitting Tucker models, the number of factors should be given for each mode') end if length(FacMax)==1 FacMax = ones(1,ord)*FacMax; elseif length(FacMax)~=ord error('Error in FacMax: When fitting Tucker models, the number of factors should be given for each mode') end end % Check if the selected segmentation works (does not produce rows/columns of only missing) out = ones(I,J); out(1:Segments:end)=NaN; out2 = ones(size(X)); out(find(isnan(out2))) = NaN; if any(sum(isnan(out))==I) error(' The chosen segmentation leads to columns of only missing elements') elseif any(sum(isnan(out'))==J) error(' The chosen segmentation leads to rows of only missing elements') end if ~strcmp(lower(Method(1:3)),'tuc') XvalResult.Fit = zeros(FacMax,2)*NaN; XvalResult.Xval = zeros(FacMax,2)*NaN; for f = 1:FacMin-1 XvalResult.XvalModel{f} = 'Not fitted'; XvalResult.FittedModel{f} = 'Not fitted'; end for f = FacMin:FacMax % Fitted model disp([' Total model - Comp. ',num2str(f),'/',num2str(FacMax)]) [M,Mean,Param] = decomp(Method,X,DimX,f,1,Segments,Cent,I,J); Model = M + ones(I,1)*Mean'; id = find(~isnan(X)); OffsetCorrectedData = X - ones(I,1)*Mean'; XvalResult.Fit(f,:) = [100*(1 - sum( (X(id) - Model(id)).^2)/sum(OffsetCorrectedData(id).^2)) f]; XvalResult.FittedModel{f} = Model; % Xvalidated Model of data ModelXval = zeros(I,J)*NaN; for s = 1:Segments disp([' Segment ',num2str(s),'/',num2str(Segments),' - Comp. ',num2str(f),'/',num2str(FacMax)]) Xnow = X; Xnow(s:Segments:end) = NaN; [M,Mean] = decomp(Method,Xnow,DimX,f,s,Segments,Cent,I,J,Param); model = M + ones(I,1)*Mean'; ModelXval(s:Segments:end) = model(s:Segments:end); end XvalResult.Xval(f,:) = [100*(1 - sum( (X(id) - ModelXval(id)).^2)/sum(OffsetCorrectedData(id).^2)) f]; XvalResult.XvalModel{f} = ModelXval; XvalResult.Factors(f)=f; end else % Do Tucker model % Find all PossibleNumber = [min(FacMin):max(FacMax)]'*ones(1,ord); possibleCombs = unique(nchoosek(PossibleNumber(:),ord),'rows'); %remove useless f2 = []; for f1 = 1:size(possibleCombs,1) if (prod(possibleCombs(f1,:))/max(possibleCombs(f1,:)))<max(possibleCombs(f1,:)) % Check that the largest mode is larger than the product of the other f2 = [f2;f1]; elseif any(possibleCombs(f1,:)>FacMax) % Chk the model is desired, f2 = [f2;f1]; end end possibleCombs(f2,:)=[]; [f1,f2]=sort(sum(possibleCombs')); possibleCombs = [possibleCombs(f2,:) f1']; XvalResult.Fit = zeros(size(possibleCombs,1),ord+1)*NaN; XvalResult.Xval = zeros(size(possibleCombs,1),ord+1)*NaN; for f = 1:size(possibleCombs,1) XvalResult.XvalModel{f} = 'Not fitted'; XvalResult.FittedModel{f} = 'Not fitted'; end for f1 = 1:size(possibleCombs,1) % Fitted model disp([' Total model - Comp. ',num2str(possibleCombs(f1,1:end-1)),'/',num2str(FacMax)]) [M,Mean,Param] = decomp(Method,X,DimX,possibleCombs(f1,1:end-1),1,Segments,Cent,I,J); Model = M + ones(I,1)*Mean'; id = find(~isnan(X)); OffsetCorrectedData = X - ones(I,1)*Mean'; XvalResult.Fit(f1,:) = [100*(1 - sum( (X(id) - Model(id)).^2)/sum(OffsetCorrectedData(id).^2)) possibleCombs(f1,1:end-1)]; XvalResult.FittedModel{f1} = Model; % Xvalidated Model of data ModelXval = zeros(I,J)*NaN; for s = 1:Segments disp([' Segment ',num2str(s),'/',num2str(Segments),' - Comp. ',num2str(possibleCombs(f1,1:end-1)),'/',num2str(FacMax)]) Xnow = X; Xnow(s:Segments:end) = NaN; [M,Mean] = decomp(Method,Xnow,DimX,possibleCombs(f1,1:end-1),s,Segments,Cent,I,J,Param); model = M + ones(I,1)*Mean'; ModelXval(s:Segments:end) = model(s:Segments:end); end XvalResult.Xval(f1,:) = [100*(1 - sum( (X(id) - ModelXval(id)).^2)/sum(OffsetCorrectedData(id).^2)) possibleCombs(f1,1:end-1)]; XvalResult.XvalModel{f1} = ModelXval; XvalResult.Factors{f1}=possibleCombs(f1,1:end-1); end end if Show&FacMin-FacMax~=0 if Method(1:3) == 'pca' Nam = 'PCA'; elseif Method(1:3) == 'tuc' Nam = 'Tucker'; elseif Method(1:3) == 'par' Nam = 'PARAFAC'; elseif Method(1:3) == 'nip' Nam = 'NIPALS'; end figure save jjj if lower(Method(1:3))~='tuc' bar(FacMin:FacMax,[XvalResult.Fit(FacMin:FacMax,1) XvalResult.Xval(FacMin:FacMax,1)],.76,'grouped') else % extract the ones with lowest Xval fit (for each # total comp) for plotting fx = []; f5 =[]; for f1 = 1:max(possibleCombs(:,end)) f2 = find(possibleCombs(:,end)==f1); if length(f2) [f3,f4] = max(XvalResult.Xval(f2)); f5 = [f5,f2(f4)]; end end fx = [possibleCombs(f5,end) XvalResult.Fit(f5,1) XvalResult.Xval(f5,1)]; bar(fx(:,1),fx(:,2:3),.76,'grouped') for f1 = 1:size(fx,1) f6=text(fx(f1,1),95,['[',num2str(possibleCombs(f5(f1),1:end-1)),']']); set(f6,'Rotation',270) end end g=get(gca,'YLim'); set(gca,'YLim',[max(-20,g(1)) 100]) legend('Fitted','Xvalidated',0) titl = ['Xvalidation results (',Nam,')']; if Cent titl = [titl ,' - centering']; else titl = [titl ,' - no centering']; end title(titl,'FontWeight','Bold') xlabel('Total number of components') ylabel('Percent variance explained') end function [M,Mean,parameters] = decomp(Method,X,DimX,f,s,Segments,Cent,I,J,parameters); Conv = 0; it = 0; maxit = 500; % Initialize if Cent Mean = nanmean(X)'; else Mean = zeros(J,1); end if lower(Method(1:3)) == 'par' Xc = reshape(X- ones(I,1)*Mean',DimX); if exist('parameters')==1 fact = parafac(Xc,f,[1e-5 10 0 0 NaN maxit],[],parameters.fact); else fact = parafac(Xc,f,[1e-5 10 0 0 NaN maxit]); end M = reshape(nmodel(fact),DimX(1),prod(DimX(2:end))); parameters.fact=fact; elseif lower(Method(1:3)) == 'tuc' Xc = reshape(X- ones(I,1)*Mean',DimX); if exist('parameters')==1 [fact,G] = tucker(Xc,f,[1e-2 0 0 0 NaN maxit],[],[],parameters.fact,parameters.G); else [fact,G] = tucker(Xc,f,[1e-2 0 0 0 NaN maxit]); end parameters.fact=fact; parameters.G=G; M = reshape(nmodel(fact,G),DimX(1),prod(DimX(2:end))) ; elseif lower(Method) == 'nip' Xc = reshape(X- ones(I,1)*Mean',DimX(1),prod(DimX(2:end))); [t,p] = pcanipals(X- ones(I,1)*Mean',f,0); parameters.t=t; parameters.p=p; M = t*p'; elseif lower(Method) == 'pca' Xc = reshape(X- ones(I,1)*Mean',DimX(1),prod(DimX(2:end))); [t,p] = pcals(X- ones(I,1)*Mean',f,0); parameters.t=t; parameters.p=p; M = t*p'; else error(' Name of method not recognized') end Fit = X - M - ones(I,1)*Mean'; Fit = sum(Fit(find(~isnan(X))).^2); % Iterate while ~Conv it = it+1; FitOld = Fit; % Fit multilinear part Xcent = X - ones(I,1)*Mean'; if Method(1:3) == 'par' fact = parafac(reshape(Xcent,DimX),f,[1e-2 0 0 0 NaN maxit],[],fact); M = reshape(nmodel(fact),DimX(1),prod(DimX(2:end))); elseif Method(1:3) == 'tuc' [fact,G] = tucker(reshape(Xcent,DimX),f,[1e-2 0 0 0 NaN maxit],[0 0 0],zeros(size(G)),fact,G); M = reshape(nmodel(fact,G),DimX(1),prod(DimX(2:end))); elseif Method == 'pca' [t,p] = pcals(Xcent,f,0,t,p,0); M = t*p'; elseif Method == 'nip' [t,p] = pcanipals(Xcent,f,0); M = t*p'; end % Find offsets if Cent x = X; mm=M+ones(I,1)*Mean'; x(find(isnan(X)))=mm(find(isnan(X))); Mean = mean(x)'; end %Find fit Fit = X - M - ones(I,1)*Mean'; Fit = sum(Fit(find(~isnan(X))).^2); if abs(Fit-FitOld)/FitOld<1e-8 | it > 1500 Conv = 1; end end disp([' Fit ',num2str(Fit),' using ',num2str(it),' it.']) function [t,p] = pcals(X,F,cent,t,p,show); % LEAST SQUARES PCA WITH MISSING ELEMENTS % 20-6-1999 % % Calculates a least squares PCA model. Missing elements % are denoted NaN. The solution is NOT nested, so one has % to calculate a new model for each number of components. ShowMeFitEvery = 20; MaxIterations = 5; [I,J]=size(X); Xorig = X; Miss = find(isnan(X)); NotMiss = find(~isnan(X)); m = t*p'; X(Miss) = m(Miss); ssX = sum(X(NotMiss).^2); Fit = 3; OldFit = 6; it = 0; while abs(Fit-OldFit)/OldFit>1e-3 & it < MaxIterations; it = it +1; OldFit = Fit; [t,s,p] = svds(X,F); t = t*s; Model = t*p'; X(Miss) = Model(Miss); Fit = sum(sum( (Xorig(NotMiss) - Model(NotMiss)).^2)); if ~rem(it,ShowMeFitEvery)&show disp([' Fit after ',num2str(it),' it. :',num2str(RelFit),'%']) end end function [t,p,Mean] = pcanipals(X,F,cent); % NIPALS-PCA WITH MISSING ELEMENTS % cent: One if centering is to be included, else zero [I,J]=size(X); rand('state',sum(100*clock)) Xorig = X; Miss = isnan(X); NotMiss = ~isnan(X); ssX = sum(X(find(NotMiss)).^2); Mean = zeros(1,J); if cent Mean = nanmean(X); end X = X - ones(I,1)*Mean; t=[]; p=[]; for f=1:F Fit = 3; OldFit = 6; it = 0; T = rand(I,1); P = rand(J,1); Fit = 2; FitOld = 3; while abs(Fit-FitOld)/FitOld>1e-7 & it < 100; FitOld = Fit; it = it +1; for j = 1:J try id=find(NotMiss(:,j)); if length(id)==0 id,end P(j) = T(id)'*X(id,j)/(T(id)'*T(id)); catch P(j) = 0; end end P = P/norm(P); for i = 1:I id=find(NotMiss(i,:)); T(i) = P(id)'*X(i,id)'/(P(id)'*P(id)); end Fit = X-T*P'; Fit = sum(Fit(find(NotMiss)).^2); end t = [t T]; p = [p P]; X = X - T*P'; end function Xc = nanmean(X) if isempty(X) Xc = NaN; return end i = isnan(X); j = find(i); i = sum(i); X(j) = 0; Num = size(X,1)-i; Xc = sum(X); i = find(Num); Xc(i) = Xc(i)./Num(i); Xc(find(~Num))=NaN;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
parafac.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/parafac.m
38,334
utf_8
3fea3384f1be9f57e339fa8f93e3ba4d
function [Factors,it,err,corcondia]=parafac(X,Fac,Options,const,OldLoad,FixMode,Weights); % PARAFAC multiway parafac model % % See also: % 'npls' 'tucker' 'dtld' 'gram' % % % ___________________________________________________ % % THE PARAFAC MODEL % ___________________________________________________ % % [Factors,it,err,corcondia] = parafac(X,Fac,Options,const,OldLoad,FixMode,Weights); % % or skipping optional in/outputs % % Factors = parafac(X,Fac); % % Algorithm for computing an N-way PARAFAC model. Optionally % constraints can be put on individual modes for obtaining % orthogonal, nonnegative, or unimodal solutions. The algorithm % also handles missing data. For details of PARAFAC % modeling see R. Bro, Chemom. Intell. Lab. Syst., 1997. % % Several possibilities exist for speeding up the algorithm. % Compressing has been incorporated, so that large arrays can be % compressed by using Tucker (see Bro & Andersson, Chemom. % Intell. Lab. Syst., 1998). % Another acceleration method incorporated here is to % extrapolate the individual loading elements a number of % iterations ahead after a specified number of iterations. % % A temporary MAT-file called TEMP.mat is saved for every % 50 iterations. IF the computer breaks down or the model % seems to be good enough, one can break the program and % load the last saved estimate. The loadings in TEMP.MAT % are given a cell array as described below and can be % converted to A, B, C etc. by FAC2LET.M typing % [A,B,C]=fac2let(Factors,size(X)); % % All loading vectors except in first mode are normalized, % so that all variance is kept in the first mode (as is % common in two-way PCA). The components are arranged as % in PCA. After iterating, the most important component is % made the first component etc. % % % % ----------------------INPUT--------------------- % % X X is the input array, which can be from three- to N-way (also % twoway if the third mode is interpreted as a onedimensional % mode). % % Fac No of factors/components sought. % % % ----------------OPTIONAL INPUT--------------------- % % Options Optional parameters. If not given or set to zero or [], % defaults will be used. If you want Options(5) to be 2 and % not change others, simply write Options(5)=2. Even if Options % hasn't been defined Options will contain zeros except its % fifth element. % % Options(1) - Convergence criterion % The relative change in fit for which the algorithm stops. % Standard is 1e-6, but difficult data might require a lower value. % % Options(2) - Initialization method % This option is ignored if PARAFAC is started with old values. % If no default values are given the default Options(2) is 0. % The advantage of using DTLD or SVD for initialization is that % they often provide good starting values. However, since the % initial values are then fixed, repeating the fitting will give % the exact same solution. Therefore it is not possible to substantiate % if a local minimum has been reached. To avoid that use an initialization % based on random values (2). % % 0 = fit using DTLD/GRAM for initialization (default if % three-way and no missing and if sizes are % largere than number of factors at least % in two modes) % 1 = fit using SVD vectors for initialization (default if higher than three-way or missing) % 2 = fit using random orthogonalized values for initialization % 10 = fit using the best-fitting models of several models % fitted using a few iterations % % Options(3) - Plotting options % 0 = no plots % 1 = produces several graphical outputs % 2 = produces several graphical outputs (loadings also shown during iterations) % 3 = as 2 but no core consistency check (very slow for large arrays and/or many components) % % Options(4) - Scaling % 0 or 1 = default scaling (columns in mode one carry the variance) % 2 = no scaling applied (hence fixed elements will not be modified % % Options(5) - How often to show fit % Determines how often the deviation between the model and the data % is shown. This is helpful for adjusting the output to the number % of iterations. Default is 10. If showfit is set to NaN, almost no % outputs are given % % Options(6) - Maximal number of iterations % Maximal number of iterations allowed. Default is 2500. % % const A vector telling type of constraints put on the loadings of the % different modes. Same size as DimX but the i'th element tells % what constraint is on that mode. % 0 => no constraint, % 1 => orthogonality % 2 => nonnegativity % 3 => unimodality (and nonnegativitiy) % If const is not defined, no constraints are used. % For no constraints in a threeway problem const = [0 0 0] % % OldLoad If initial guess of the loadings is available. OldLoad should be % given a cell array where OldLoad{1}=A,OldLoad{2}=B etc. % % FixMode FixMode is a binary vector of same sixe as DimX. If % FixMode(i) = 1 => Mode i is fixed (requires old values given) % FixMode(i) = 0 => Mode i is not fixed hence estimated % Ex.: FixMode = [0 1 1] find the scores of a data set given the loadings. % When some modes are fixed, the numbering of the components will % also be fixed. Normally components are sorted according to variance % as in PCA, but this will not be performed if some modes are fixed. % % Weights If a matrix of the same size as X is given, weighted regression % is performed using the weights in the matrix Weights. Statistically % the weights will usually contain the inverse error standard % deviation of the particular element % % ---------------------OUTPUT--------------------- % % Factors PARAFAC estimate of loadings in one matrix. For a 3 component % solution to a 4 x 3 x 3 array the loadings A, B & C will be % stored in a 3 element cell vector: % Factors{1}=A, % Factors{2}=B % Factors{3}=C % etc. % % Use FAC2LET.M for converting to "normal" output or simply extract the % components as e.g. A = Factors{1}; % % it Number of iterations used. Can be helpful for checking if the algorithm % has converged or simply hit the maximal number of iterations (default 2500). % % err The fit of the model = the sum of squares of errors (not including missing % elements). % % Corcondia Core consistency test. Should ideally be 100%. If significantly below % 100% the model is not valid % % % % OTHER STUFF % % Missing values are handled by expectation maximization only. Set all % missing values to NaN % % COMMAND LINE (SHORT) % % Factors = parafac(X,Fac); % % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. % $ Version 1.03 $ Date 1. October 1998 $ Not compiled $ Changed sign-convention because of problems with centered data % $ Version 1.04 $ Date 18. February 1999 $ Not compiled $ Removed auxiliary line % $ Version 1.06 $ Date 1. December 1999 $ Not compiled $ Fixed bug in low fit error handling % $ Version 1.07 $ Date 17. January 2000 $ Not compiled $ Fixed bug in nnls handling so that the algorithm is not stopped until nonnegative appear % $ Version 1.08 $ Date 21. January 2000 $ Not compiled $ Changed init DTLD so that primarily negative loadings are reflected if possible % $ Version 1.09 $ Date 30. May 2000 $ Not compiled $ changed name noptioPF to noptiopf % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.001 $ June 2001 $ Fixed error in weighted regression $ RB $ Not compiled $ % $ Version 2.002 $ Jan 2002 $ Fixed scaling problem due to non-identifiability of DTLD(QZ) by scaling and normalizing after each iteration $ RB $ Not compiled $ % $ Version 2.003 $ Jan 2002 $ Fixed negative solutions when nonneg imposed $ RB $ Not compiled $ % $ Version 2.004 $ Jan 2002 $ Changed initialization when many components used $ RB $ Not compiled $ % $ Version 2.005 $ Jan 2002 $ Changed absolute fit criterion (approacing eps) into relative sse/ssx$ RB $ Not compiled $ % $ Version 2.006 $ Jan 2002 $ Fixed post-scaling when fixed loadings $ RB $ Not compiled $ % $ Version 2.01 $ Jan 2003 $ Removed corcondia for two-way data (doesn't work) and fixed a bug for data with dimension 2 $ RB $ Not compiled $ % $ Version 2.011 $ feb 2003 $ Added an option (4) for not post scaling components $ RB $ Not compiled $ % $ Version 2.10 $ jan 2004 $ Fixed a plotting error occuring when fitting model to old data $ RB $ Not compiled $ % $ Version 2.11 $ jan 2004 $ Fixed that PCA can be fitted $ RB $ Not compiled $ % $ Version 2.12 $ Jul 2004 $ Fixed initialization bug $ RB $ Not compiled $ % $ Version 2.13 $ Jan 2005 $ Modified sign conventions of scores and loads $ RB $ Not compiled $ % $ Version 2.14 $ Feb 2006 $ Fixed bug in sign-swicth when loadings are fixed $ RB $ Not compiled $ NumbIteraInitia=20; if nargin==0 disp(' ') disp(' ') disp(' THE PARAFAC MODEL') disp(' ') disp(' Type <<help parafac>> for more info') disp(' ') disp(' [Factors,it,err,Corcondia] = parafac(X,Fac,Options,const,OldLoad,FixMode,Weights);') disp(' or short') disp(' Factors = parafac(X,Fac);') disp(' ') disp(' Options=[Crit Init Plot NotUsed ShowFit MaxIt]') disp(' ') disp(' ') disp(' EXAMPLE:') disp(' To fit a four-component PARAFAC model to X of size 6 x 2 x 200 x 3 type') disp(' Factors=parafac(X,4)') disp(' and to obtain the scores and loadings from the output type') disp(' [A,B,C,D]=fac2let(Factors);') return elseif nargin<2 error(' The inputs X, and Fac must be given') end DimX = size(X); X = reshape(X,DimX(1),prod(DimX(2:end))); nonneg_obeyed = 1; % used to check if noneg is ok if nargin<3 load noptiopf OptionsDefault=Options; else % Call the current Options OptionsHere and load default to use if some of the current settings should be default Options=Options(:); I=length(Options); if I==0 Options=zeros(8,1); end I=length(Options); if I<8 Options=[Options;zeros(8-I,1)]; end OptionsHere=Options; load noptiopf OptionsDefault=Options; Options=OptionsHere; end if ~exist('OldLoad')==1 OldLoad=0; elseif length(OldLoad)==0 OldLoad=0; end % Convergence criteria if Options(1,1)==0 Options(1,1)=OptionsDefault(1,1); end crit=Options(1); % Initialization if ~any(Options(2)) Options(2)=OptionsDefault(2); end Init=Options(2); % Interim plotting Plt=Options(3,1); if ~any([0 1 2 3]==Plt) error(' Options(3,1) - Plotting - not set correct; must be 0,1,2 or 3') end if Options(5,1)==0 Options(5,1)=OptionsDefault(5,1); end showfit=Options(5,1); if isnan(showfit) showfit=-1; end if showfit<-1|round(showfit)~=showfit error(' Options(5,1) - How often to show fit - not set correct; must be positive integer or -1') end if Options(6,1)==0 Options(6,1)=OptionsDefault(6,1); maxit=Options(6,1); elseif Options(6)>0&round(Options(6))==Options(6) maxit=Options(6,1); else error(' Options(6,1) - Maximal number of iterations - not set correct; must be positive integer') end ShowPhi=0; % Counter. Tuckers congruence coef/Multiple cosine/UUC shown every ShowPhiWhen'th time the fit is shown ShowPhiWhen=10; MissConvCrit=1e-4; % Convergence criterion for estimates of missing values NumberOfInc=0; % Counter for indicating the number of iterations that increased the fit. ALS algorithms ALLWAYS decrease the fit, but using outside knowledge in some sense (approximate equality or iteratively reweighting might cause the algorithm to diverge % INITIALIZE if showfit~=-1 disp(' ') disp(' PRELIMINARY') disp(' ') end ord=length(DimX); if showfit~=-1 disp([' A ',num2str(Fac),'-component model will be fitted']) end if exist('const')~=1 const=zeros(size(DimX)); elseif length(const)~=ord if length(DimX)==2 & length(const)==3 const = const(1:2); else const=zeros(size(DimX)); if showfit~=-1 disp(' Constraints are not given properly') end end end if showfit~=-1 for i=1:ord if const(i)==0 disp([' No constraints on mode ',num2str(i)]) elseif const(i)==1 disp([' Orthogonality on mode ',num2str(i)]) elseif const(i)==2 disp([' Nonnegativity on mode ',num2str(i)]) elseif const(i)==3 disp([' Unimodality on mode ',num2str(i)]) end end end % Check if orthogonality required on all modes DoingPCA= 0; if max(max(const))==1 if min(min(const))==1, if length(DimX)>2 disp(' ') disp(' Not possible to orthogonalize all modes in this implementation.') error(' Contact the authors for further information') else const = [1 0]; % It's ok for PCA but do in one mode to get LS and then orthogonalize afterwards DoingPCA = 1; end end end if exist('FixMode')==1 if length(FixMode)~=ord FixMode = zeros(1,ord); end else FixMode = zeros(1,ord); end if showfit~=-1 if any(FixMode) disp([' The loadings of mode : ',num2str(find(FixMode(:)')),' are fixed']) end end if exist('Weights')~=1 Weights=[]; end % Display convergence criterion if showfit~=-1 disp([' The convergence criterion is ',num2str(crit)]) end % Define loading as one ((r1*r2*r3*...*r7)*Fac x 1) vector [A(:);B(:);C(:);...]. % The i'th loading goes from lidx(i,1) to lidx(i,2) lidx=[1 DimX(1)*Fac]; for i=2:ord lidx=[lidx;[lidx(i-1,2)+1 sum(DimX(1:i))*Fac]]; end % Check if weighted regression required if size(Weights,1)==size(X,1)&prod(size(Weights))/size(X,1)==size(X,2) Weights = reshape(Weights,size(Weights,1),prod(size(Weights))/size(X,1)); if showfit~=-1 disp(' Given weights will be used for weighted regression') end DoWeight=1; else if showfit~=-1 disp(' No weights given') end DoWeight=0; end % Make idx matrices if missing values if any(isnan(X(:))) MissMeth=1; else MissMeth=0; end if MissMeth id=sparse(find(isnan(X))); idmiss2=sparse(find(~isnan(X))); if showfit~=-1 disp([' ', num2str(100*(length(id)/prod(DimX))),'% missing values']); disp(' Expectation maximization will be used for handling missing values') end SSX=sum(sum(X(idmiss2).^2)); % To be used for evaluating the %var explained % If weighting to zero should be used % Replace missing with mean values or model estimates initially %Chk format ok. dimisok = 1; if length(OldLoad)==length(DimX) for i=1:length(DimX) if ~all(size(OldLoad{i})==[DimX(i) Fac]) dimisok = 0; end end else dimisok = 0; end if dimisok model=nmodel(OldLoad); model = reshape(model,DimX); X(id)=model(id); else meanX=mean(X(find(~isnan(X)))); meanX=mean(meanX); X(id)=meanX*ones(size(id)); end else if showfit~=-1 disp(' No missing values') end SSX=sum(sum(X.^2)); % To be used for evaluating the %var explained end % Check if weighting is tried used together with unimodality or orthogonality if any(const==3)|any(const==1) if DoWeight==1 disp(' ') disp(' Weighting is not possible together with unimodality and orthogonality.') disp(' It can be done using majorization, but has not been implemented here') disp(' Please contact the authors for further information') error end end % Acceleration acc=-5; do_acc=1; % Do acceleration every do_acc'th time acc_pow=2; % Extrapolate to the iteration^(1/acc_pow) ahead acc_fail=0; % Indicate how many times acceleration have failed max_fail=4; % Increase acc_pow with one after max_fail failure if showfit~=-1 disp(' Line-search acceleration scheme initialized') end % Find initial guesses for the loadings if no initial values are given % Use old loadings if length(OldLoad)==ord % Use old values if showfit~=-1 disp(' Using old values for initialization') end Factors=OldLoad; % Use DTLD elseif Init==0 if min(DimX)>1&ord==3&MissMeth==0 if sum(DimX<Fac)<2 if showfit~=-1 disp(' Using direct trilinear decomposition for initialization') end try [A,B,C]=dtld(reshape(X,DimX),Fac); catch A = rand(DimX(1),Fac);B = rand(DimX(2),Fac);C = rand(DimX(3),Fac); end else if showfit~=-1 disp(' Using random values for initialization') end for i=1:length(DimX) Factors{i}=rand(DimX(i),Fac); end A = Factors{1};B=Factors{2};C = Factors{3}; end A=real(A);B=real(B);C=real(C); % Check for signs and reflect if appropriate for f=1:Fac if sign(sum(A(:,f)))<0 if sign(sum(B(:,f)))<0 B(:,f)=-B(:,f); A(:,f)=-A(:,f); elseif sign(sum(C(:,f)))<0 C(:,f)=-C(:,f); A(:,f)=-A(:,f); end end if sign(sum(B(:,f)))<0 if sign(sum(C(:,f)))<0 C(:,f)=-C(:,f); B(:,f)=-B(:,f); end end end Factors{1}=A;Factors{2}=B;Factors{3}=C; else if showfit~=-1 disp(' Using singular values for initialization') end try Factors=ini(reshape(X,DimX),Fac,2); catch Factors=[]; for i=1:length(DimX); l = rand(DimX(i),Fac); Factors{i} =l; end if showfit~=-1 disp(' Oops sorry - ended up with random instead') end end end % Use SVD elseif Init==1 if all(DimX>=Fac) if showfit~=-1 disp(' Using singular values for initialization') end try Factors=ini(reshape(X,DimX),Fac,2); catch Factors=[]; for i=1:length(DimX); l = rand(DimX(i),Fac); Factors = [Factors;l(:)]; end end else if showfit~=-1 disp(' Using random values for initialization') end for i=1:length(DimX) Factors{i}=rand(DimX(i),Fac); end end % Use random (orthogonal) elseif Init==2 if showfit~=-1 disp(' Using orthogonal random for initialization') end Factors=ini(reshape(X,DimX),Fac,1); elseif Init==3 error(' Initialization option set to three has been changed to 10') % Use several small ones of the above elseif Init==10 if showfit~=-1 disp(' Using several small runs for initialization') end Opt=Options; Opt(5) = NaN; Opt(6) = NumbIteraInitia; Opt(2) = 0; ERR=[]; [Factors,it,err] = parafac(reshape(X,DimX),Fac,Opt,const,[],[],Weights); ERR = [ERR;err]; Opt(2) = 1; [F,it,Err] = parafac(reshape(X,DimX),Fac,Opt,const,[],[],Weights); ERR=[ERR;Err]; if Err<err Factors=F; err=Err; end Opt(2)=2; for rep=1:3 [F,it,Err]=parafac(reshape(X,DimX),Fac,Opt,const,[],[],Weights); ERR=[ERR;Err]; if Err<err Factors=F; err=Err; end end if showfit~=-1 disp(' ') disp(' Obtained fit-values') disp([' Method Fit']) disp([' DTLD ',num2str(ERR(1))]) disp([' SVD ',num2str(ERR(2))]) disp([' RandOrth ',num2str(ERR(3))]) disp([' RandOrth ',num2str(ERR(4))]) disp([' RandOrth ',num2str(ERR(5))]) end else error(' Problem in PARAFAC initialization - Not set correct') end % Check for signs and reflect if appropriate for f=1:Fac for m=1:ord-1 if sign(sum(Factors{m}(:,f)<0)) & FixMode(m)==0 contin=1; for m2 = m+1:ord if contin & FixMode(m2)==0 if sign(sum(Factors{m2}(:,f)<0)) Factors{m}(:,f)=-Factors{m}(:,f); Factors{m2}(:,f)=-Factors{m2}(:,f); contin=0; end end end end end end % Convert to old format if iscell(Factors) ff = []; for f=1:length(Factors) ff=[ff;Factors{f}(:)]; end Factors = ff; end % ALTERNATING LEAST SQUARES err=SSX; f=2*crit; it=0; connew=2;conold=1; % for missing values ConstraintsNotRight = 0; % Just to ensure that iterations are not stopped if constraints are not yet fully imposed if showfit~=-1 disp(' ') disp(' Sum-of-Squares Iterations Explained') disp(' of residuals variation') end while (((f>crit) | (norm(connew-conold)/norm(conold)>MissConvCrit) | ConstraintsNotRight) & it<maxit)|~ nonneg_obeyed conold=connew; % for missing values it=it+1; acc=acc+1; if acc==do_acc; Load_o1=Factors; end if acc==do_acc+1; acc=0;Load_o2=Factors; Factors=Load_o1+(Load_o2-Load_o1)*(it^(1/acc_pow)); % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end model=nmodel(ff); model = reshape(model,DimX(1),prod(DimX(2:end))); if MissMeth connew=model(id); errX=X-model; if DoWeight==0 nerr=sum(sum(errX(idmiss2).^2)); else nerr=sum(sum((Weights(idmiss2).*errX(idmiss2)).^2)); end else if DoWeight==0 nerr=sum(sum((X-model).^2)); else nerr=sum(sum((X.*Weights-model.*Weights).^2)); end end if nerr>err acc_fail=acc_fail+1; Factors=Load_o2; if acc_fail==max_fail, acc_pow=acc_pow+1+1; acc_fail=0; if showfit~=-1 disp(' Reducing acceleration'); end end else if MissMeth X(id)=model(id); end end end if DoWeight==0 for ii=ord:-1:1 if ii==ord; i=1; else i=ii+1; end idd=[i+1:ord 1:i-1]; l_idx2=lidx(idd,:); dimx=DimX(idd); if ~FixMode(i) L1=reshape(Factors(l_idx2(1,1):l_idx2(1,2)),dimx(1),Fac); if ord>2 L2=reshape(Factors(l_idx2(2,1):l_idx2(2,2)),dimx(2),Fac); Z=kr(L2,L1); else Z = L1; end for j=3:ord-1 L1=reshape(Factors(l_idx2(j,1):l_idx2(j,2)),dimx(j),Fac); Z=kr(L1,Z); end ZtZ=Z'*Z; ZtX=Z'*X'; OldLoad=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); L=pfls(ZtZ,ZtX,DimX(i),const(i),OldLoad,DoWeight,Weights); Factors(lidx(i,1):lidx(i,2))=L(:); end x=zeros(prod(DimX([1:ii-1 ii+1:ord])),DimX(ii)); % Rotate X so the current last mode is the first x(:)=X; X=x'; end else for ii=ord:-1:1 if ii==ord; i=1; else i=ii+1; end idd=[i+1:ord 1:i-1]; l_idx2=lidx(idd,:); dimx=DimX(idd); if ~FixMode(i) L1=reshape(Factors(l_idx2(1,1):l_idx2(1,2)),dimx(1),Fac); if ord>2 L2=reshape(Factors(l_idx2(2,1):l_idx2(2,2)),dimx(2),Fac); Z=kr(L2,L1); else Z = L1; end for j=3:ord-1 L1=reshape(Factors(l_idx2(j,1):l_idx2(j,2)),dimx(j),Fac); Z=kr(L1,Z); end OldLoad=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); L=pfls(Z,X,DimX(i),const(i),OldLoad,DoWeight,Weights); Factors(lidx(i,1):lidx(i,2))=L(:); end x=zeros(prod(DimX([1:ii-1 ii+1:ord])),DimX(ii)); x(:)=X; X=x'; x(:)=Weights; Weights=x'; end end % POSTPROCES LOADINGS (ALL VARIANCE IN FIRST MODE) if ~any(FixMode) A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); for i=2:ord B=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); for ff=1:Fac A(:,ff)=A(:,ff)*norm(B(:,ff)); B(:,ff)=B(:,ff)/norm(B(:,ff)); end Factors(lidx(i,1):lidx(i,2))=B(:); end Factors(lidx(1,1):lidx(1,2))=A(:); end % APPLY SIGN CONVENTION IF NO FIXED MODES % FixMode=1 if ~any(FixMode)&~(any(const==2)|any(const==3)) Sign = ones(1,Fac); for i=ord:-1:2 A=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); Sign2=ones(1,Fac); for ff=1:Fac [out,sig]=max(abs(A(:,ff))); Sign(ff) = Sign(ff)*sign(A(sig,ff)); Sign2(ff) = sign(A(sig,ff)); end A=A*diag(Sign2); Factors(lidx(i,1):lidx(i,2))=A(:); end A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); A=A*diag(Sign); Factors(lidx(1,1):lidx(1,2))=A(:); end % Check if nonneg_obeyed for i=1:ord if const(i)==2|const(i)==3 A=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); if any(A(:))<0 nonneg_obeyed=0; end end end % EVALUATE SOFAR % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac); ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac); id1 = id2; end model=nmodel(ff); model = reshape(model,DimX(1),prod(DimX(2:end))); if MissMeth % Missing values present connew=model(id); X(id)=model(id); errold=err; errX=X-model; if DoWeight==0 err=sum(sum(errX(idmiss2).^2)); else err=sum(sum((Weights(idmiss2).*errX(idmiss2)).^2)); end else errold=err; if DoWeight==0 err=sum(sum((X-model).^2)); else err=sum(sum((Weights.*(X-model)).^2)); end end if err/SSX<1000*eps, % Getting close to the machine uncertainty => stop disp(' WARNING') disp(' The misfit is approaching the machine uncertainty') disp(' If pure synthetic data is used this is OK, otherwise if the') disp(' data elements are very small it might be appropriate ') disp(' to multiply the whole array by a large number to increase') disp(' numerical stability. This will only change the solution ') disp(' by a scaling constant') f = 0; else f=abs((err-errold)/err); if f<crit % Convergence: then check that constraints are fulfilled if any(const==2)|any(const==3) % If nnls or unimodality imposed for i=1:ord % Extract the if const(i)==2|const(i)==3 % If nnls or unimodality imposed Loadd = Factors(sum(DimX(1:i-1))*Fac+1:sum(DimX(1:i))*Fac); if any(Loadd<0) ConstraintsNotRight=1; else ConstraintsNotRight=0; end end end end end end if it/showfit-round(it/showfit)==0 if showfit~=-1, ShowPhi=ShowPhi+1; if ShowPhi==ShowPhiWhen, ShowPhi=0; if showfit~=-1, disp(' '), disp(' Tuckers congruence coefficient'), % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end [phi,out]=ncosine(ff,ff); disp(phi), if MissMeth fprintf(' Change in estim. missing values %12.10f',norm(connew-conold)/norm(conold)); disp(' ') disp(' ') end disp(' Sum-of-Squares Iterations Explained') disp(' of residuals variation') end end if DoWeight==0 PercentExpl=100*(1-err/SSX); else PercentExpl=100*(1-sum(sum((X-model).^2))/SSX); end fprintf(' %12.10f %g %3.4f \n',err,it,PercentExpl); if Plt==2|Plt==3 % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end pfplot(reshape(X,DimX),ff,Weights',[0 0 0 0 0 0 0 1]); drawnow end end end % Make safety copy of loadings and initial parameters in temp.mat if it/50-round(it/50)==0 save temp Factors end % JUDGE FIT if err>errold NumberOfInc=NumberOfInc+1; end % POSTPROCESS. IF PCA on two-way enforce orth in both modes. end % while f>crit if DoingPCA A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); B=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); [u,s,v]=svd(A*B',0); A = u(:,1:size(A,2))*s(1:size(A,2),1:size(A,2)); B = u(:,1:size(B,2)); Factors = [A(:);B(:)]; end % CALCULATE TUCKERS CONGRUENCE COEFFICIENT if showfit~=-1 & DimX(1)>1 disp(' '),disp(' Tuckers congruence coefficient') % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end [phi,out]=ncosine(ff,ff); disp(phi) disp(' ') if max(max(abs(phi)-diag(diag(phi))))>.85 disp(' ') disp(' ') disp(' WARNING, SOME FACTORS ARE HIGHLY CORRELATED.') disp(' ') disp(' You could decrease the number of components. If this') disp(' does not help, try one of the following') disp(' ') disp(' - If systematic variation is still present you might') disp(' wanna decrease your convergence criterion and run') disp(' one more time using the loadings as initial guess.') disp(' ') disp(' - Or use another preprocessing (check for constant loadings)') disp(' ') disp(' - Otherwise try orthogonalising some modes,') disp(' ') disp(' - Or use Tucker3/Tucker2,') disp(' ') disp(' - Or a PARAFAC with some modes collapsed (if # modes > 3)') disp(' ') end end % SHOW FINAL OUTPUT if DoWeight==0 PercentExpl=100*(1-err/SSX); else PercentExpl=100*(1-sum(sum((X-model).^2))/SSX); end if showfit~=-1 fprintf(' %12.10f %g %3.4f \n',err,it,PercentExpl); if NumberOfInc>0 disp([' There were ',num2str(NumberOfInc),' iterations that increased fit']); end end % POSTPROCES LOADINGS (ALL VARIANCE IN FIRST MODE) if Options(4)==0|Options(4)==1 A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); for i=2:ord B=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); for ff=1:Fac A(:,ff)=A(:,ff)*norm(B(:,ff)); B(:,ff)=B(:,ff)/norm(B(:,ff)); end Factors(lidx(i,1):lidx(i,2))=B(:); end Factors(lidx(1,1):lidx(1,2))=A(:); if showfit~=-1 disp(' ') disp(' Components have been normalized in all but the first mode') end end % PERMUTE SO COMPONENTS ARE IN ORDER AFTER VARIANCE DESCRIBED (AS IN PCA) IF NO FIXED MODES if ~any(FixMode) A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); [out,order]=sort(diag(A'*A)); order=flipud(order); A=A(:,order); Factors(lidx(1,1):lidx(1,2))=A(:); for i=2:ord B=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); B=B(:,order); Factors(lidx(i,1):lidx(i,2))=B(:); end if showfit~=-1 disp(' Components have been ordered according to contribution') end elseif showfit ~= -1 disp(' Some modes fixed hence no sorting of components performed') end % TOOLS FOR JUDGING SOLUTION if nargout>3 x=X; if MissMeth x(id)=NaN*id; end % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end corcondia=corcond(reshape(x,DimX),ff,Weights,0); end % APPLY SIGN CONVENTION IF NO FIXED MODES % FixMode=1 if ~any(FixMode)&~(any(const==2)|any(const==3)) Sign = ones(1,Fac); for i=ord:-1:2 A=reshape(Factors(lidx(i,1):lidx(i,2)),DimX(i),Fac); Sign2=ones(1,Fac); for ff=1:Fac [out,sig]=max(abs(A(:,ff))); Sign(ff) = Sign(ff)*sign(A(sig,ff)); Sign2(ff) = sign(A(sig,ff)); end A=A*diag(Sign2); Factors(lidx(i,1):lidx(i,2))=A(:); end A=reshape(Factors(lidx(1,1):lidx(1,2)),DimX(1),Fac); A=A*diag(Sign); Factors(lidx(1,1):lidx(1,2))=A(:); % % Instead of above, do signs so as to make them as "natural" as possible % Factors = signswtch(Factors,reshape(X,DimX)); % DIDN't WORK (TOOK AGES FOR 7WAY DATA) if showfit~=-1 disp(' Components have been reflected according to convention') end end % Convert to new format clear ff,id1 = 0; for i = 1:length(DimX) id2 = sum(DimX(1:i).*Fac);ff{i} = reshape(Factors(id1+1:id2),DimX(i),Fac);id1 = id2; end Factors = ff; if Plt==1|Plt==2|Plt==3 % if Fac<6&Plt~=3&order>2&ord>2 if Fac<6&Plt~=3&ord>2 pfplot(reshape(X,DimX),ff,Weights,ones(1,8)); else pfplot(reshape(X,DimX),ff,Weights,[1 1 0 1 1 1 1 1]); if ord>2 disp(' Core consistency plot not shown because it requires large memory') disp(' It can be made writing pfplot(X,Factors,[Weights],[0 0 1 0 0 0 0 0]'); else disp(' Core consistency not applicable for two-way data') end end end % Show which criterion stopped the algorithm if showfit~=-1 if ((f<crit) & (norm(connew-conold)/norm(conold)<MissConvCrit)) disp(' The algorithm converged') elseif it==maxit disp(' The algorithm did not converge but stopped because the') disp(' maximum number of iterations was reached') elseif f<eps disp(' The algorithm stopped because the change in fit is now') disp(' smaller than the machine uncertainty.') else disp(' Algorithm stopped for some mysterious reason') end end function swloads = signswtch(loads,X); %SIGNSWTCH switches sign of multilinear models so that signs are in %accordance with majority of data % % % I/O swloads = signswtch(loads,X); % % Factors must be a cell with the loadings. If Tucker or NPLS, then the % last element of the cell must be the core array try % Does not work in older versions of matlab warning('off','MATLAB:divideByZero'); end sizeX=size(X); order = length(sizeX); for i=1:order; F(i) = size(loads{i},2); end if isa(X,'dataset')% Then it's a SDO inc=X.includ; X = X.data(inc{:}); end % Compare centered X with center loading vector if length(loads)==order % PARAFAC % go through each component and then update in the end for m = 1:order % For each mode determine the right sign for f=1:F(1) % one factor at the time s=[]; a = loads{m}(:,f); x = permute(X,[m 1:m-1 m+1:order]); for i=1:size(x(:,:),2); % For each column id = find(~isnan(x(:,i))); if length(id)>1 try c = corrcoef(x(id,i),a(id)); catch disp('Oops - something wrong in signswtch - please send a note to [email protected]') whos end if isnan(c(2,1)) s(i)=0; else s(i) = c(2,1)*length(id); % Weigh correlation by number of elements so many-miss columns don't influence too much end else s(i) = 0; end end S(m,f) = sum(s); end end % Use S to switch signs. If the signs of S (for each f) multiply to a % positive number the switches are performed. If not, the mode of the % negative one with the smallest absolute value is not switched. for f = 1:F(1) if sign(prod(S(:,f)))<1 % Problem: make the smallest negative positive to avoid switch of that id = find(S(:,f)<0); [a,b]=min(abs(S(id,f))); S(id(b(1)),f)=-S(id(b(1)),f); end end % Now ok, so switch what needs to be switched for f = 1:F(1) for m = 1:order if sign(S(m,f))<1 loads{m}(:,f)=-loads{m}(:,f); end end end elseif length(loads)==(order+1) % NPLS/Tucker % go through each mode and update and correct core accordinglu for m = 1:order % For each mode determine the right sign for f=1:F(m) % one factor at the time a = loads{m}(:,f); x = permute(X,[m 1:m-1 m+1:order]); for i=1:size(x(:,:),2); % For each column id = find(~isnan(x(:,i))); if length(id)>1 c = corrcoef(x(id,i),a(id)); if isnan(c(2,1)) s(i)=0; else s(i) = c(2,1)*length(id); % Weigh correlation by number of elements so many-miss columns don't influence too much end else s(i) = 0; end end if sum(s) < 0 % turn around loads{m}(:,f) = -loads{m}(:,f); % Then switch the core accordingly G = loads{order+1}; G = permute(G,[m 1:m-1 m+1:order]); sizeG = size(G); G = reshape(G,sizeG(1),prod(sizeG)/sizeG(1)); G(f,:) = -G(f,:); G = reshape(G,sizeG); G = ipermute(G,[m 1:m-1 m+1:order]); loads{order+1} = G; end end end else error('Unknown model type in SIGNS.M') end swloads = loads;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
ncrossdecompn.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/ncrossdecompn.m
17,959
utf_8
0301a7a14a32ccf091dc76d066fd22e9
function XvalResult = ncrossdecomp(Method,X,FacMin,FacMax,Segments,Cent,Show); %NCROSSDECOMP crossvalidation of PARAFAC/Tucker/PCA % % See also: % 'ncrossreg' % % This file performs cross-validation of decomposition models % PARAFAC, PCA, and Tucker. The cross-validation is performed % such that part of the data are set to missing, the model is % fitted to the remaining data, and the residuals between fitted % and true left-out elements is calculated. This is performed % 'Segments' times such that all elements are left out once. % The segments are chosen by taking every 'Segments' element of % X(:), i.e. from the vectorized array. If X is of size 5 x 7, % and three segemnts are chosen ('Segments' = 3), then in the % first of three models, the model is fitted to the matrix % % |x 0 0 x 0 0 x| % |0 x 0 0 x 0 0| % |0 0 x 0 0 x 0| % |x 0 0 x 0 0 x| % |0 x 0 0 x 0 0| % % where x's indicate missing elements. After fitting the residuals % in the locations of missing values are calculated. After fitting % all three models, all residuals have been calculated. % % Note that the number of segments must be chosen such that no columns % or rows contain only missing elements (the algorithm will check this). % Using 'Segments' = 7, 9, or 13 will usually achieve that. % % I/O % XvalResult = ncrossdecomp(Method,X,FacMin,FacMax,Segments,Cent,Show); % % INPUT % Method : 'parafac', 'tucker', 'pca', or 'nipals' % For Tucker only Tucker3 models with equal % number of components is currently available. % For PCA the least squares model is calculated. % Thus, offsets and parameters are calculated in % a least squares sense unlike the method NIPALS, % which calculates the PCA model using an ad hoc % approach for handling missing data (as in % standard chemometric software). % X : Multi-way array of data % FacMin : Lowest number of factors to use % FacMax : Highest number of factors (note that for Tucker only models % with the same number of components in each mode are % calculated currently % Segments : The number of segments to use. Try many! % Cent : If set of one, the data are centered across samples, % i.e. ordinary centering. Note, however, that the centering % is not performed in a least squares sense but as preprocessing. % This is not optimal because the data have missing data because % of the way the elements are left out. This can give % significantly lower fit than reasonable if you have few samples % or use few segments. Alternatively, you can center the data % beforehand and perform cross-validation on the centered data % Show : If set to 0, no plot is given % % OUTPUT % Structure XvalResult holding: % Fit: The fitted percentage of variation explaind (as a % function of component number) % Xval: The cross-validated percentage of variation explaind % (as a function of component number) % FittedModel: The fitted model (as a function of component number) % XvalModel: The cross-validated model (as a function of component number) % $ Version 1.0301 $ Date 28. June 1999 $ Not compiled $ % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. % uses NANSUM, %GT Perm = [1:ndims(X)]; DimX = size(X); ord = ndims(X); delta = zeros(1,ndims(X)); for i = 1:ndims(X) c(i) = isempty(intersect(factor(DimX(i)),factor(Segments))); index{i} = 1:DimX(i); end delta = zeros(1,ndims(X)); for i = 1:ndims(X) c(i) = isempty(intersect(factor(DimX(i)),factor(Segments))); index{i} = 1:DimX(i); end P = find(~c); if sum(c) < length(DimX) - 1 for i = 1:sum(~c) while ~c(P(i)) & delta(P(i)) < (abs(DimX(P(i))- Segments) - 1) if ~rem(DimX(P(i)),2) & ~rem(Segments,2) & delta(P(i)) > 0 Off = 2; else Off = 1; end delta(P(i)) = delta(P(i)) + Off; c(P(i)) = isempty(intersect(factor(DimX(P(i)) + delta(P(i))),factor(Segments))); end if sum(c) == length(DimX) - 1 return end end if sum(~c) > 1 error('The chosen segmentation leads to tubes of only missing values') end end if sum(c) == length(DimX) - 1 [c,Perm] = sort(~c); end [nil,PermI] = sort(Perm); X = reshape(X,DimX(1),prod(DimX(2:end))); %GT end [I,J] = size(X); if exist('Show')~=1 Show = 1; end if lower(Method(1:3)=='tuc') if length(FacMin)==1 FacMin = ones(1,ord)*FacMin; elseif length(FacMin)~=ord error('Error in FacMin: When fitting Tucker models, the number of factors should be given for each mode') end if length(FacMax)==1 FacMax = ones(1,ord)*FacMax; elseif length(FacMax)~=ord error('Error in FacMax: When fitting Tucker models, the number of factors should be given for each mode') end end %RB % Check if the selected segmentation works (does not produce rows/columns of only missing) %out = ones(I,J); %out(1:Segments:end)=NaN; %out(find(isnan(X))) = NaN; %if any(sum(isnan(out))==I) % error(' The chosen segmentation leads to columns of only missing elements') %elseif any(sum(isnan(out'))==J) % error(' The chosen segmentation leads to rows of only missing elements') %end %RB end if lower(Method(1:3)~='tuc') XvalResult.Fit = zeros(FacMax,2)*NaN; XvalResult.Xval = zeros(FacMax,2)*NaN; for f = 1:FacMin-1 XvalResult.XvalModel{f} = 'Not fitted'; XvalResult.FittedModel{f} = 'Not fitted'; end for f = FacMin:FacMax % Fitted model disp([' Total model - Comp. ',num2str(f),'/',num2str(FacMax)]) [M,Mean,Param] = decomp(Method,X,DimX,f,1,Segments,Cent,I,J); Model = M + ones(I,1)*Mean'; id = find(~isnan(X)); OffsetCorrectedData = X - ones(I,1)*Mean'; XvalResult.Fit(f,:) = [100*(1 - sum( (X(id) - Model(id)).^2)/sum(OffsetCorrectedData(id).^2)) f]; XvalResult.FittedModel{f} = Model; % Xvalidated Model of data ModelXval = zeros(I,J)*NaN; for s = 1:Segments disp([' Segment ',num2str(s),'/',num2str(Segments),' - Comp. ',num2str(f),'/',num2str(FacMax)]) %GT Xnow = permute(zeros(DimX),Perm); dimsadd = size(Xnow); for j = 1:length(DimX) dimsadd(j) = delta(Perm(j)); Xnow = cat(j,Xnow,zeros(dimsadd)); index2{j} = 1:DimX(Perm(j)); dimsadd = size(Xnow); end Xnow(s:Segments:end) = NaN; Xnow = reshape(permute(Xnow(index2{:}),PermI),DimX(1),prod(DimX(2:end))); Pos = isnan(Xnow); [M,Mean] = decomp(Method,Xnow + X,DimX,f,s,Segments,Cent,I,J,Param); model = M + ones(I,1)*Mean'; ModelXval(Pos) = model(Pos); %GT end end XvalResult.Xval(f,:) = [100*(1 - sum( (X(id) - ModelXval(id)).^2)/sum(OffsetCorrectedData(id).^2)) f]; XvalResult.XvalModel{f} = ModelXval; end else % Do Tucker model %GT if length(FacMin) ~= ord FacMin = ones(1,ord)*min(FacMin); end if length(FacMax) ~= ord FacMax = ones(1,ord)*min(FacMax); end for i=1:length(FacMin) ind{i} = [FacMin(i):FacMax(i)]'; ind2{i} = ones(length(ind{i}),1); end NCombs = cellfun('length',ind); for i=1:length(FacMin) o = [1:i-1,i+1:length(FacMin)]; t = ipermute(ind{i}(:,ind2{o}),[i,o]); possibleCombs(1:prod(NCombs),i) = t(:); end FeasCombs = sort(possibleCombs'); f2 = prod(FeasCombs(1:size(FeasCombs,1)-1,:))<FeasCombs(end,:); possibleCombs(f2,:) = []; possibleCombs(:,end+1) = find(~f2(:)); %GTend %RB % Find all %PossibleNumber = [min(FacMin):max(FacMax)]'*ones(1,ord); %possibleCombs = unique(nchoosek(PossibleNumber(:),ord),'rows'); %remove useless %f2 = []; %for f1 = 1:size(possibleCombs,1) % if (prod(possibleCombs(f1,:))/max(possibleCombs(f1,:)))<max(possibleCombs(f1,:)) % Check that the largest mode is larger than the product of the other % f2 = [f2;f1]; % elseif any(possibleCombs(f1,:)>FacMax) % Chk the model is desired, % f2 = [f2;f1]; % end %end %possibleCombs(f2,:)=[]; %[f1,f2]=sort(sum(possibleCombs')); %possibleCombs = [possibleCombs(f2,:) f1']; %RBend XvalResult.Fit = zeros(size(possibleCombs,1),ord+1)*NaN; XvalResult.Xval = zeros(size(possibleCombs,1),ord+1)*NaN; for f = 1:size(possibleCombs,1) XvalResult.XvalModel{f} = 'Not fitted'; XvalResult.FittedModel{f} = 'Not fitted'; end for f1 = 1:size(possibleCombs,1) % Fitted model %GT disp([' Total model - Comp. ',num2str(possibleCombs(f1,:)),'/',num2str(FacMax)]) [M,Mean,Param] = decomp(Method,X,DimX,possibleCombs(f1,:),1,Segments,Cent,I,J); %GTend %RB %disp([' Total model - Comp. ',num2str(possibleCombs(f1,1:end-1)),'/',num2str(FacMax)]) %[M,Mean,Param] = decomp(Method,X,DimX,possibleCombs(f1,1:end-1),1,Segments,Cent,I,J); %RBend Model = M + ones(I,1)*Mean'; id = find(~isnan(X)); OffsetCorrectedData = X - ones(I,1)*Mean'; XvalResult.Fit(f1,:) = [100*(1 - sum( (X(id) - Model(id)).^2)/sum(OffsetCorrectedData(id).^2)) possibleCombs(f1,1:end-1)]; XvalResult.FittedModel{f1} = Model; % Xvalidated Model of data ModelXval = zeros(I,J)*NaN; for s = 1:Segments disp([' Segment ',num2str(s),'/',num2str(Segments),' - Comp. ',num2str(possibleCombs(f1,1:end-1)),'/',num2str(FacMax)]) %GT Xnow = permute(zeros(DimX),Perm); dimsadd = DimX; for j = 1:length(DimX) dimsadd(j) = delta(j); Xnow = cat(j,Xnow,zeros(dimsadd)); index2{j} = 1:DimX(j); dimsadd(j) = dimsadd(j) + DimX(j); end Xnow(s:Segments:end) = NaN; Xnow = reshape(permute(Xnow(index2{:}),PermI),DimX(1),prod(DimX(2:end))); Pos = isnan(Xnow); [M,Mean] = decomp(Method,Xnow + X,DimX,possibleCombs(f1,1:end-1),s,Segments,Cent,I,J,Param); model = M + ones(I,1)*Mean'; ModelXval(Pos) = model(Pos); %GT end end XvalResult.Xval(f1,:) = [100*(1 - sum( (X(id) - ModelXval(id)).^2)/sum(OffsetCorrectedData(id).^2)) possibleCombs(f1,1:end-1)]; XvalResult.XvalModel{f1} = ModelXval; end end if Show&FacMin-FacMax~=0 if Method(1:3) == 'pca' Nam = 'PCA'; elseif Method(1:3) == 'tuc' Nam = 'Tucker'; elseif Method(1:3) == 'par' Nam = 'PARAFAC'; elseif Method(1:3) == 'nip' Nam = 'NIPALS'; end figure save jjj if lower(Method(1:3))~='tuc' bar(FacMin:FacMax,[XvalResult.Fit(FacMin:FacMax,1) XvalResult.Xval(FacMin:FacMax,1)],.76,'grouped') else % extract the ones with lowest Xval fit (for each # total comp) for plotting fx = []; f5 =[]; for f1 = 1:max(possibleCombs(:,end)) f2 = find(possibleCombs(:,end)==f1); if length(f2) [f3,f4] = max(XvalResult.Xval(f2)); f5 = [f5,f2(f4)]; end end fx = [possibleCombs(f5,end) XvalResult.Fit(f5,1) XvalResult.Xval(f5,1)]; bar(fx(:,1),fx(:,2:3),.76,'grouped') for f1 = 1:size(fx,1) f6=text(fx(f1,1),95,['[',num2str(possibleCombs(f5(f1),1:end-1)),']']); set(f6,'Rotation',270) end end g=get(gca,'YLim'); set(gca,'YLim',[max(-20,g(1)) 100]) legend('Fitted','Xvalidated',0) titl = ['Xvalidation results (',Nam,')']; if Cent titl = [titl ,' - centering']; else titl = [titl ,' - no centering']; end title(titl,'FontWeight','Bold') xlabel('Total number of components') ylabel('Percent variance explained') end function [M,Mean,parameters] = decomp(Method,X,DimX,f,s,Segments,Cent,I,J,parameters); Conv = 0; it = 0; maxit = 500; % Initialize if Cent Mean = nanmean(X)'; else Mean = zeros(J,1); end if lower(Method(1:3)) == 'par' Xc = reshape(X- ones(I,1)*Mean',DimX); if exist('parameters')==1 fact = parafac(Xc,f,[1e-5 10 0 0 NaN maxit],[],parameters.fact); else fact = parafac(Xc,f,[1e-5 10 0 0 NaN maxit]); end M = reshape(nmodel(fact),DimX(1),prod(DimX(2:end))); parameters.fact=fact; elseif lower(Method(1:3)) == 'tuc' Xc = reshape(X- ones(I,1)*Mean',DimX); if exist('parameters')==1 [fact,G] = tucker(Xc,f,[1e-2 0 0 0 NaN maxit],[],[],parameters.fact,parameters.G); else [fact,G] = tucker(Xc,f,[1e-2 0 0 0 NaN maxit]); end parameters.fact=fact; parameters.G=G; M = reshape(nmodel(fact,G),DimX(1),prod(DimX(2:end))) ; elseif lower(Method) == 'pca'|lower(Method) == 'nip' Xc = reshape(X- ones(I,1)*Mean',DimX(1),prod(DimX(2:end))); [t,p] = pcanipals(X- ones(I,1)*Mean',f,0); parameters.t=t; parameters.p=p; M = t*p'; else error(' Name of method not recognized') end Fit = X - M - ones(I,1)*Mean'; Fit = sum(Fit(find(~isnan(X))).^2); % Iterate while ~Conv it = it+1; FitOld = Fit; % Fit multilinear part Xcent = X - ones(I,1)*Mean'; if Method(1:3) == 'par' fact = parafac(reshape(Xcent,DimX),f,[1e-2 0 0 0 NaN maxit],[],fact); M = reshape(nmodel(fact),DimX(1),prod(DimX(2:end))); elseif Method(1:3) == 'tuc' [fact,G] = tucker(reshape(Xcent,DimX),f,[1e-2 0 0 0 NaN maxit],[0 0 0],zeros(size(G)),fact,G); M = reshape(nmodel(fact,G),DimX(1),prod(DimX(2:end))); elseif Method == 'pca' [t,p] = pcals(Xcent,f,0,t,p,0); M = t*p'; elseif Method == 'nip' [t,p] = pcanipals(Xcent,f,0); M = t*p'; end % Find offsets if Cent x = X; mm=M+ones(I,1)*Mean'; x(find(isnan(X)))=mm(find(isnan(X))); Mean = mean(x)'; end %Find fit Fit = X - M - ones(I,1)*Mean'; Fit = sum(Fit(find(~isnan(X))).^2); if abs(Fit-FitOld)/FitOld<1e-8 | it > 1500 Conv = 1; end end disp([' Fit ',num2str(Fit),' using ',num2str(it),' it.']) function [t,p] = pcals(X,F,cent,t,p,show); % LEAST SQUARES PCA WITH MISSING ELEMENTS % 20-6-1999 % % Calculates a least squares PCA model. Missing elements % are denoted NaN. The solution is NOT nested, so one has % to calculate a new model for each number of components. ShowMeFitEvery = 20; MaxIterations = 5; [I,J]=size(X); Xorig = X; Miss = find(isnan(X)); NotMiss = find(~isnan(X)); m = t*p'; X(Miss) = m(Miss); ssX = sum(X(NotMiss).^2); Fit = 3; OldFit = 6; it = 0; while abs(Fit-OldFit)/OldFit>1e-3 & it < MaxIterations; it = it +1; OldFit = Fit; [t,s,p] = svds(X,F); t = t*s; Model = t*p'; X(Miss) = Model(Miss); Fit = sum(sum( (Xorig(NotMiss) - Model(NotMiss)).^2)); if ~rem(it,ShowMeFitEvery)&show disp([' Fit after ',num2str(it),' it. :',num2str(RelFit),'%']) end end function [t,p,Mean] = pcanipals(X,F,cent); % NIPALS-PCA WITH MISSING ELEMENTS % cent: One if centering is to be included, else zero [I,J]=size(X); rand('state',sum(100*clock)) Xorig = X; Miss = isnan(X); NotMiss = ~isnan(X); ssX = sum(X(find(NotMiss)).^2); Mean = zeros(1,J); if cent Mean = nanmean(X); end X = X - ones(I,1)*Mean; t=[]; p=[]; for f=1:F Fit = 3; OldFit = 6; it = 0; T = rand(I,1); P = rand(J,1); Fit = 2; FitOld = 3; while abs(Fit-FitOld)/FitOld>1e-7 & it < 100; FitOld = Fit; it = it +1; for j = 1:J id=find(NotMiss(:,j)); if length(id)==0 id,end P(j) = T(id)'*X(id,j)/(T(id)'*T(id)); end P = P/norm(P); for i = 1:I id=find(NotMiss(i,:)); T(i) = P(id)'*X(i,id)'/(P(id)'*P(id)); end Fit = X-T*P'; Fit = sum(Fit(find(NotMiss)).^2); end t = [t T]; p = [p P]; X = X - T*P'; end function Xc = nanmean(X) if isempty(X) Xc = NaN; return end i = isnan(X); j = find(i); i = sum(i); X(j) = 0; Num = size(X,1)-i; Xc = sum(X); i = find(Num); Xc(i) = Xc(i)./Num(i); Xc(find(~Num))=NaN;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
unimodalcrossproducts.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/unimodalcrossproducts.m
5,308
utf_8
a01635517eb192929d08cfdb95f5c5d1
function B=unimodalcrossproducts(XtX,XtY,Bold) %UNIMODALCROSSPRODUCTS % Solves the problem min|Y-XB'| subject to the columns of % B are unimodal and nonnegative. The algorithm is iterative and % only one iteration is given, hence the solution is only improving % the current estimate % % I/O B=unimodalcrossproducts(XtX,XtY,Bold) % Modified from unimodal.m to handle crossproducts in input 1999 % Reference % Bro and Sidiropoulos, "Journal of Chemometrics", 1998, 12, 223-247. % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. B=Bold; F=size(B,2); for f=1:F xty = XtY(f,:)-XtX(f,[1:f-1 f+1:F])*B(:,[1:f-1 f+1:F])'; beta=pinv(XtX(f,f))*xty; B(:,f)=ulsr(beta',1); end function [b,All,MaxML]=ulsr(x,NonNeg); % ------INPUT------ % % x is the vector to be approximated % NonNeg If NonNeg is one, nonnegativity is imposed % % % % ------OUTPUT----- % % b is the best ULSR vector % All is containing in its i'th column the ULSRFIX solution for mode % location at the i'th element. The ULSR solution given in All % is found disregarding the i'th element and hence NOT optimal % MaxML is the optimal (leftmost) mode location (i.e. position of maximum) % % ___________________________________________________________ % % % Copyright 1997 % % Nikos Sidiroupolos % University of Maryland % Maryland, US % % & % % Rasmus Bro % Royal Veterinary & Agricultural University % Denmark % % % ___________________________________________________________ % This file uses MONREG.M x=x(:); I=length(x); xmin=min(x); if xmin<0 x=x-xmin; end % THE SUBSEQUENT % CALCULATES BEST BY TWO MONOTONIC REGRESSIONS % B1(1:i,i) contains the monontonic increasing regr. on x(1:i) [b1,out,B1]=monreg(x); % BI is the opposite of B1. Hence BI(i:I,i) holds the monotonic % decreasing regression on x(i:I) [bI,out,BI]=monreg(flipud(x)); BI=flipud(fliplr(BI)); % Together B1 and BI can be concatenated to give the solution to % problem ULSR for any modloc position AS long as we do not pay % attention to the element of x at this position All=zeros(I,I+2); All(1:I,3:I+2)=B1; All(1:I,1:I)=All(1:I,1:I)+BI; All=All(:,2:I+1); Allmin=All; Allmax=All; % All(:,i) holds the ULSR solution for modloc = i, disregarding x(i), iii=find(x>=max(All)'); b=All(:,iii(1)); b(iii(1))=x(iii(1)); Bestfit=sum((b-x).^2); MaxML=iii(1); for ii=2:length(iii) this=All(:,iii(ii)); this(iii(ii))=x(iii(ii)); thisfit=sum((this-x).^2); if thisfit<Bestfit b=this; Bestfit=thisfit; MaxML=iii(ii); end end if xmin<0 b=b+xmin; end % Impose nonnegativity if NonNeg==1 if any(b<0) id=find(b<0); % Note that changing the negative values to zero does not affect the % solution with respect to nonnegative parameters and position of the % maximum. b(id)=zeros(size(id))+0; end end function [b,B,AllBs]=monreg(x); % Monotonic regression according % to J. B. Kruskal 64 % % b = min|x-b| subject to monotonic increase % B = b, but condensed % AllBs = All monotonic regressions, i.e. AllBs(1:i,i) is the % monotonic regression of x(1:i) % % % Copyright 1997 % % Rasmus Bro % Royal Veterinary & Agricultural University % Denmark % [email protected] % I=length(x); if size(x,2)==2 B=x; else B=[x(:) ones(I,1)]; end AllBs=zeros(I,I); AllBs(1,1)=x(1); i=1; while i<size(B,1) if B(i,1)>B(min(I,i+1),1) summ=B(i,2)+B(i+1,2); B=[B(1:i-1,:);[(B(i,1)*B(i,2)+B(i+1,1)*B(i+1,2))/(summ) summ];B(i+2:size(B,1),:)]; OK=1; while OK if B(i,1)<B(max(1,i-1),1) summ=B(i,2)+B(i-1,2); B=[B(1:i-2,:);[(B(i,1)*B(i,2)+B(i-1,1)*B(i-1,2))/(summ) summ];B(i+1:size(B,1),:)]; i=max(1,i-1); else OK=0; end end bInterim=[]; for i2=1:i bInterim=[bInterim;zeros(B(i2,2),1)+B(i2,1)]; end No=sum(B(1:i,2)); AllBs(1:No,No)=bInterim; else i=i+1; bInterim=[]; for i2=1:i bInterim=[bInterim;zeros(B(i2,2),1)+B(i2,1)]; end No=sum(B(1:i,2)); AllBs(1:No,No)=bInterim; end end b=[]; for i=1:size(B,1) b=[b;zeros(B(i,2),1)+B(i,1)]; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
nprocess.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/NWAY/nprocess.m
10,939
utf_8
251743bad479e490e243bd1285a1a1f6
function [Xnew,mX,sX]=nprocess(X,Cent,Scal,mX,sX,reverse,show,usemse); %NPROCESS pre and postprocessing of multiway arrays % % % CENTERING AND SCALING OF N-WAY ARRAYS % % This m-file works in two ways % I. Calculate center and scale parameters and preprocess data % II. Use given center and scale parameters for preprocessing data % % %%% I. Calculate center and scale parameters %%% % % [Xnew,Means,Scales]=nprocess(X,Cent,Scal); % % INPUT % X Data array % Cent is binary row vector with as many elements as DimX. % If Cent(i)=1 the centering across the i'th mode is performed % I.e cnt = [1 0 1] means centering across mode one and three. % Scal is defined likewise. Scal(i)=1, means scaling to standard % deviation one within the i'th mode % % OUTPUT % Xnew The preprocessed data % mX Sparse vector holding the mean-values % sX Sparse vector holding the scales % % %%% II. Use given center and scale parameters %%% % % Xnew=nprocess(X,Cent,Scal,mX,sX,reverse); % % INPUT % X Data array % Cent is binary row vector with as many elements as DimX. % If Cent(i)=1 the centering across the i'th mode is performed % I.e Cent = [1 0 1] means centering across mode one and three. % Scal is defined likewise. Scal(i)=1, means scaling to standard % deviation one within the i'th mode % mX Sparse vector holding the mean-values % sX Sparse vector holding the scales % reverse Optional input % if reverse = 1 normal preprocessing is performed (default) % if reverse = -1 inverse (post-)processing is performed % % OUTPUT % Xnew The preprocessed data % % For convenience this m-file does not use iterative % preprocessing, which is necessary for some combinations of scaling % and centering. Instead the algorithm first standardizes the modes % successively and afterwards centers. The prior standardization ensures % that the individual variables are on similar scale (this might be slightly % disturbed upon centering - unlike for two-way data). % % The full I/O for nprocess is % [Xnew,mX,sX]=nprocess(X,Cent,Scal,mX,sX,reverse,show,usemse); % where show set to zero avoids screen output and where usemse set % to one uses RMSE instead of STD for scaling (more appropriate % in some settings) % Copyright, 1998 - % This M-file and the code in it belongs to the holder of the % copyrights and is made public under the following constraints: % It must not be changed or modified and code cannot be added. % The file must be regarded as read-only. Furthermore, the % code can not be made part of anything but the 'N-way Toolbox'. % In case of doubt, contact the holder of the copyrights. % % Rasmus Bro % Chemometrics Group, Food Technology % Department of Food and Dairy Science % Royal Veterinary and Agricultutal University % Rolighedsvej 30, DK-1958 Frederiksberg, Denmark % Phone +45 35283296 % Fax +45 35283245 % E-mail [email protected] % $ Version 1.03 $ Date 6. May 1998 $ Drastic error in finding scale parameters corrected $ Not compiled $ % $ Version 1.031 $ Date 25. January 2000 $ Error in scaling part $ Not compiled $ % $ Version 1.032 $ Date 28. January 2000 $ Minor bug$ Not compiled $ % $ Version 1.033 $ Date 14. April 2001 $ Incorrect backscaling fixed. % $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $ % $ Version 2.00 $ May 2001 $ rewritten by Giorgio Tomasi $ RB $ Not compiled $ % $ Version 2.01 $ Feb 2002 $ Fixed errors occuring with one-slab inputs $ RB $ Not compiled $ % $ Version 2.02 $ Oct 2003 $ Added possibility for sclaing with RMSE $ RB $ Not compiled $ % $ Version 1.03 $ Date 6. May 1998 $ Drastic error in finding scale parameters corrected $ Not compiled $ % Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson % Copenhagen University, DK-1958 Frederiksberg, Denmark, [email protected] % % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 51 Franklin % Street, Fifth Floor, Boston, MA 02110-1301, USA. % % % CENTERING AND SCALING OF N-WAY ARRAYS % % This m-file works in two ways % I. Calculate center and scale parameters and preprocess data % II. Use given center and scale parameters for preprocessing data % % %%% I. Calculate center and scale parameters %%% % % [Xnew,Means,Scales]=nprocess(X,DimX,Cent,Scal); % % INPUT % X Data array % DimX Size of X % Cent is binary row vector with as many elements as DimX. % If Cent(i)=1 the centering across the i'th mode is performed % I.e cnt = [1 0 1] means centering across mode one and three. % Scal is defined likewise. Scal(i)=1, means scaling to standard % deviation one within the i'th mode % % OUTPUT % Xnew The preprocessed data % mX Sparse vector holding the mean-values % sX Sparse vector holding the scales % % %%% II. Use given center and scale parameters %%% % % Xnew=nprocess(X,DimX,Cent,Scal,mX,sX); % % INPUT % X Data array % DimX Size of X % Cent is binary row vector with as many elements as DimX. % If Cent(i)=1 the centering across the i'th mode is performed % I.e Cent = [1 0 1] means centering across mode one and three. % Scal is defined likewise. Scal(i)=1, means scaling to standard % deviation one within the i'th mode % mX Sparse vector holding the mean-values % sX Sparse vector holding the scales % reverse Optional input % if reverse = 1 normal preprocessing is performed (default) % if reverse = -1 inverse (post-)processing is performed % % OUTPUT % Xnew The preprocessed data % % For convenience this m-file does not use iterative % preprocessing, which is necessary for some combinations of scaling % and centering. Instead the algorithm first standardizes the modes % successively and afterwards centers. The prior standardization ensures % that the individual variables are on similar scale (this might be slightly % disturbed upon centering - unlike for two-way data). % % Copyright % Rasmus Bro 1997 % Denmark % E-mail [email protected] ord = ndims(X); DimX = size(X); Xnew = X; if nargin<3 error(' Three input arguments must be given') end if nargin==4 error(' You must input both mX and sX even if you are only doing centering') end if nargin<8 usemse=0; end if ~exist('mX','var') mX = []; end if ~exist('sX','var') sX = []; end MODE = isa(mX,'cell')&isa(sX,'cell'); if ~exist('show')==1 show=1; end if ~exist('reverse')==1 reverse=1; end if ~any([1 -1]==reverse) error( 'The input <<reverse>> must be one or minus one') end if show~=-1 if ~MODE disp(' Calculating mean and scale and processing data') else if reverse==1 disp(' Using given mean and scale values for preprocessing data') elseif reverse==-1 disp(' Using given mean and scale values for postprocessing data') end end end for i=1:ndims(X) Inds{i} = ones(size(Xnew,i),1); end Indm = repmat({':'},ndims(Xnew) - 1,1); out=0; if ~MODE mX = cell(ord,1); sX = cell(ord,1); end Ord2Patch = [2,1;1,2]; if reverse == 1 %Standardize for j = ord:-1:1 o = [j 1:j-1 j+1:ord]; if Scal(j) if show~=-1 disp([' Scaling mode ',num2str(j)]) end if ~MODE if ~usemse sX{j} = (stdnan(nshape(Xnew,j)')').^-1; else sX{j} = (rmsenan(nshape(Xnew,j)')').^-1; end end Xnew = Xnew.*ipermute(sX{j}(:,Inds{o(2:end)}),o); end end %Center for j = ord:-1:1 o = [1:j-1 j+1:ord,j]; if Cent(j) if show~=-1 if ~MODE disp([' Centering mode ',num2str(j)]) else disp([' Subtracting off-sets in mode ',num2str(j)]) end end if ~MODE if ord ~= 2 mmm = nshape(Xnew,j); if min(size(mmm))==1 mmm = mmm; else mmm = missmean(mmm); end mX{j} = reshape(mmm,DimX(o(1:end-1))); else mX{j} = reshape(missmean(nshape(Xnew,j)),DimX(o(1)),1); end end Xnew = Xnew - ipermute(mX{j}(Indm{:},Inds{j}),o); end end else %Center for j = 1:ord if Cent(j) if show~=-1 disp([' Adding off-sets in mode ',num2str(j)]) end Xnew = Xnew + ipermute(mX{j}(Indm{:},Inds{j}),[1:j-1 j+1:ord,j]); end end %Standardize for j = 1:ord o = [1:j-1 j+1:ord]; if Scal(j) if show~=-1 disp([' Rescaling back to original domain in mode ',num2str(j)]) end Xnew = Xnew ./ ipermute(sX{j}(:,Inds{o}),[j o]); end end end function st=rmsenan(X); %RMSENAN estimate RMSE with NaN's % % Estimates the RMSE of each column of X % when there are NaN's in X. % % Columns with only NaN's get a standard deviation of zero % $ Version 1.02 $ Date 28. July 1998 $ Not compiled $ % % % Copyright, 1998 - % This M-file and the code in it belongs to the holder of the % copyrights and is made public under the following constraints: % It must not be changed or modified and code cannot be added. % The file must be regarded as read-only. Furthermore, the % code can not be made part of anything but the 'N-way Toolbox'. % In case of doubt, contact the holder of the copyrights. % % Rasmus Bro % Chemometrics Group, Food Technology % Department of Food and Dairy Science % Royal Veterinary and Agricultutal University % Rolighedsvej 30, DK-1958 Frederiksberg, Denmark % E-mail: [email protected] [I,J]=size(X); st=[]; for j=1:J id=find(~isnan(X(:,j))); if length(id) st=[st sqrt(mean(X(id,j).^2))]; else st=[st 0]; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
jdqr.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/jdqr.m
73,068
utf_8
b45810ddb5b2767c9289909175d1dc04
function varargout=jdqr(varargin) %JDQR computes a partial Schur decomposition of a square matrix or operator. % Lambda = JDQR(A) returns the absolute largest eigenvalues in a K vector % Lambda. Here K=min(5,N) (unless K has been specified), where N=size(A,1). % JDQR(A) (without output argument) displays the K eigenvalues. % % [X,Lambda] = JDQR(A) returns the eigenvectors in the N by K matrix X and % the eigenvalues in the K by K diagonal matrix Lambda. Lambda contains the % Jordan structure if there are multiple eigenvalues. % % [X,Lambda,HISTORY] = JDQR(A) returns also the convergence history % (that is, norms of the subsequential residuals). % % [X,Lambda,Q,S] = JDQR(A) returns also a partial Schur decomposition: % S is an K by K upper triangular matrix and Q is an N by K orthonormal matrix % such that A*Q = Q*S. The diagonal elements of S are eigenvalues of A. % % [X,Lambda,Q,S,HISTORY] = JDQR(A) returns also the convergence history. % % [X,Lambda,HISTORY] = JDQR('Afun') % [X,Lambda,HISTORY] = JDQR('Afun',N) % The first input argument is either a square matrix (which can be % full or sparse, symmetric or nonsymmetric, real or complex), or a % string containing the name of an M-file which applies a linear % operator to a given column vector. In the latter case, the M-file must % return the the order N of the problem with N = Afun([],'dimension') or % N must be specified in the list of input arguments. % For example, EIGS('fft',...) is much faster than EIGS(F,...) % where F is the explicit FFT matrix. % % The remaining input arguments are optional and can be given in % practically any order: % ... = JDQR(A,K,SIGMA,OPTIONS) % ... = JDQR('Afun',K,SIGMA,OPTIONS) % where % % K An integer, the number of eigenvalues desired. % SIGMA A scalar shift or a two letter string. % OPTIONS A structure containing additional parameters. % % With one output argument, S is a vector containing K eigenvalues. % With two output arguments, S is a K-by-K upper triangular matrix % and Q is a matrix with K columns so that A*Q = Q*S and Q'*Q=I. % With three output arguments, HISTORY contains the convergence history. % % If K is not specified, then K = MIN(N,5) eigenvalues are computed. % % If SIGMA is not specified, then the K-th eigenvalues largest in magnitude % are computed. If SIGMA is zero, then the K-th eigenvalues smallest in % magnitude are computed. If SIGMA is a real or complex scalar then the % K-th eigenvalues nearest SIGMA are computed. If SIGMA is one of the % following strings, then it specifies the desired eigenvalues. % % SIGMA Location wanted eigenvalues % % 'LM' Largest Magnitude (the default) % 'SM' Smallest Magnitude (same as sigma = 0) % 'LR' Largest Real part % 'SR' Smallest Real part % 'BE' Both Ends. Computes k/2 eigenvalues % from each end of the spectrum (one more % from the high end if k is odd.) % % % The OPTIONS structure specifies certain parameters in the algorithm. % % Field name Parameter Default % % OPTIONS.Tol Convergence tolerance: 1e-8 % norm(A*Q-Q*S,1) <= tol * norm(A,1) % OPTIONS.jmin minimum dimension search subspace k+5 % OPTIONS.jmax maximum dimension search subspace jmin+5 % OPTIONS.MaxIt Maximum number of iterations. 100 % OPTIONS.v0 Starting space ones+0.1*rand % OPTIONS.Schur Gives schur decomposition 'no' % also in case of 2 or 3 output % arguments (X=Q, Lambda=R). % % OPTIONS.TestSpace For using harmonic Ritz values 'Standard' % If 'TestSpace'='Harmonic' then % sigma=0 is the default value for SIGMA % % OPTIONS.Disp Shows size of intermediate residuals 1 % and displays the appr. eigenvalues. % % OPTIONS.LSolver Linear solver 'GMRES' % OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,.. % OPTIONS.LS_MaxIt Maximum number it. linear solver 5 % OPTIONS.LS_ell ell for BiCGstab(ell) 4 % % OPTIONS.Precond Preconditioner LU=[[],[]]. % % For instance % % OPTIONS=STRUCT('Tol',1.0e-10,'LSolver','BiCGstab','LS_ell',2,'Precond',M); % % changes the convergence tolerance to 1.0e-10, takes BiCGstab(2) as linear % solver and the preconditioner defined in M.m if M is the string 'M', % or M = L*U if M is an n by 2*n matrix: M = [L,U]. % % The preconditoner can be specified in the OPTIONS structure, % but also in the argument list: % ... = JDQR(A,K,SIGMA,M,OPTIONS) % ... = JDQR(A,K,SIGMA,L,U,OPTIONS) % ... = JDQR('Afun',K,SIGMA,'M',OPTIONS) % ... = JDQR('Afun',K,SIGMA,'L','U',OPTIONS) % as an N by N matrix M (then M is the preconditioner), or an N by 2*N % matrix M (then L*U is the preconditioner, where M = [L,U]), % or as N by N matrices L and U (then L*U is the preconditioner), % or as one or two strings containing the name of M-files ('M', or % 'L' and 'U') which apply a linear operator to a given column vector. % % JDQR (without input arguments) lists the options and the defaults. % Gerard Sleijpen. % Copyright (c) 98 % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology global Qschur Rschur PinvQ Pinv_u Pu nm_operations if nargin==0, possibilities, return, end %%% Read/set parameters [n,nselect,sigma,SCHUR,... jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV0,t_tol,... lsolver,LSpar] = ReadOptions(varargin{1:nargin}); LSpar0=LSpar; JDV=0; tol0=tol; LOCK0=~ischar(sigma); if nargout>3, SCHUR=0; end tau=0; if INTERIOR>=1 & LOCK0, tau=sigma(1); end n_tar=size(sigma,1); nt=1; FIG=gcf; %%% Initiate global variables Qschur = zeros(n,0); Rschur = []; PinvQ = zeros(n,0); Pinv_u = zeros(n,1); Pu = []; nm_operations = 0; history = []; %%% Return if eigenvalueproblem is trivial if n<2 if n==1, Qschur=1; Rschur=MV(1); end if nargout == 0, eigenvalue=Rschur, else [varargout{1:nargout}]=output(history,Qschur,Rschur); end, return, end String = ['\r#it=%i #MV=%i dim(V)=%i |r_%i|=%6.1e ']; StrinP = '--- Checking for conjugate pair ---\n'; time = clock; %%% Initialize V, W: %%% V,W orthonormal, A*V=W*R+Qschur*E, R upper triangular [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol); j=size(V,2); k=size(Rschur,1); nit=0; nlit=0; SOLVED=0; switch INTERIOR case 0 %%% The JD loop (Standard) %%% V orthogonal, V orthogonal to Qschur %%% V*V=eye(j), Qschur'*V=0, %%% W=A*V, M=V'*W %%% W=W*R; if tau ~=0; W=W+tau*V; end, M=M'*R; temptarget=sigma(nt,:); while (k<nselect) & (nit < maxit) %%% Compute approximate eigenpair and residual [UR,S]=SortSchur(M,temptarget,j==jmax,jmin); y=UR(:,1); theta=S(1,1); u=V*y; w=W*y; r=w-theta*u; [r,s]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1; if LOCK0 & nr<t_tol, temptarget=[theta;sigma(nt,:)]; end % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defekt',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2, LOCK = LOCK0 & nr<t_tol; %%% if MovieTheta(n,nit,diag(S),jmin,sigma(nt,:),LOCK,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; Rschur=[Rschur,s;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1, [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end W=W*R; if tau ~=0; W=W+tau*V; end; M=M'*R; j=size(V,2); else, J=[2:j]; j=j-1; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND, temptarget=conj(theta); if SHOW, fprintf(StrinP), end else, nlit=0; nt=min(nt+1,n_tar); temptarget=sigma(nt,:); end end % nr<tol %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; end % if j>=jmax if r_KNOWN %%% Solve correction equation v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1; nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; end % if r_KNOWN if EXPAND %%% Expand the subspaces of the interaction matrix v=RepGS([Qschur,V],v); if size(v,2)>0 w=MV(v); M=[M,V'*w;v'*W,v'*w]; V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0; else tol=2*tol; end end % if EXPAND end % while (nit<maxit) case 1 %%% The JD loop (Harmonic Ritz values) %%% Both V and W orthonormal and orthogonal w.r.t. Qschur %%% V*V=eye(j), Qschur'*V=0, W'*W=eye(j), Qschur'*W=0 %%% (A*V-tau*V)=W*R+Qschur*E, E=Qschur'*(A*V-tau*V), M=W'*V %%% temptarget=0; FIXT=1; lsolver0=lsolver; while (k<nselect) & (nit<maxit) %%% Compute approximate eigenpair and residual [UR,UL,S,T]=SortQZ(R,M,temptarget,j>=jmax,jmin); y=UR(:,1); theta=T(1,1)'*S(1,1); u=V*y; w=W*(R*y); r=w-theta*u; nr=norm(r); r_KNOWN=1; if nr<t_tol, temptarget=[theta;0]; end, theta=theta+tau; % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defect',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2, Lambda=diag(S)./diag(T)+tau; Lambda(1)=theta; %%% if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; Rschur=[Rschur,E*y;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; JDV=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1, [V,W,R,E,M]=... SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end, j=size(V,2); else J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J); R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; [r,a]=RepGS(u,r,0); E=[E*UR;(T(1,1)'-a/S(1,1))*S(1,J)]; s=(S(1,J)/S(1,1))/R; W=W+r*s; M=M+s'*(r'*V); if (nr*norm(s))^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\M; end end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND, if SHOW, fprintf(StrinP), end temptarget=[conj(theta)-tau;0]; else, nlit=0; temptarget=0; if nt<n_tar nt=nt+1; tau0=tau; tau=sigma(nt,1); tau0=tau0-tau; [W,R]=qr(W*R+tau0*V,0); M=W'*V; end end end %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J); R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; E=E*UR; end % if j>=jmax if r_KNOWN %%% Solve correction equation if JDV, disp('Stagnation'), LSpar(end-1)=(LSpar(end-1)+15)*2; % lsolver='bicgstab'; LSpar=[1.e-2,300,4]; else LSpar=LSpar0; JDV=0; lsolver=lsolver0; end if nr>0.001 & FIXT, theta=tau; else, FIXT=0; end v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; SOLVED=1; JDV=0; end if EXPAND %%% Expand the subspaces of the interaction matrix [v,zeta]=RepGS([Qschur,V],v); if JDV0 & abs(zeta(end,1))/norm(zeta)<0.06, JDV=JDV+1; end if size(v,2)>0 w=MV(v); if tau ~=0, w=w-tau*v; end [w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w); R=[[R;zeros(1,j)],y]; M=[M,W'*v;w'*V,w'*v]; E=[E,e]; V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0; else tol=2*tol; end end end % while (nit<maxit) case 1.1 %%% The JD loop (Harmonic Ritz values) %%% V W AV. %%% Both V and W orthonormal and orthogonal w.r.t. Qschur, AV=A*V-tau*V %%% V*V=eye(j), W'*W=eye(j), Qschur'*V=0, Qschur'*W=0, %%% (I-Qschur*Qschur')*AV=W*R, M=W'*V; R=W'*AV; %%% AV=W*R; temptarget=0; while (k<nselect) & (nit<maxit) %%% Compute approximate eigenpair and residual [UR,UL,S,T]=SortQZ(R,M,temptarget,j>=jmax,jmin); y=UR(:,1); u=V*y; w=AV*y; theta=u'*w; r=w-theta*u; [r,y]=RepGS(Qschur,r,0); nr=norm(r); r_KNOWN=1; if nr<t_tol, temptarget=[theta;0]; end, theta=theta+tau; % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defect',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2,Lambda=diag(S)./diag(T)+tau; Lambda(1)=theta; %%% if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; Rschur=[Rschur,y;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1 [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end AV=W*R; j=size(V,2); else J=[2:j]; j=j-1; UR=UR(:,J); UL=UL(:,J); AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND,if SHOW, fprintf(StrinP), end temptarget=[conj(theta)-tau;0]; else, nlit=0; temptarget=0; if nt<n_tar nt=nt+1; tau0=tau; tau=sigma(nt,1); tau0=tau0-tau; AV=AV+tau0*V; [W,R]=qr(W*R+tau0*V,0); M=W'*V; end end end %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); UL=UL(:,J); AV=AV*UR; R=S(J,J); M=T(J,J); V=V*UR; W=W*UL; end % if j>=jmax if r_KNOWN %%% Solve correction equation v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1; nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; end if EXPAND %%% Expand the subspaces of the interaction matrix v=RepGS([Qschur,V],v); if size(v,2)>0 w=MV(v); if tau ~=0, w=w-tau*v;end AV=[AV,w]; R=[R,W'*w]; w=RepGS([Qschur,W],w); R=[R;w'*AV]; M=[M,W'*v;w'*V,w'*v]; V=[V,v]; W=[W,w]; j=j+1; EXPAND=0; tol=tol0; else tol=2*tol; end end end % while (nit<maxit) case 1.2 %%% The JD loop (Harmonic Ritz values) %%% W orthonormal, V and W orthogonal to Qschur, %%% W'*W=eye(j), Qschur'*V=0, Qschur'*W=0 %%% W=(A*V-tau*V)-Qschur*E, E=Qschur'*(A*V-tau*V), %%% M=W'*V V=V/R; M=M/R; temptarget='LM'; E=E/R; while (k<nselect) & (nit<maxit) %%% Compute approximate eigenpair and residual [UR,S]=SortSchur(M,temptarget,j==jmax,jmin); y=UR(:,1); u=V*y; nrm=norm(u); y=y/nrm; u=u/nrm; theta=S(1,1)'/(nrm*nrm); w=W*y; r=w-theta*u; nr=norm(r); r_KNOWN=1; if nr<t_tol, temptarget=[S(1,1);inf]; end, theta=theta+tau; % defekt=abs(norm(RepGS(Qschur,MV(u)-theta*u,0))-nr); % DispResult('defect',defekt,3) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% history=[history;nr,nit,nm_operations]; %%% if SHOW, fprintf(String,nit,nm_operations,j,nlit,nr) %%% if SHOW == 2, Lambda=1./diag(S)+tau; Lambda(1)=theta; %%% if MovieTheta(n,nit,Lambda,jmin,sigma(nt,:),nr<t_tol,j==jmax) %%% break, end, end, end %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Check for convergence if nr<tol %%% Expand the partial Schur form Qschur=[Qschur,u]; %% Rschur=[[Rschur;zeros(1,k)],Qschur'*MV(u)]; k=k+1; y=E*y; Rschur=[Rschur,y;zeros(1,k),theta]; k=k+1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if SHOW, ShowLambda(theta,k), end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if k>=nselect, break, end, r_KNOWN=0; %%% Expand preconditioned Schur matrix PinvQ SOLVED=UpdateMinv(u,SOLVED); if j==1 [V,W,R,E,M]=SetInitialSpaces(zeros(n,0),nselect,tau,jmin,tol); k=size(Rschur,1); if k>=nselect, break, end V=V/R; j=size(V,2); M=M/R; E=E/R; else J=[2:j]; j=j-1; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; [r,a]=RepGS(u,r,0); s=u'*V; V=V-u*s; W=W-r*s; M=M-s'*(r'*V)-(W'*u)*s; E=[E*UR-y*s;(tau-theta-a)*s]; if (nr*norm(s))^2>eps, [W,R]=qr(W,0); V=V/R; M=(R'\M)/R; E=E/R; end end if PAIRS & abs(imag(theta))>tol, v=imag(u/sign(max(u))); if norm(v)>tol, v=RepGS(Qschur,v,0); EXPAND=(norm(v)>sqrt(tol)); end end if EXPAND, if SHOW, fprintf(StrinP), end temptarget=[1/(conj(theta)-tau);inf]; else, nlit=0; temptarget='LM'; if nt<n_tar nt=nt+1; tau0=tau; tau=sigma(nt,1); [W,R]=qr(W+(tau0-tau)*V,0); V=V/R; M=W'*V; E=E/R; end end end %%% Check for shrinking the search subspace if j>=jmax j=jmin; J=[1:j]; UR=UR(:,J); M=S(J,J); V=V*UR; W=W*UR; E=E*UR; end % if j>=jmax if r_KNOWN %%% Solve correction equation v=Solve_pce(theta,u,r,lsolver,LSpar,nlit); SOLVED=1; nlit=nlit+1; nit=nit+1; r_KNOWN=0; EXPAND=1; end if EXPAND %%% Expand the subspaces of the interaction matrix v=RepGS(Qschur,v,0); if size(v,2)>0 w=MV(v); if tau ~=0, w=w-tau*v; end [w,e]=RepGS(Qschur,w,0); [w,y]=RepGS(W,w); nrw=y(j+1,1); y=y(1:j,:); v=v-V*y; v=v/nrw; e=e-E*y; e=e/nrw; M=[M,W'*v;w'*V,w'*v]; V=[V,v]; W=[W,w]; j=j+1; E=[E,e]; if 1/cond(M)<10*tol [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E); k=size(Rschur,1); if k>=nselect, break, end V=V/R; M=M/R; j=size(V,2);temptarget='LM'; E=E/R; end EXPAND=0; tol=tol0; else tol=2*tol; end end end % while (nit<maxit) end % case time_needed=etime(clock,time); Refine([Qschur,V],1);% 2-SCHUR); CheckSortSchur(sigma); Lambda=[]; X=zeros(n,0); if ~SCHUR & k>0, [z,Lambda]=Jordan(Rschur); X=Qschur*z; end %-------------- display results ---------------------------- if SHOW == 2, MovieTheta, figure(FIG), end if SHOW & size(history,1)>0 switch INTERIOR case 0 testspace='V, V orthonormal'; case 1 testspace='A*V-sigma*V, V and W orthonormal'; case 1.1 testspace='A*V-sigma*V, V and W orthonormal, AV'; case 1.2 testspace='A*V-sigma*V, W orthogonal'; otherwise testspace='Experimental'; end StringT=sprintf('The test subspace W is computed as W = %s.',testspace); StringX=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',... jmin,jmax,tol); StringY=sprintf('Correction equation solved with %s.',lsolver); date=fix(clock); String=sprintf('\n%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6)); StringL='log_{10} || r_{#it} ||_2'; for pl=1:SHOW subplot(SHOW,1,pl), t=history(:,pl+1); plot(t,log10(history(:,1)),'*-',t,log10(tol)+0*t,':') legend(StringL), title(StringT) StringL='log_{10} || r_{#MV} ||_2'; StringT=StringX; end if SHOW==2, xlabel([StringY,String]) else, xlabel([StringX,String]), ylabel(StringY), end drawnow end if SHOW str1=num2str(abs(k-nselect)); str='s'; if k>nselect, if k==nselect+1, str1='one'; str=''; end fprintf('\n\nDetected %s additional eigenpair%s.',str1,str) end if k<nselect, if k==0, str1='any'; str=''; elseif k==nselect-1, str1='one'; str=''; end fprintf('\n\nFailed detection of %s eigenpair%s.',str1,str) end if k>0, ShowLambda(diag(Rschur)); else, fprintf('\n'); end Str='time_needed'; DispResult(Str,eval(Str)) if (k>0) if ~SCHUR Str='norm(MV(X)-X*Lambda)'; DispResult(Str,eval(Str)) end Str='norm(MV(Qschur)-Qschur*Rschur)'; DispResult(Str,eval(Str)) I=eye(k); Str='norm(Qschur''*Qschur-I)'; DispResult(Str,eval(Str)) end fprintf('\n\n') end if nargout == 0, if ~SHOW, eigenvalues=diag(Rschur), end, return, end [varargout{1:nargout}]=output(history,X,Lambda); return %=========================================================================== %======= PREPROCESSING ===================================================== %=========================================================================== %======= INITIALIZE SUBSPACE =============================================== function [V,W,R,E,M]=SetInitialSpaces(V,nselect,tau,jmin,tol,W,E); %[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol); % Output: V(:,1:SIZE(VV,2))=ORTH(VV), % V'*V=W'*W=EYE(JMIN), M=W'*V; % such that A*V-tau*V=W*R+Qschur*E, % with R upper triangular, and E=Qschur'*(A*V-tau*V). % %[V,W,R,E,M]=SetInitialSpaces(VV,nselect,tau,jmin,tol,AV,EE); % Input such that % A*VV-tau*VV=AV+Qschur*EE, EE=Qschur'*(A*VV-tau*VV); % % Output: V(:,1:SIZE(VV,2))=ORTH(VV), % V'*V=W'*W=EYE(JMIN), M=W'*V; % such that A*V-tau*V=W*R+Qschur*E, % with R upper triangular, and E=Qschur'*(A*V-tau*V). global Qschur Rschur [n,j]=size(V); k=size(Qschur,2); if j>1, [V,R]=qr(V,0); if nargin <6, W=MV(V); R=eye(j); if tau~=0, W=W-tau*V; end if k>0, E=Qschur'*W; W=W-Qschur*E; else, E=zeros(0,j); end end [V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,R); l=size(Qschur,2); j=size(V,2); if l>=nselect, if size(V,2)==0; R=1; M=1; return, end, end if l>k, UpdateMinv(Qschur(:,k+1:l),0); end, k=l; end if j==0, nr=0; while nr==0 V = ones(n,1)+0.1*rand(n,1); V=RepGS(Qschur,V); nr=norm(V); end, j=1; end if j==1 [V,H,E]=Arnoldi(V,tau,jmin,nselect,tol); l=size(Qschur,2); j=max(size(H,2),1); if l>=nselect, W=V; R=eye(j); M=R; return, end if l>k, UpdateMinv(Qschur(:,k+1:l),0); end [Q,R]=qr(full(H),0); W=V*Q; V(:,j+1)=[]; M=Q(1:j,:)'; %% W=V*Q; V=V(:,1:j)/R; E=E/R; R=eye(j); M=Q(1:j,:)'/R; %% W=V*H; V(:,j+1)=[];R=R'*R; M=H(1:j,:)'; end return %%%======== ARNOLDI (for initializing spaces) =============================== function [V,H,E]=Arnoldi(v,tau,jmin,nselect,tol) % %[V,AV,H,nMV,tau]=ARNOLDI(A,V0,TAU,JMIN,NSELECT,TOL) % ARNOLDI computes the Arnoldi factorization of dimenison JMIN+1: % (A-tau)*V(:,1:JMIN)=V*H where V is n by JMIN+1 orthonormal with % first column a multiple of V0, and H is JMIN+1 by JMIN Hessenberg. % % If an eigenvalue if H(1:j,1:j) is an eigenvalue of A % within the required tolerance TOL then the Schurform % A*Qschur=Qschur*Rschur is expanded and the Arnoldi factorization % (A-tau)*V(:,1:j)=V(:,1:j+1)*H(1:j+1,1:j) is deflated. % Returns if size(Qschur,2) = NSELECT or size(V,2) = JMIN+1 % (A-tau)*V(:,1:JMIN)=V*H+Qschur*E, Qschur'*V=0 % Coded November 5, 1998, G. Sleijpen global Qschur Rschur k=size(Qschur,2); [n,j]=size(v); if ischar(tau), tau=0; end H=zeros(1,0); V=zeros(n,0); E=[]; j=0; nr=norm(v); while j<jmin & k<nselect & j+k<n if nr>=tol v=v/nr; V=[V,v]; j=j+1; Av=MV(v); end if j==0 H=zeros(1,0); j=1; nr=0; while nr==0, v=RepGS(Qschur,rand(n,1)); nr=norm(v); end v=v/nr; V=v; Av=MV(v); end if tau~=0; Av=Av-tau*v; end, [v,e] = RepGS(Qschur,Av,0); if k==0, E=zeros(0,j); else, E = [E,e(1:k,1)]; end [v,y] = RepGS(V,v,0); H = [H,y(1:j,1)]; nr = norm(v); H = [H;zeros(1,j-1),nr]; [Q,U,H1] = DeflateHess(full(H),tol); j=size(U,2); l=size(Q,2); if l>0 %--- expand Schur form ------ Qschur=[Qschur,V*Q]; Rschur=[Rschur,E*Q; zeros(l,k),H1(1:l,1:l)+tau*eye(l)]; k=k+l; E=[E*U;H1(1:l,l+1:l+j)]; if j>0, V=V*U; H=H1(l+1:l+j+1,l+1:l+j); else, V=zeros(n,0); H=zeros(1,0); end end end % while if nr>=tol v=v/nr; V=[V,v]; end return %---------------------------------------------------------------------- function [Q,U,H]=DeflateHess(H,tol) % H_in*[Q,U]=[Q,U]*H_out such that H_out(K,K) upper triangular % where K=1:SIZE(Q,2) and ABS(Q(end,2)*H_in(j+1,j))<TOL, j=SIZE(H,2), [j1,j]=size(H); if j1==j, [Q,H]=schur(H); U=zeros(j,0); return, end nr=H(j+1,j); U=eye(j); i=1; J=i:j; for l=1:j [X,Lambda]=eig(H(J,J)); I=find(abs(X(size(X,1),:)*nr)<tol); if isempty(I), break, end q=X(:,I(1)); q=q/norm(q); q(1,1)=q(1,1)+sign(q(1,1)); q=q/norm(q); H(:,J)=H(:,J)-(2*H(:,J)*q)*q'; H(J,:)=H(J,:)-2*q*(q'*H(J,:)); U(:,J)=U(:,J)-(2*U(:,J)*q)*q'; i=i+1; J=i:j; end [Q,HH]=RestoreHess(H(i:j+1,J)); H(:,J)=H(:,J)*Q; H(J,:)=Q'*H(J,:); U(:,J)=U(:,J)*Q; Q=U(:,1:i-1); U=U(:,i:j); return %---------------------------------------------------------------------- function [Q,M]=RestoreHess(M) [j1,j2]=size(M); Q=eye(j2); for j=j1:-1:2 J=1:j-1; q=M(j,J)'; q=q/norm(q); q(j-1,1)=q(j-1,1)+sign(q(j-1,1)); q=q/norm(q); M(:,J)=M(:,J)-2*(M(:,J)*q)*q'; M(J,:)=M(J,:)-2*q*q'*M(J,:); Q(:,J)=Q(:,J)-2*Q(:,J)*q*q'; end return %%%=========== END ARNOLDI ============================================ function [V,W,R,E,M]=CheckForNullSpace(V,nselect,tau,tol,W,E,Rv); % V,W orthonormal, A*V-tau*V=W*R+Qschur'*E global Qschur Rschur k=size(Rschur,1); j=size(V,2); [W,R]=qr(W,0); E=E/Rv; R=R/Rv; M=W'*V; %%% not accurate enough M=Rw'\(M/Rv); if k>=nselect, return, end CHECK=1; l=k; [S,T,Z,Q]=qz(R,M); Z=Z'; while CHECK I=SortEigPairVar(S,T,2); [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1)); s=abs(S(1,1)); t=min(abs(T(1,1)),1); CHECK=(s*sqrt(1-t*t)<tol); if CHECK V=V*Q; W=W*Z; E=E*Q; u=V(:,1); [r,a]=RepGS(u,(W(:,1)-T(1,1)'*u)*S(1,1),0); Qschur=[Qschur,u]; t=(T(1,1)'-a/S(1,1))*S(1,:); Rschur=[Rschur,E(:,1);zeros(1,k),tau+t(1,1)]; k=k+1; J=[2:j]; j=j-1; V=V(:,J); W=W(:,J); E=[E(:,J);t(1,J)]; s=S(1,J)/S(1,1); R=S(J,J); M=T(J,J); Q=eye(j); Z=eye(j); s=s/R; nrs=norm(r)*norm(s); if nrs>=tol, W=W+r*s; M=M+s'*(r'*V); if nrs^2>eps, [W,R0]=qr(W,0); R=R0*R; M=R0'\M; end end S=R; T=M; CHECK=(k<nselect & j>0); end end return %=========================================================================== %======= POSTPROCESSING ==================================================== %=========================================================================== function Refine(V,gamma); if gamma==0, return, end global Qschur Rschur J=1:size(Rschur,1); if gamma==1, [V,R]=qr(V(:,J),0); W=MV(V); M=V'*W; [U,Rschur]=schur(M); [U,Rschur]=rsf2csf(U,Rschur); Qschur=V*U; return elseif gamma==2 [V,R]=qr(V,0); W=MV(V); M=V'*W; [U,S]=schur(M); [U,S]=rsf2csf(U,S); R=R*U; F=R'*R-S'*S; [X,Lambda]=Jordan(S); % Xinv=inv(X); D=sqrt(diag(Xinv*Xinv')); X=X*diag(D); [d,I]=sort(abs(diag(X'*F*X))); [U,S]=SwapSchur(U,S,I(J)); Qschur=V*U(:,J); Rschur=S(J,J); end return %=========================================================================== function CheckSortSchur(sigma) global Qschur Rschur k=size(Rschur,1); if k==0, return, end I=SortEig(diag(Rschur),sigma); if ~min((1:k)'==I) [U,Rschur]=SwapSchur(eye(k),Rschur,I); Qschur=Qschur*U; end return %%%=========== COMPUTE SORTED JORDAN FORM ================================== function [X,Jordan]=Jordan(S) % [X,J]=JORDAN(S) % For S k by k upper triangular matrix with ordered diagonal elements, % JORDAN computes the Jordan decomposition. % X is a k by k matrix of vectors spanning invariant spaces. % If J(i,i)=J(i+1,i+1) then X(:,i)'*X(:,i+1)=0. % J is a k by k matrix, J is Jordan such that S*X=X*J. % diag(J)=diag(S) are the eigenvalues % coded by Gerard Sleijpen, Januari 14, 1998 k=size(S,1); X=zeros(k); if k==0, Jordan=[]; return, end %%% accepted separation between eigenvalues: delta=2*sqrt(eps)*norm(S,inf); delta=max(delta,10*eps); T=eye(k); s=diag(S); Jordan=diag(s); for i=1:k I=[1:i]; e=zeros(i,1); e(i,1)=1; C=S(I,I)-s(i,1)*T(I,I); C(i,i)=1; j=i-1; q=[]; jj=0; while j>0 if abs(C(j,j))<delta, jj=jj+1; j=j-1; else, j=0; end end q=X(I,i-jj:i-1); C=[C,T(I,I)*q;q',zeros(jj)]; q=C\[e;zeros(jj,1)]; nrm=norm(q(I,1)); Jordan(i-jj:i-1,i)=-q(i+1:i+jj,1)/nrm; X(I,i)=q(I,1)/nrm; end return %========== OUTPUT ========================================================= function varargout=output(history,X,Lambda) global Qschur Rschur if nargout == 1, varargout{1}=diag(Rschur); return, end if nargout > 2, varargout{nargout}=history; end if nargout > 3, varargout{3} = Qschur; varargout{4} = Rschur; end if nargout < 4 & size(X,2)<2 varargout{1}=Qschur; varargout{2}=Rschur; return else varargout{1}=X; varargout{2}=Lambda; end return %=========================================================================== %===== UPDATE PRECONDITIONED SCHUR VECTORS ================================= %=========================================================================== function solved=UpdateMinv(u,solved) global Qschur PinvQ Pinv_u Pu L_precond if ~isempty(L_precond) if ~solved, Pinv_u=SolvePrecond(u); end Pu=[[Pu;u'*PinvQ],Qschur'*Pinv_u]; PinvQ=[PinvQ,Pinv_u]; solved=0; end return %=========================================================================== %===== SOLVE CORRECTION EQUATION =========================================== %=========================================================================== function t=Solve_pce(theta,u,r,lsolver,par,nit) global Qschur PinvQ Pinv_u Pu L_precond switch lsolver case 'exact' t = exact(theta,[Qschur,u],r); case 'iluexact' t = iluexact(theta,[Qschur,u],r); case {'gmres','bicgstab','olsen'} if isempty(L_precond) %%% no preconditioning t = feval(lsolver,theta,... [Qschur,u],[Qschur,u],1,r,spar(par,nit)); else %%% solve left preconditioned system %%% compute vectors and matrices for skew projection Pinv_u=SolvePrecond(u); mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u]; %%% precondion and project r r=SolvePrecond(r); r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r); %%% solve preconditioned system t = feval(lsolver,theta,... [Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit)); end case {'cg','minres','symmlq'} if isempty(L_precond) %%% no preconditioning t = feval(lsolver,theta,... [Qschur,u],[Qschur,u],1,r,spar(par,nit)); else %%% solve two-sided expl. precond. system %%% compute vectors and matrices for skew projection Pinv_u=SolvePrecond(u,'L'); mu=[Pu,Qschur'*Pinv_u;u'*PinvQ,u'*Pinv_u]; %%% precondion and project r r=SolvePrecond(r,'L'); r=SkewProj([Qschur,u],[PinvQ,Pinv_u],mu,r); %%% solve preconditioned system t = feval(lsolver,theta,... [Qschur,u],[PinvQ,Pinv_u],mu,r,spar(par,nit)); %%% "unprecondition" solution t=SkewProj([PinvQ,Pinv_u],[Qschur,u],mu,t); t=SolvePrecond(t,'U'); end end return %======================================================================= %======= LINEAR SOLVERS ================================================ %======================================================================= function x = exact(theta,Q,r) global A_operator [n,k]=size(Q); [n,l]=size(r); if ischar(A_operator) [x,xtol]=bicgstab(theta,Q,Q,1,r,[5.0e-14/norm(r),200,4]); return end x = [A_operator-theta*speye(n,n),Q;Q',zeros(k,k)]\[r;zeros(k,l)]; x = x(1:n,1:l); return %---------------------------------------------------------------------- function x = iluexact(theta,Q,r) global L_precond U_precond [n,k]=size(Q); [n,l]=size(r); y = L_precond\[r,Q]; x = [U_precond,y(:,l+1:k+1);Q',zeros(k,k)]\[y(:,1:l);zeros(k,l)]; x = x(1:n,1:l); return %---------------------------------------------------------------------- function r = olsen(theta,Q,Z,M,r,par) return % %======= Iterative methods ============================================= % function x = bicgstab(theta,Q,Z,M,r,par) % BiCGstab(ell) % [x,rnrm] = bicgstab(theta,Q,Z,M,r,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=r % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % This function is specialized for use in JDQZ. % integer nmv: number of matrix multiplications % rnrm: relative residual norm % % par=[tol,mxmv,ell] where % integer m: max number of iteration steps % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: ETNA % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization -- % tol=par(1); max_it=par(2); l=par(3); n=size(r,1); rnrm=1; nmv=0; if max_it==0 | tol>=1, x=r; return, end rnrm=norm(r); snrm=rnrm; tol=tol*rnrm; sigma=1; omega=1; x=zeros(n,1); u=zeros(n,1); tr=r; % hist=rnrm; % -- Iteration loop while (rnrm > tol) & (nmv <= max_it) sigma=-omega*sigma; for j = 1:l, rho=tr'*r(:,j); bet=rho/sigma; u=r-bet*u; %%%%%% u(:,j+1)=Atilde*u(:,j) u(:,j+1)=mvp(theta,Q,Z,M,u(:,j)); sigma=tr'*u(:,j+1); alp=rho/sigma; x=x+alp*u(:,1); r=r-alp*u(:,2:j+1); %%%%%% r(:,j+1)=Atilde*r(:,j) r(:,j+1)=mvp(theta,Q,Z,M,r(:,j)); end gamma=r(:,2:l+1)\r(:,1); omega=gamma(l,1); x=x+r*[gamma;0]; u=u*[1;-gamma]; r=r*[1;-gamma]; rnrm = norm(r); nmv = nmv+2*l; % hist=[hist,rnrm]; end % figure(3), % plot([0:length(hist)-1]*2*l,log10(hist/snrm),'-*'), % drawnow, rnrm = rnrm/snrm; return %---------------------------------------------------------------------- function v = gmres(theta,Q,Z,M,v,par) % GMRES % [x,rnrm] = gmres(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Saad % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); n = size(v,1); max_it=min(par(2),n); rnrm = 1; nmv=0; if max_it==0 | tol>=1, return, end H = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)]; rnrm = norm(v); v = v/rnrm; V = [v]; tol = tol * rnrm; snrm = rnrm; y = [ rnrm ; zeros(max_it,1) ]; j=0; % hist=rnrm; while (nmv < max_it) & (rnrm > tol), j=j+1; nmv=nmv+1; v=mvp(theta,Q,Z,M,v); % [v, H(1:j+1,j)] = RepGS(V,v); [v,h] = RepGS(V,v); H(1:size(h,1),j)=h; V = [V, v]; for i = 1:j-1, a = Rot(:,i); H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j); end J=[j, j+1]; a=H(J,j); if a(2) ~= 0 cs = norm(a); a = a/cs; Rot(:,j) = a; H(J,j) = [cs; 0]; y(J) = [a'; -a(2) a(1)]*y(J); end rnrm = abs(y(j+1)); % hist=[hist,rnrm]; end % figure(3) % plot([0:length(hist)-1],log10(hist/snrm),'-*') % drawnow, pause J=[1:j]; v = V(:,J)*(H(J,J)\y(J)); rnrm = rnrm/snrm; return %====================================================================== %========== BASIC OPERATIONS ========================================== %====================================================================== function v=MV(v) global A_operator nm_operations if ischar(A_operator) v = feval(A_operator,v); else v = A_operator*v; end nm_operations = nm_operations+1; return %---------------------------------------------------------------------- function v=mvp(theta,Q,Z,M,v) % v=Atilde*v v = MV(v) - theta*v; v = SolvePrecond(v); v = SkewProj(Q,Z,M,v); return %---------------------------------------------------------------------- function u=SolvePrecond(u,flag); global L_precond U_precond if isempty(L_precond), return, end if nargin<2 if ischar(L_precond) if ischar(U_precond) u=feval(L_precond,u,U_precond); elseif isempty(U_precond) u=feval(L_precond,u); else u=feval(L_precond,u,'L'); u=feval(L_precond,u,'U'); end else u=U_precond\(L_precond\u); end else switch flag case 'U' if ischar(L_precond), u=feval(L_precond,u,'U'); else, u=U_precond\u; end case 'L' if ischar(L_precond), u=feval(L_precond,u,'L'); else, u=L_precond\u; end end end return %---------------------------------------------------------------------- function r=SkewProj(Q,Z,M,r); if ~isempty(Q), r=r-Z*(M\(Q'*r)); end return %---------------------------------------------------------------------- function ppar=spar(par,nit) % Changes par=[tol(:),max_it,ell] to % ppap=[TOL,max_it,ell] where % if lenght(tol)==1 % TOL=tol % else % red=tol(end)/told(end-1); tole=tol(end); % tol=[tol,red*tole,red^2*tole,red^3*tole,...] % TOL=tol(nit); % end k=size(par,2)-2; ppar=par(1,k:k+2); if k>1 if nit>k ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k)); else ppar(1,1)=par(1,max(nit,1)); end end ppar(1,1)=max(ppar(1,1),1.0e-8); return % %======= Iterative methods for symmetric systems ======================= % function x = cg(theta,Q,Z,M,r,par) % CG % [x,rnrm] = cg(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Hestenes and Stiefel % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); max_it=par(2); n = size(r,1); rnrm = 1; nmv=0; b=r; if max_it ==0 | tol>=1, x=r; return, end x= zeros(n,1); u=zeros(n,1); rho = norm(r); snrm = rho; rho = rho*rho; tol = tol*tol*rho; sigma=1; while ( rho > tol & nmv < max_it ) beta=rho/sigma; u=r-beta*u; y=smvp(theta,Q,Z,M,u); nmv=nmv+1; sigma=y'*r; alpha=rho/sigma; x=x+alpha*u; r=r-alpha*y; sigma=-rho; rho=r'*r; end % while rnrm=sqrt(rho)/snrm; return %---------------------------------------------------------------------- function x = minres(theta,Q,Z,M,r,par) % MINRES % [x,rnrm] = minres(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Paige and Saunders % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); max_it=par(2); n = size(r,1); rnrm = 1; nmv=0; if max_it ==0 | tol>=1, x=r; return, end x=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho; beta = 0; v_old = zeros(n,1); beta_t = 0; c = -1; s = 0; w = zeros(n,1); www = v; tol=tol*rho; while ( nmv < max_it & abs(rho) > tol ) wv =smvp(theta,Q,Z,M,v)-beta*v_old; nmv=nmv+1; alpha = v'*wv; wv = wv-alpha*v; beta = norm(wv); v_old = v; v = wv/beta; l1 = s*alpha - c*beta_t; l2 = s*beta; alpha_t = -s*beta_t - c*alpha; beta_t = c*beta; l0 = sqrt(alpha_t*alpha_t+beta*beta); c = alpha_t/l0; s = beta/l0; ww = www - l1*w; www = v - l2*w; w = ww/l0; x = x + (rho*c)*w; rho = s*rho; end % while rnrm=abs(rho)/snrm; return %---------------------------------------------------------------------- function x = symmlq(theta,Q,Z,M,r,par) % SYMMLQ % [x,rnrm] = symmlq(theta,Q,Z,M,b,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*M^(-1)*Q')*(U\L\(A-theta)). % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Paige and Saunders % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization tol=par(1); max_it=par(2); n = size(r,1); rnrm = 1; nmv=0; if max_it ==0 | tol>=1, x=r; return, end x=zeros(n,1); rho = norm(r); v = r/rho; snrm=rho; beta = 0; beta_t = 0; c = -1; s = 0; v_old = zeros(n,1); w = v; gtt = rho; g = 0; tol=tol*rho; while ( nmv < max_it & rho > tol ) wv = smvp(theta,Q,Z,M,v) - beta*v_old; nmv=nmv+1; alpha = v'*wv; wv = wv - alpha*v; beta = norm(wv); v_old = v; v = wv/beta; l1 = s*alpha - c*beta_t; l2 = s*beta; alpha_t = -s*beta_t - c*alpha; beta_t = c*beta; l0 = sqrt(alpha_t*alpha_t+beta*beta); c = alpha_t/l0; s = beta/l0; gt = gtt - l1*g; gtt = -l2*g; g = gt/l0; rho = sqrt(gt*gt+gtt*gtt); x = x + (g*c)*w + (g*s)*v; w = s*w - c*v; end % while rnrm=rho/snrm; return %---------------------------------------------------------------------- function v=smvp(theta,Q,Z,M,v) % v=Atilde*v v = SkewProj(Z,Q,M,v); v = SolvePrecond(v,'U'); v = MV(v) - theta*v; v = SolvePrecond(v,'L'); v = SkewProj(Q,Z,M,v); return %======================================================================= %========== Orthogonalisation ========================================== %======================================================================= function [v,y]=RepGS(V,v,gamma) % [v,y]=REP_GS(V,w) % If V orthonormal then [V,v] orthonormal and w=[V,v]*y; % If size(V,2)=size(V,1) then w=V*y; % % The orthonormalisation uses repeated Gram-Schmidt % with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion. % % [v,y]=REP_GS(V,w,GAMMA) % GAMMA=1 (default) same as [v,y]=REP_GS(V,w) % GAMMA=0, V'*v=zeros(size(V,2)) and w = V*y+v (v is not normalized). % coded by Gerard Sleijpen, August 28, 1998 if nargin < 3, gamma=1; end [n,d]=size(V); if size(v,2)==0, y=zeros(d,0); return, end nr_o=norm(v); nr=eps*nr_o; y=zeros(d,1); if d==0 if gamma, v=v/nr_o; y=nr_o; else, y=zeros(0,1); end, return end y=V'*v; v=v-V*y; nr_n=norm(v); ort=0; while (nr_n<0.5*nr_o & nr_n > nr) s=V'*v; v=v-V*s; y=y+s; nr_o=nr_n; nr_n=norm(v); ort=ort+1; end if nr_n <= nr, if ort>2, disp(' dependence! '), end if gamma % and size allows, expand with a random vector if d<n, v=RepGS(V,rand(n,1)); y=[y;0]; else, v=zeros(n,0); end else, v=0*v; end elseif gamma, v=v/nr_n; y=[y;nr_n]; end return %======================================================================= %============== Sorts Schur form ======================================= %======================================================================= function [Q,S]=SortSchur(A,sigma,gamma,kk) %[Q,S]=SortSchur(A,sigma) % A*Q=Q*S with diag(S) in order prescribed by sigma. % If sigma is a scalar then with increasing distance from sigma. % If sigma is string then according to string % ('LM' with decreasing modulus, etc) % %[Q,S]=SortSchur(A,sigma,gamma,kk) % if gamma==0, sorts only for the leading element % else, sorts for the kk leading elements l=size(A,1); if l<2, Q=1;S=A; return, elseif nargin==2, kk=l-1; elseif gamma, kk=min(kk,l-1); else, kk=1; sigma=sigma(1,:); end %%%------ compute schur form ------------- [Q,S]=schur(A); %% A*Q=Q*S, Q'*Q=eye(size(A)); %%% transform real schur form to complex schur form if norm(tril(S,-1),1)>0, [Q,S]=rsf2csf(Q,S); end %%%------ find order eigenvalues --------------- I = SortEig(diag(S),sigma); %%%------ reorder schur form ---------------- [Q,S] = SwapSchur(Q,S,I(1:kk)); return %---------------------------------------------------------------------- function I=SortEig(t,sigma); %I=SortEig(T,SIGMA) sorts the indices of T. % % T is a vector of scalars, % SIGMA is a string or a vector of scalars. % I is a permutation of (1:LENGTH(T))' such that: % if SIGMA is a vector of scalars then % for K=1,2,...,LENGTH(T) with KK = MIN(K,SIZE(SIGMA,1)) % ABS( T(I(K))-SIGMA(KK) ) <= ABS( T(I(J))-SIGMA(KK) ) % SIGMA(kk)=INF: ABS( T(I(K)) ) >= ABS( T(I(J)) ) % for all J >= K if ischar(sigma) switch sigma case 'LM' [s,I]=sort(-abs(t)); case 'SM' [s,I]=sort(abs(t)); case 'LR'; [s,I]=sort(-real(t)); case 'SR'; [s,I]=sort(real(t)); case 'BE'; [s,I]=sort(real(t)); I=twistdim(I,1); end else [s,I]=sort(abs(t-sigma(1,1))); ll=min(size(sigma,1),size(t,1)-1); for j=2:ll if sigma(j,1)==inf [s,J]=sort(abs(t(I(j:end)))); J=flipdim(J,1); else [s,J]=sort(abs(t(I(j:end))-sigma(j,1))); end I=[I(1:j-1);I(J+j-1)]; end end return %---------------------------------------------------------------------- function t=twistdim(t,k) d=size(t,k); J=1:d; J0=zeros(1,2*d); J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J); if k==1, t=t(I,:); else, t=t(:,I); end return %---------------------------------------------------------------------- function [Q,S]=SwapSchur(Q,S,I) % [Q,S]=SwapSchur(QQ,SS,P) % QQ and SS are square matrices of size K by K % P is the first part of a permutation of (1:K)'. % % If M = QQ*SS*QQ' and QQ'*QQ = EYE(K), SS upper triangular % then M*Q = Q*S with Q'*Q = EYE(K), S upper triangular % and D(1:LENGTH(P))=DD(P) where D=diag(S), DD=diag(SS) % % Computations uses Givens rotations. kk=min(length(I),size(S,1)-1); j=1; while (j<=kk & j==I(j)), j=j+1; end; while j<=kk i=I(j); for k=i-1:-1:j q = [S(k,k)-S(k+1,k+1),S(k,k+1)]; if q(1) ~= 0 q = q/norm(q); G = [[q(2);-q(1)],q']; J = [k,k+1]; Q(:,J) = Q(:,J)*G; S(:,J) = S(:,J)*G; S(J,:) = G'*S(J,:); end S(k+1,k) = 0; end I=I+(I<i); j=j+1; while (j<=kk & j==I(j)), j=j+1; end end return %---------------------------------------------------------------------- function [Q,Z,S,T]=SortQZ(A,B,sigma,gamma,kk) % % [Q,Z,S,T]=SORTQZ(A,B,SIGMA) % A and B are K by K matrices, SIGMA is a complex scalar or string. % SORTQZ computes the qz-decomposition of (A,B) with prescribed % ordering: A*Q=Z*S, B*Q=Z*T; % Q and Z are K by K unitary, % S and T are K by K upper triangular. % The ordering is as follows: % (DAIG(S),DAIG(T)) are the eigenpairs of (A,B) ordered % as prescribed by SIGMA. % % coded by Gerard Sleijpen, version Januari 12, 1998 l=size(A,1); if l<2; Q=1; Z=1; S=A; T=B; return elseif nargin==3, kk=l-1; elseif gamma, kk=min(kk,l-1); else, kk=1; sigma=sigma(1,:); end %%%------ compute qz form ---------------- [S,T,Z,Q]=qz(A,B); Z=Z'; S=triu(S); %%%------ sort eigenvalues --------------- I=SortEigPair(diag(S),diag(T),sigma); %%%------ sort qz form ------------------- [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1:kk)); return %---------------------------------------------------------------------- function I=SortEigPair(s,t,sigma) % I=SortEigPair(S,T,SIGMA) % S is a complex K-vectors, T a positive real K-vector % SIGMA is a string or a vector of pairs of complex scalars. % SortEigPair gives the index set I that sorts the pairs (S,T). % % If SIGMA is a pair of scalars then the sorting is % with increasing "chordal distance" w.r.t. SIGMA. % % The chordal distance D between a pair A and a pair B is defined as follows. % Scale A by a scalar F such that NORM(F*A)=1 and F*A(2)>=0, % scale B by a scalar G such that NORM(G*B)=1 and G*B(2)>=0, % then D(A,B)=ABS((F*A)*RROT(G*B)) where RROT(alpha,beta)=(beta,-alpha) % coded by Gerard Sleijpen, version Januari 14, 1998 n=sign(t); n=n+(n==0); t=abs(t./n); s=s./n; if ischar(sigma) switch sigma case {'LM','SM'} case {'LR','SR','BE'} s=real(s); end [s,I]=sort((-t./sqrt(s.*conj(s)+t.*t))); switch sigma case {'LM','LR'} I=flipdim(I,1); case {'SM','SR'} case 'BE' I=twistdim(I,1); end else n=sqrt(sigma.*conj(sigma)+1); ll=size(sigma,1); tau=[ones(ll,1)./n,-sigma./n]; tau=tau.'; n=sqrt(s.*conj(s)+t.*t); s=[s./n,t./n]; [t,I]=sort(abs(s*tau(:,1))); ll = min(ll,size(I,1)-1); for j=2:ll [t,J]=sort(abs(s(I(j:end),:)*tau(:,j))); I=[I(1:j-1);I(J+j-1)]; end end return %---------------------------------------------------------------------- function [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I) % [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P) % QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular. % P is the first part of a permutation of (1:K)'. % % Then Q and Z are K by K unitary, S and T are K by K upper triangular, % such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have % A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where % LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT). % % Computation uses Givens rotations. % % coded by Gerard Sleijpen, version October 12, 1998 kk=min(length(I),size(S,1)-1); j=1; while (j<=kk & j==I(j)), j=j+1; end while j<=kk i=I(j); for k = i-1:-1:j, %%% i>j, move ith eigenvalue to position j J = [k,k+1]; q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J); if q(1) ~= 0 q = q/norm(q); G = [[q(2);-q(1)],q']; Q(:,J) = Q(:,J)*G; S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G; end if abs(S(k+1,k))<abs(T(k+1,k)), q=T(J,k); else q=S(J,k); end if q(2) ~= 0 q=q/norm(q); G = [q';q(2),-q(1)]; Z(:,J) = Z(:,J)*G'; S(J,:) = G*S(J,:); T(J,:) = G*T(J,:); end T(k+1,k) = 0; S(k+1,k) = 0; end I=I+(I<i); j=j+1; while (j<=kk & j==I(j)), j=j+1; end end return %======================================================================= %======= SET PARAMETERS ================================================ %======================================================================= function [n,nselect,sigma,SCHUR,... jmin,jmax,tol,maxit,V,INTERIOR,SHOW,PAIRS,JDV,OLD,... lsolver,par] = ReadOptions(varargin) % Read options and set defaults global A_operator L_precond U_precond A_operator = varargin{1}; %%% determine dimension if ischar(A_operator) n=-1; if exist(A_operator) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',A_operator); errordlg(msg,'MATRIX'),n=-2; end if n==-1, eval('n=feval(A_operator,[],''dimension'');','n=-1;'), end else [n,n] = size(A_operator); if any(size(A_operator) ~= n) msg=sprintf(' The operator must be a square matrix or a string. '); errordlg(msg,'MATRIX'),n=-3; end end %%% defaults SCHUR = 0; jmin = -1; jmax = -1; p0 = 5; % jmin=nselect+p0 p1 = 5; % jmax=jmin+p1 tol = 1e-8; maxit = 200; V = zeros(0,0); INTERIOR= 0; SHOW = 0; PAIRS = 0; JDV = 0; OLD = 1e-4; lsolver = 'gmres'; ls_maxit= 200; ls_tol = [1,0.7]; ell = 4; par = [ls_tol,ls_maxit,ell]; options=[]; sigma=[]; varg=[]; L_precond = []; U_precond = []; for j = 2:nargin if isstruct(varargin{j}) options = varargin{j}; elseif ischar(varargin{j}) if length(varargin{j}) == 2 & isempty(sigma) sigma = varargin{j}; elseif isempty(L_precond) L_precond=varargin{j}; elseif isempty(U_precond) U_precond=varargin{j}; end elseif length(varargin{j}) == 1 varg = [varg,varargin{j}]; elseif min(size(varargin{j}))==1 sigma = varargin{j}; if size(sigma,1)==1, sigma=conj(sigma'); end elseif isempty(L_precond) L_precond=varargin{j}; elseif isempty(U_precond) U_precond=varargin{j}; end end if ischar(sigma) sigma0=sigma; sigma=upper(sigma); switch sigma case {'LM','LR','SR','BE','SM'} otherwise if exist(sigma0)==2 & isempty(L_precond) ok=1; eval('v=feval(sigma,zeros(n,1));','ok=0') if ok, L_precond=sigma0; sigma=[]; end end end end [s,I]=sort(varg); I=flipdim(I,2); J=[]; j=0; while j<length(varg) j=j+1; jj=I(j); s=varg(jj); if isreal(s) & (s == fix(s)) & (s > 0) if n==-1 n=s; eval('v=feval(A_operator,zeros(n,0));','n=-1;') if n>-1, J=[J,jj]; end end else if isempty(sigma), sigma=s; elseif ischar(sigma) & isempty(L_precond) ok=1; eval('v=feval(sigma0,zeros(n,1));','ok=0') if ok, L_precond=sigma0; sigma=s; end end, J=[J,jj]; end end varg(J)=[]; if n==-1, msg1=sprintf(' Cannot find the dimension of ''%s''. \n',A_operator); msg2=sprintf(' Put the dimension n in the parameter list: \n like'); msg3=sprintf('\t\n\n\t jdqr(''%s'',n,..), \n\n',A_operator); msg4=sprintf(' or let\n\n\t n = %s(',A_operator); msg5=sprintf('[],''dimension'')\n\n give n.'); msg=[msg1,msg2,msg3,msg4,msg5]; errordlg(msg,'MATRIX') end nselect=[]; if n<2, return, end if length(varg) == 1 nselect=min(n,varg); elseif length(varg)>1 if isempty(sigma), sigma=varg(end); varg(end)=[]; end nselect=min(n,min(varg)); end fopts = []; if ~isempty(options), fopts=fields(options); end if isempty(L_precond) if strmatch('Precond',fopts) L_precond = options.Precond; elseif strmatch('L_Precond',fopts) L_precond = options.L_Precond; end end if isempty(U_precond) & strmatch('U_Precond',fopts) U_precond = options.U_Precond; end if isempty(L_precond), ls_tol = [0.7,0.49]; end if ~isempty(L_precond) & ischar(L_precond) if exist(L_precond) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',L_precond); n=-1; elseif ~isempty(U_precond) & ~ischar(U_precond) & n>0 msg=sprintf(' L and U should both be strings or matrices'); n=-1; elseif strcmp(L_precond,U_precond) eval('v=feval(L_precond,zeros(n,1),''L'');','n=-1;') eval('v=feval(L_precond,zeros(n,1),''U'');','n=-1;') if n<0 msg='L and U use the same M-file'; msg1=sprintf(' %s.m \n',L_precond); msg2='Therefore L and U are called'; msg3=sprintf(' as\n\n\tw=%s(v,''L'')',L_precond); msg4=sprintf(' \n\tw=%s(v,''U'')\n\n',L_precond); msg5=sprintf('Check the dimensions and/or\n'); msg6=sprintf('put this "switch" in %s.m.',L_precond); msg=[msg,msg1,msg2,msg3,msg4,msg5,msg6]; else U_precond=0; end elseif ischar(A_operator) & strcmp(A_operator,L_precond) U_precond='preconditioner'; eval('v=feval(L_precond,zeros(n,1),U_precond);','n=-1;') if n<0 msg='Preconditioner and matrix use the same M-file'; msg1=sprintf(' %s. \n',L_precond); msg2='Therefore the preconditioner is called'; msg3=sprintf(' as\n\n\tw=%s(v,''preconditioner'')\n\n',L_precond); msg4='Put this "switch" in the M-file.'; msg=[msg,msg1,msg2,msg3,msg4]; end else eval('v=feval(L_precond,zeros(n,1));','n=-1') if n<0 msg=sprintf('''%s'' should produce %i-vectors',L_precond,n); end end end Ud=1; if ~isempty(L_precond) & ~ischar(L_precond) & n>0 if ~isempty(U_precond) & ischar(U_precond) msg=sprintf(' L and U should both be strings or matrices'); n=-1; elseif ~isempty(U_precond) if ~min([n,n]==size(L_precond) & [n,n]==size(U_precond)) msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1; end elseif min([n,n]==size(L_precond)) U_precond=speye(n); Ud=0; elseif min([n,2*n]==size(L_precond)) U_precond=L_precond(:,n+1:2*n); L_precond=L_precond(:,1:n); else msg=sprintf('The preconditioning matrix\n'); msg2=sprintf('should be %iX%i or %ix%i ([L,U]).\n',n,n,n,2*n); msg=[msg,msg2]; n=-1; end end if n<0, errordlg(msg,'PRECONDITIONER'), return, end ls_tol0=ls_tol; if strmatch('Tol',fopts), tol = options.Tol; end if isempty(nselect), nselect=min(n,5); end if strmatch('jmin',fopts), jmin=min(n,options.jmin); end if strmatch('jmax',fopts) jmax=min(n,options.jmax); if jmin<0, jmin=max(1,jmax-p1); end else if jmin<0, jmin=min(n,nselect+p0); end jmax=min(n,jmin+p1); end if strmatch('MaxIt',fopts), maxit = abs(options.MaxIt); end if strmatch('v0',fopts); V = options.v0; [m,d]=size(V); if m~=n | d==0 if m>n, V = V(1:n,:); end nrV=norm(V); if nrV>0, V=V/nrV; end d=max(d,1); V = [V; ones(n-m,d) +0.1*rand(n-m,d)]; end else V = ones(n,1) +0.1*rand(n,1); d=1; end if strmatch('TestSpace',fopts), INTERIOR = boolean(options.TestSpace,... [INTERIOR,0,1,1.1,1.2],strvcat('standard','harmonic')); end if isempty(sigma) if INTERIOR, sigma=0; else, sigma = 'LM'; end elseif ischar(sigma) switch sigma case {'LM','LR','SR','BE'} case {'SM'} sigma=0; otherwise if INTERIOR, sigma=0; else, sigma='LM'; end end end if strmatch('Schur',fopts), SCHUR = boolean(options.Schur,SCHUR); end if strmatch('Disp',fopts), SHOW = boolean(options.Disp,[SHOW,2]); end if strmatch('Pairs',fopts), PAIRS = boolean(options.Pairs,PAIRS); end if strmatch('AvoidStag',fopts),JDV = boolean(options.AvoidStag,JDV); end if strmatch('Track',fopts) OLD = boolean(options.Track,[OLD,0,OLD,inf],strvcat('no','yes')); end OLD=max(abs(OLD),10*tol); if strmatch('LSolver',fopts), lsolver = lower(options.LSolver); end switch lsolver case {'exact'} L_precond=[]; if ischar(A_operator) msg=sprintf('The operator must be a matrix for ''exact''.'); msg=[msg,sprintf('\nDo you want to solve the correction equation')]; msg=[msg,sprintf('\naccurately with an iterative solver (BiCGstab)?')]; button=questdlg(msg,'Solving exactly','Yes','No','Yes'); if strcmp(button,'No'), n=-1; return, end end case {'iluexact'} if ischar(L_precond) msg=sprintf('The preconditioner must be matrices for ''iluexact''.'); errordlg(msg,'Solving with ''iluexact''') n=-1; return end case {'olsen'} case {'cg','minres','symmlq'} ls_tol=1.0e-12; case 'gmres' ls_maxit=5; case 'bicgstab' ls_tol=1.0e-10; otherwise error(['Unknown method ''' lsolver '''.']); end if strmatch('LS_MaxIt',fopts), ls_maxit=abs(options.LS_MaxIt); end if strmatch('LS_Tol',fopts), ls_tol=abs(options.LS_Tol); end if strmatch('LS_ell',fopts), ell=round(abs(options.LS_ell)); end par=[ls_tol,ls_maxit,ell]; if SHOW fprintf('\n'),fprintf('PROBLEM\n') if ischar(A_operator) fprintf(' A: ''%s''\n',A_operator); elseif issparse(A_operator) fprintf(' A: [%ix%i sparse]\n',n,n); else fprintf(' A: [%ix%i double]\n',n,n); end fprintf(' dimension: %i\n',n); fprintf(' nselect: %i\n\n',nselect); fprintf('TARGET\n') if ischar(sigma) fprintf(' sigma: ''%s''',sigma) else Str=ShowLambda(sigma); fprintf(' sigma: %s',Str) end fprintf('\n\n') fprintf('OPTIONS\n'); fprintf(' Schur: %i\n',SCHUR); fprintf(' Tol: %g\n',tol); fprintf(' Disp: %i\n',SHOW); fprintf(' jmin: %i\n',jmin); fprintf(' jmax: %i\n',jmax); fprintf(' MaxIt: %i\n',maxit); fprintf(' v0: [%ix%i double]\n',size(V)); fprintf(' TestSpace: %g\n',INTERIOR); fprintf(' Pairs: %i\n',PAIRS); fprintf(' AvoidStag: %i\n',JDV); fprintf(' Track: %g\n',OLD); fprintf(' LSolver: ''%s''\n',lsolver); switch lsolver case {'exact','iluexact','olsen'} case {'cg','minres','symmlq','gmres','bicgstab'} if length(ls_tol)>1 fprintf(' LS_Tol: ['); fprintf(' %g',ls_tol); fprintf(' ]\n'); else fprintf(' LS_Tol: %g\n',ls_tol); end fprintf(' LS_MaxIt: %i\n',ls_maxit); end if strcmp(lsolver,'bicgstab') fprintf(' LS_ell: %i\n',ell); end if isempty(L_precond) fprintf(' Precond: []\n'); else StrL='Precond'; StrU='U precond'; Us='double'; Ls=Us; ok=0; if issparse(L_precond), Ls='sparse'; end if ~isempty(U_precond) & Ud, StrL='L precond'; ok=1; if issparse(U_precond), Us='sparse'; end end if ischar(L_precond) fprintf('%13s: ''%s''\n',StrL,L_precond); if ok if U_precond~=0 & ~strcmp(U_precond,'preconditioner') fprintf('%13s: ''%s''\n',StrU,U_precond); else fprintf('%13s: ''%s''\n',StrU,L_precond); end end else fprintf('%13s: [%ix%i %s]\n',StrL,n,n,Ls); if ok & Ud, fprintf('%13s: [%ix%i %s]\n',StrU,n,n,Us); end end end fprintf('\n') string1='%13s: ''%s'''; string2='\n\t %s'; switch INTERIOR case 0 fprintf(string1,'TestSpace','Standard, W = V ') fprintf(string2,'V W: V orthogonal') fprintf(string2,'W=A*V') case 1 fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V') fprintf(string2,'V W: V and W orthogonal') fprintf(string2,'AV-Q*E=W*R where AV=A*V-sigma*V and E=Q''*AV') case 1.1 fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V') fprintf(string2,'V W AV: V and W orthogonal') fprintf(string2,'AV=A*V-sigma*V, AV-Q*Q''*AV=W*R') case 1.2 fprintf(string1,'TestSpace','Harmonic, W = A*V - sigma*V') fprintf(string2,'V W: W orthogonal') fprintf(string2,'W=AV-Q*E where AV=A*V-sigma*V and E=Q''*AV') otherwise fprintf(string1,'TestSpace','Experimental') end % switch INTERIOR fprintf('\n\n') end % if SHOW if ischar(sigma) & INTERIOR >=1 msg1=sprintf('\n The choice sigma = ''%s'' does not match',sigma); msg2=sprintf('\n the search for INTERIOR eigenvalues.'); msg3=sprintf('\n Specify a numerical value for sigma'); msg4=sprintf(',\n for instance, a value that is '); switch sigma case {'LM'} % sigma='SM'; msg5=sprintf('absolute large.\n'); msg4=[msg4,msg5]; case {'LR'} % sigma='SP'; % smallest positive real msg5=sprintf('positive large.\n'); msg4=[msg4,msg5]; case {'SR'} % sigma='LN'; % largest negative real msg5=sprintf('negative and absolute large.\n'); msg4=[msg4,msg5]; case {'BE'} % sigma='AS'; % alternating smallest pos., largest neg msg4=sprintf('.\n'); end msg=[msg1,msg2,msg3,msg4]; msg5=sprintf(' Do you want to continue with sigma=0?'); msg=[msg,msg5]; button=questdlg(msg,'Finding Interior Eigenvalues','Yes','No','Yes'); if strcmp(button,'Yes'), sigma=0, else, n=-1; end end return %------------------------------------------------------------------- function x = boolean(x,gamma,string) %Y = BOOLEAN(X,GAMMA,STRING) % GAMMA(1) is the default. % If GAMMA is not specified, GAMMA = 0. % STRING is a matrix of accepted strings. % If STRING is not specified STRING = ['no ';'yes'] % STRING(I,:) and GAMMA(I) are accepted expressions for X % If X=GAMMA(I) then Y=X. If X=STRING(I,:), then Y=GAMMA(I+1). % For other values of X, Y=GAMMA(1); if nargin < 2, gamma=0; end if nargin < 3, string=strvcat('no','yes'); gamma=[gamma,0,1]; end if ischar(x) i=strmatch(lower(x),string,'exact'); if isempty(i),i=1; else, i=i+1; end, x=gamma(i); elseif max((gamma-x)==0) elseif gamma(end) == inf else, x=gamma(1); end return %------------------------------------------------------------------- function possibilities fprintf('\n') fprintf('PROBLEM\n') fprintf(' A: [ square matrix | string ]\n'); fprintf(' nselect: [ positive integer {5} ]\n\n'); fprintf('TARGET\n') fprintf(' sigma: [ scalar | vector of scalars |\n'); fprintf(' ''LM'' | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\n\n'); fprintf('OPTIONS\n'); fprintf(' Schur: [ yes | {no} ]\n'); fprintf(' Tol: [ positive scalar {1e-8} ]\n'); fprintf(' Disp: [ yes | {no} | 2 ]\n'); fprintf(' jmin: [ positive integer {nselect+5} ]\n'); fprintf(' jmax: [ positive integer {jmin+5} ]\n'); fprintf(' MaxIt: [ positive integer {200} ]\n'); fprintf(' v0: [ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\n'); fprintf(' TestSpace: [ Standard | {Harmonic} ]\n'); fprintf(' Pairs: [ yes | {no} ]\n'); fprintf(' AvoidStag: [ yes | {no} ]\n'); fprintf(' Track: [ {yes} | no | non-negative scalar {1e-4} ]\n'); fprintf(' LSolver: [ {gmres} | bicgstab ]\n'); fprintf(' LS_Tol: [ row of positive scalars {[1,0.7]} ]\n'); fprintf(' LS_MaxIt: [ positive integer {5} ]\n'); fprintf(' LS_ell: [ positive integer {4} ]\n'); fprintf(' Precond: [ n by 2n matrix | string {identity} ]\n'); fprintf('\n') return %=========================================================================== %============= OUTPUT FUNCTIONS ============================================ %=========================================================================== function varargout=ShowLambda(lambda,kk) for k=1:size(lambda,1); if k>1, Str=[Str,sprintf('\n%15s','')]; else, Str=[]; end rlambda=real(lambda(k,1)); ilambda=imag(lambda(k,1)); Str=[Str,sprintf(' %+11.4e',rlambda)]; if abs(ilambda)>100*eps*abs(rlambda) if ilambda>0 Str=[Str,sprintf(' + %10.4ei',ilambda)]; else Str=[Str,sprintf(' - %10.4ei',-ilambda)]; end end end if nargout == 0 if nargin == 2 Str=[sprintf('\nlambda(%i) =',kk),Str]; else Str=[sprintf('\nDetected eigenvalues:\n\n%15s',''),Str]; end fprintf('%s\n',Str) else varargout{1}=Str; end return %=========================================================================== function DispResult(s,nr,gamma) if nargin<3, gamma=0; end extra=''; if nr > 100*eps & gamma extra=' norm > 100*eps !!! '; end if gamma<2 | nr>100*eps fprintf('\n %35s: %0.5g\t%s',s,nr,extra) end return %=========================================================================== function STATUS0=MovieTheta(n,nit,Lambda,jmin,tau,LOCKED,SHRINK) % MovieTheta(n,nit,Lambda,jmin,tau,nr<t_tol,j==jmax); global A_operator Rschur EigMATLAB CIRCLE MovieAxis M_STATUS f=256; if nargin==0, if ~isempty(CIRCLE) %figure(f), buttons(f,-2); hold off, refresh end return end if nit==0 EigMATLAB=[]; if ~ischar(A_operator) & n<201 EigMATLAB=eig(full(A_operator)); end CIRCLE=0:0.005:1; CIRCLE=exp(CIRCLE*2*pi*sqrt(-1)); if ischar(tau) switch tau case {'LR','SR'} if ~ischar(A_operator) CIRCLE=norm(A_operator,'inf')*[sqrt(-1),-sqrt(-1)]+1; end end end Explanation(~isempty(EigMATLAB),f-1) end %if gcf~=f, figure(f), end jmin=min(jmin,length(Lambda)); %plot(real(Lambda(1:jmin)),imag(Lambda(1:jmin)),'bo'); if nit>0, axis(MovieAxis), end, hold on pls='bo'; if SHRINK, pls='mo'; end %plot(real(Lambda(jmin+1:end)),imag(Lambda(jmin+1:end)),pls) %plot(real(EigMATLAB),imag(EigMATLAB),'cp'); THETA=diag(Rschur); %plot(real(THETA),imag(THETA),'k*'); x=real(Lambda(1)); y=imag(Lambda(1)); %plot(x,y,'kd'), pls='ks'; if LOCKED, plot(x,y,'ks'), pls='ms'; end if ischar(tau), tau=0; end delta=Lambda([1,jmin])-tau; if length(CIRCLE)~=2, delta=abs(delta); % plot(real(tau),imag(tau),pls) else, delta=real(delta); end for i=1:1+SHRINK, zeta=delta(i)*CIRCLE+tau; % plot(real(zeta),imag(zeta),'r:'), end if nit==0 buttons(f,-1); hold off, zoom on end title('legend see figure(255)') if SHRINK, STATUS0=buttons(f,2); if STATUS0, return, end, end STATUS0=buttons(f,1); drawnow, hold off return %============================================================= function Explanation(E,f) %if gcf~=f, figure(f), end HL=plot(0,0,'kh',0,0,'bo'); hold on StrL=str2mat('Detected eigenvalues','Approximate eigenvalues'); if E HL=[HL;plot(0,0,'cp')]; StrL=str2mat(StrL,'Exact eigenvenvalues'); end HL=[HL;plot(0,0,'kd',0,0,'ks',0,0,'r:')]; % StrL=str2mat(StrL,'Tracked app. eig.','target',... % 'inner/outer bounds for restart'); StrL=str2mat(StrL,'Selected approximate eigenvalue','target',... 'inner/outer bounds for restart'); legend(HL,StrL), hold on, drawnow, hold off title('legend for figure(256)') return %============================================================= function STATUS0=buttons(f,push) % push=0: do nothing % push>0: check status buttons, % STATUS0=1 if break else STATUS0=0. % push=-1: make buttons for pause and break % push=-2: remove buttons global M_STATUS MovieAxis if push>0 % check status buttons ud = get(f,'UserData'); if ud.pause ==1, M_STATUS=1; end if ud.break ==1, STATUS0=1; ud.pause=0; ud.break=0; set(f,'UserData',ud); return, else, STATUS0=0; end if push>1 ud.pause=0; set(f,'UserData',ud); while M_STATUS ud = get(f,'UserData'); pause(0.1) if ud.pause, M_STATUS=0; end if ud.break, M_STATUS=0; STATUS0=1; end MovieAxis=axis; end ud.pause=0; ud.break=0; set(f,'UserData',ud); end elseif push==0, STATUS0=0; return elseif push==-1 % make buttons ud = []; h = findobj(f,'Tag','pause'); if isempty(h) ud.pause = 0; pos = get(0,'DefaultUicontrolPosition'); pos(1) = pos(1) - 15; pos(2) = pos(2) - 15; str = 'ud=get(gcf,''UserData''); ud.pause=1; set(gcf,''UserData'',ud);'; uicontrol( ... 'Style','push', ... 'String','Pause', ... 'Position',pos, ... 'Callback',str, ... 'Tag','pause'); else set(h,'Visible','on'); % make sure it's visible if ishold oud = get(f,'UserData'); ud.pause = oud.pause; % don't change old ud.pause status else ud.pause = 0; end end h = findobj(f,'Tag','break'); if isempty(h) ud.break = 0; pos = get(0,'DefaultUicontrolPosition'); pos(1) = pos(1) + 50; pos(2) = pos(2) - 15; str = 'ud=get(gcf,''UserData''); ud.break=1; set(gcf,''UserData'',ud);'; uicontrol( ... 'Style','push', ... 'String','Break', ... 'Position',pos, ... 'Callback',str, ... 'Tag','break'); else set(h,'Visible','on'); % make sure it's visible if ishold oud = get(f,'UserData'); ud.break = oud.break; % don't change old ud.break status else ud.break = 0; end end set(f,'UserData',ud); M_STATUS=0; STATUS0=0; hold off, zoom on MA=axis; nl=MA/10; MovieAxis = MA-max(nl([2,4])-nl([1,3]))*[1,-1,1,-1]; else % remove buttons set(findobj(f,'Tag','pause'),'Visible','off'); set(findobj(f,'Tag','break'),'Visible','off'); STATUS0=0; return, refresh end return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
lmnn.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/lmnn.m
5,421
utf_8
8d5b80dee8cf8730a96c0c415c5876fc
function [M, L, Y, C] = lmnn(X, labels) %LMNN Learns a metric using large-margin nearest neighbor metric learning % % [M, L, Y, C] = lmnn(X, labels) % % The function uses large-margin nearest neighbor (LMNN) metric learning to % learn a metric on the data set specified by the NxD matrix X and the % corresponding Nx1 vector labels. The metric is returned in M. % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % Initialize some variables [N, D] = size(X); assert(length(labels) == N); [lablist, ~, labels] = unique(labels); K = length(lablist); label_matrix = false(N, K); label_matrix(sub2ind(size(label_matrix), (1:length(labels))', labels)) = true; same_label = logical(double(label_matrix) * double(label_matrix')); M = eye(D); C = Inf; prev_C = Inf; % Set learning parameters min_iter = 50; % minimum number of iterations max_iter = 1000; % maximum number of iterations eta = .1; % learning rate mu = .5; % weighting of pull and push terms tol = 1e-3; % tolerance for convergence best_C = Inf; % best error obtained so far best_M = M; % best metric found so far no_targets = 3; % number of target neighbors % Select target neighbors sum_X = sum(X .^ 2, 2); DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (X * X'))); DD(~same_label) = Inf; DD(1:N + 1:end) = Inf; [~, targets_ind] = sort(DD, 2, 'ascend'); targets_ind = targets_ind(:,1:no_targets); targets = false(N, N); targets(sub2ind([N N], vec(repmat((1:N)', [1 no_targets])), vec(targets_ind))) = true; % Compute pulling term between target neigbhors to initialize gradient slack = zeros(N, N, no_targets); G = zeros(D, D); for i=1:no_targets G = G + (1 - mu) .* (X - X(targets_ind(:,i),:))' * (X - X(targets_ind(:,i),:)); end % Perform main learning iterations iter = 0; while (prev_C - C > tol || iter < min_iter) && iter < max_iter % Compute pairwise distances under current metric sum_X = sum((X * M) .* X, 2); DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * ((X * M) * X'))); % Compute value of slack variables old_slack = slack; for i=1:no_targets slack(:,:,i) = ~same_label .* max(0, bsxfun(@minus, 1 + DD(sub2ind([N N], (1:N)', targets_ind(:,i))), DD)); end % Compute value of cost function prev_C = C; C = (1 - mu) .* sum(DD(targets)) + ... % push terms between target neighbors mu .* sum(slack(:)); % pull terms between impostors % Maintain best solution found so far (subgradient method) if C < best_C best_C = C; best_M = M; end % Perform gradient update for i=1:no_targets % Add terms for new violations [r, c] = find(slack(:,:,i) > 0 & old_slack(:,:,i) == 0); G = G + mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ... (X(r,:) - X(targets_ind(r, i),:)) - ... (X(r,:) - X(c,:))' * (X(r,:) - X(c,:))); % Remove terms for resolved violations [r, c] = find(slack(:,:,i) == 0 & old_slack(:,:,i) > 0); G = G - mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ... (X(r,:) - X(targets_ind(r, i),:)) - ... (X(r,:) - X(c,:))' * (X(r,:) - X(c,:))); end M = M - (eta ./ N) .* G; % Project metric back onto the PSD cone [V, L] = eig(M); V = real(V); L = real(L); ind = find(diag(L) > 0); if isempty(ind) warning('Projection onto PSD cone failed. All eigenvalues were negative.'); break end M = V(:,ind) * L(ind, ind) * V(:,ind)'; if any(isinf(M(:))) warning('Projection onto PSD cone failed. Metric contains Inf values.'); break end if any(isnan(M(:))) warning('Projection onto PSD cone failed. Metric contains NaN values.'); break end % Update learning rate if prev_C > C eta = eta * 1.01; else eta = eta * .5; end % Print out progress iter = iter + 1; no_slack = sum(slack(:) > 0); if rem(iter, 10) == 0 [~, sort_ind] = sort(DD, 2, 'ascend'); disp(['Iteration ' num2str(iter) ': error is ' num2str(C ./ N) ... ', nearest neighbor error is ' num2str(sum(labels(sort_ind(:,2)) ~= labels) ./ N) ... ', number of constraints: ' num2str(no_slack)]); end end % Return best metric and error M = best_M; C = best_C; % Compute mapped data [L, S, ~] = svd(M); L = bsxfun(@times, sqrt(diag(S)), L); Y = X * L; end function x = vec(x) x = x(:); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
d2p.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/d2p.m
3,487
utf_8
0c7024a8039ea16b937d283585883fc3
function [P, beta] = d2p(D, u, tol) %D2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = d2p(D, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(D, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Run over all datapoints for i=1:n if ~rem(i, 500) disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; % why not: H = exp(-sum(P(P > 1e-5) .* log(P(P > 1e-5)))); ??? P = P / sumP; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
cg_update.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/cg_update.m
3,715
utf_8
1556078ae7c31950ec738949384cf180
% Version 1.000 % % Code provided by Ruslan Salakhutdinov and Geoff Hinton % % Permission is granted for anyone to copy, use, modify, or distribute this % program and accompanying programs and documents for any purpose, provided % this copyright notice is retained and prominently displayed, along with % a note saying that the original programs are available from our % web page. % The programs and documents are distributed without any warranty, express or % implied. As the programs were written for research purposes only, they have % not been tested to the degree that would be advisable in any important % application. All use of these programs is entirely at the user's own risk. % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology function [f, df] = cg_update(VV, Dim, XX) l1 = Dim(1); l2 = Dim(2); l3 = Dim(3); l4 = Dim(4); l5 = Dim(5); l6 = Dim(6); l7 = Dim(7); l8 = Dim(8); l9 = Dim(9); N = size(XX, 1); % Extract weights back from VV w1 = reshape(VV(1:(l1 + 1) * l2), l1 + 1, l2); xxx = (l1 + 1) * l2; w2 = reshape(VV(xxx + 1:xxx + (l2 + 1) * l3), l2 + 1, l3); xxx = xxx + (l2 + 1) * l3; w3 = reshape(VV(xxx + 1:xxx + (l3 + 1) * l4), l3 + 1, l4); xxx = xxx + (l3 + 1) * l4; w4 = reshape(VV(xxx + 1:xxx + (l4 + 1) * l5), l4 + 1, l5); xxx = xxx + (l4 + 1) * l5; w5 = reshape(VV(xxx + 1:xxx + (l5 + 1) * l6), l5 + 1, l6); xxx = xxx + (l5 + 1) * l6; w6 = reshape(VV(xxx + 1:xxx + (l6 + 1) * l7), l6 + 1, l7); xxx = xxx + (l6 + 1) * l7; w7 = reshape(VV(xxx + 1:xxx + (l7 + 1) * l8), l7 + 1, l8); xxx = xxx + (l7 + 1) * l8; w8 = reshape(VV(xxx + 1:xxx + (l8 + 1) * l9), l8 + 1, l9); % Evaluate points XX = [XX ones(N, 1)]; w1probs = 1 ./ (1 + exp(-XX * w1)); w1probs = [w1probs ones(N,1)]; w2probs = 1 ./ (1 + exp(-w1probs * w2)); w2probs = [w2probs ones(N,1)]; w3probs = 1 ./ (1 + exp(-w2probs * w3)); w3probs = [w3probs ones(N,1)]; w4probs = w3probs * w4; w4probs = [w4probs ones(N,1)]; w5probs = 1 ./ (1 + exp(-w4probs * w5)); w5probs = [w5probs ones(N,1)]; w6probs = 1 ./ (1 + exp(-w5probs * w6)); w6probs = [w6probs ones(N,1)]; w7probs = 1 ./ (1 + exp(-w6probs * w7)); w7probs = [w7probs ones(N,1)]; XXout = 1 ./ (1 + exp(-w7probs * w8)); % Compute gradients f = (-1 / N) * sum(sum(XX(:,1:end - 1) .* log(XXout) + (1 - XX(:,1:end - 1)) .* log(1 - XXout))); IO = (1 / N) * (XXout - XX(:,1:end - 1)); Ix8 = IO; dw8 = w7probs'*Ix8; Ix7 = (Ix8 * w8') .* w7probs .* (1 - w7probs); Ix7 = Ix7(:,1:end - 1); dw7 = w6probs' * Ix7; Ix6 = (Ix7*w7') .* w6probs .* (1 - w6probs); Ix6 = Ix6(:,1:end - 1); dw6 = w5probs' * Ix6; Ix5 = (Ix6 * w6') .* w5probs .* (1 - w5probs); Ix5 = Ix5(:,1:end - 1); dw5 = w4probs' * Ix5; Ix4 = (Ix5 * w5'); Ix4 = Ix4(:,1:end - 1); dw4 = w3probs' * Ix4; Ix3 = (Ix4 * w4') .* w3probs .* (1 - w3probs); Ix3 = Ix3(:,1:end - 1); dw3 = w2probs' * Ix3; Ix2 = (Ix3 * w3') .* w2probs .* (1 - w2probs); Ix2 = Ix2(:,1:end - 1); dw2 = w1probs' * Ix2; Ix1 = (Ix2 * w2') .* w1probs .* (1 - w1probs); Ix1 = Ix1(:,1:end - 1); dw1 = XX' * Ix1; % Return gradients df = [dw1(:)' dw2(:)' dw3(:)' dw4(:)' dw5(:)' dw6(:)' dw7(:)' dw8(:)']';
github
umariqb/3D_Pose_Estimation_CVPR2016-master
lmvu.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/lmvu.m
8,540
utf_8
c8003ed7ff0fd0e226776c42c72ad385
function [mappedX, mapping] = lmvu(X, no_dims, K, LL) %LMVU Performs Landmark MVU on dataset X % % [mappedX, mapping] = lmvu(X, no_dims, k1, k2) % % The function performs Landmark MVU on the DxN dataset X. The value of k1 % represents the number of nearest neighbors that is employed in the MVU % constraints. The value of k2 represents the number of nearest neighbors % that is employed to compute the reconstruction weights (for embedding the % non-landmark points). % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology if ~exist('K', 'var') K = 3; end if ~exist('LL', 'var') LL = 12; end % Save some data for out-of-sample extension if ischar(K) error('Adaptive neighborhood selection not supported for landmark MVU.'); end mapping.k1 = K; mapping.k2 = LL; mapping.X = X; % Initialize some variables N = size(X, 2); % number of datapoints B = ceil(0.02 * N); % number of landmark points % Set some parameters parameters pars.ep = eps; pars.fastmode = 1; pars.warmup = K * B / N; pars.verify = 1; pars.angles = 1; pars.maxiter = 100; pars.noise = 0; pars.ignore = 0.1; pars.penalty = 1; pars.factor = 0.9999; % Identify nearest neighbors disp('Identifying nearest neighbors...'); KK = max(LL, K); X = L2_distance(X, X); % memory-intensive: O(n^{2}) !!! [foo, neighbors] = find_nn(X, KK); neighbors = neighbors'; % Get inverse of reconstruction weight matrix Pia = getPia(B, LL, X, neighbors); % Generate SDP problem disp('Generating SDP problem...'); neighbors = neighbors(1:K,:); clear temp index sorted nck = nchoosek(1:K + 1, 2); AA = zeros(N * K, 2); pos3 = 1; for i=1:N ne = neighbors(:,i); nne = [ne; i]; pairs = nne(nck); js = pairs(:,1); ks = pairs(:,2); AA(pos3:pos3 + length(js) - 1,:) = sort([js ks], 2); pos3 = pos3 + length(js); if i == B AA = unique(AA, 'rows'); ForceC = size(AA, 1); end if pos3 > size(AA, 1) && i < N AA = unique(AA, 'rows'); pos3 = size(AA, 1) + 1; AA = [AA; zeros(round(N / (N - i) * pos3), 2)]; fprintf('.'); end end AA = unique(AA, 'rows'); AA = AA(2:end,:); clear neighbors ne v2 v3 js ks bb = zeros(1, size(AA, 1)); for i=1:size(AA, 1) bb(i) = sum((X(:,AA(i, 1)) - X(:,AA(i, 2))) .^ 2); end disp(' '); % Reduce the number of forced vectors ii = (1:ForceC)'; jj = zeros(1, size(AA, 1)); jj(ii) = 1; jj = find(jj == 0); jj1 = jj(jj <= ForceC); jj2 = jj(jj > ForceC); jj2 = jj2(randperm(length(jj2))); jj1 = jj1(randperm(length(jj1))); corder = [ii; jj1'; jj2']; AA = AA(corder,:); bb = bb(corder); ForceC = length(ii); clear temp jj1 jj2 jj ii Const = max(round(pars.warmup * size(AA, 1)), ForceC); [A, b, AA, bb] = getConstraints(AA, Pia, bb, B, Const, pars); Qt = sum(Pia, 1)' * sum(Pia, 1); A = [Qt(:)'; A]; b = [0; b]; clear K; solved = 0; % Start SDP iterations disp('Perform semi-definite programming...'); disp('CSDP OUTPUT ============================================================================='); while solved == 0 % Initialize some variables c = -vec(Pia' * Pia); flags.s = B; flags.l = size(A, 1) - 1; A = [[zeros(1,flags.l); speye(flags.l)] A]; % Set c (employ penalty) c = [ones(ForceC, 1) .* max(max(c)); zeros(flags.l - ForceC, 1); c]; % Launch the CSDP solver options.maxiter=pars.maxiter; [x, d, z, info] = csdp(A, b, c, flags, options); K = mat(x(flags.l + 1:flags.l + flags.s ^ 2)); % Check whether a solution is reached solved = isempty(AA); A = A(:,flags.l + 1:end); xx = K(:); if size(AA, 1) Aold = size(A,1); total = 0; while size(A, 1) - Aold < Const && ~isempty(AA) [newA, newb, AA, bb] = getConstraints(AA, Pia, bb, B, Const, pars); jj = find(newA * xx - newb > pars.ignore * abs(newb)); if info == 2 jj = 1:size(newA, 1); end total = total + length(jj); A(size(A,1) + 1:size(A,1) + length(jj),:) = newA(jj,:); b(length(b) + 1:length(b) + length(jj)) = newb(jj); end if total == 0 solved = 1; end else solved=1; end if solved == 1 && pars.maxiter < 100 pars.maxiter = 100; end end disp('========================================================================================='); % Perform eigendecomposition of kernel matrix to compute Y disp('Perform eigendecomposition to obtain low-dimensional data representation...'); [V, D] = eig(K); V = V * sqrt(D); Y = (V(:,end:-1:1))'; mappedX = Y * Pia'; % Reorder data in original order mappedX = mappedX(1:no_dims,:); % Set some information for the out-of-sample extension mapping.Y = Y; mapping.D = X; mapping.no_landmarks = B; mapping.no_dims = no_dims; % Function that computes LLE weight matrix function Q = getPia(B, LL, X, neighbors) % Initialize some variables N = size(X,2); % Compute reconstruction weights disp('Computing reconstruction weights...'); tol = 1e-7; Pia = sparse([], [], [], B, N); for i=1:N z = X(:,neighbors(:,i)) - repmat(X(:,i), 1, LL); C = z' * z; C = C + tol * trace(C) * eye(LL) / LL; invC = inv(C); Pia(neighbors(:,i),i) = sum(invC)' / sum(sum(invC)); end % Fill sparse LLE weight matrix M = speye(N) + sparse([], [], [], N, N, N * LL .^ 2); for i=1:N j = neighbors(:,i); w = Pia(j, i); M(i, j) = M(i, j) - w'; M(j, i) = M(j, i) - w; M(j, j) = M(j, j) + w * w'; end % Invert LLE weight matrix disp('Invert reconstruction weight matrix...'); Q = -M(B + 1:end, B + 1:end) \ M(B + 1:end, 1:B); Q = [eye(B); Q]; % Functions that constructs the constraints for the SDP function [A, b, AAomit, bbomit] = getConstraints(AA, Pia, bb, B, Const, pars) % Initialize some variables pos2 = 0; perm = 1:size(AA,1); if size(AA, 1) > Const AAomit = AA(perm(Const + 1:end),:); bbomit = bb(perm(Const + 1:end)); AA = AA(perm(1:Const),:); bb = bb(perm(1:Const)); else AAomit = []; bbomit = []; end % Allocate some memory persistent reqmem; if isempty(reqmem) A2 = zeros(size(AA, 1) * B, 3); else A2 = zeros(reqmem, 3); end % Set the constraints pos = 0; for j=1:size(AA, 1) % Evaluate for current row in AA ii = AA(j, 1); jj = AA(j, 2); Q = Pia(ii,:)' * Pia(ii,:) - 2 .* Pia(jj,:)' * Pia(ii,:) + Pia(jj,:)' * Pia(jj,:); Q = (Q + Q') ./ 2; it = find(abs(Q) > pars.ep .^ 2); % Constraint found if ~isempty(it) % Allocate more memory if needed pos = pos + 1; if pos2 + length(it) > size(A2, 1) A2 = [A2; zeros(ceil((size(AA, 1) - j) / j * size(A2, 1)), 3)]; end % Set constraint A2(1 + pos2:pos2 + length(it), 1) = ones(length(it), 1) .* pos; A2(1 + pos2:pos2 + length(it), 2) = it; A2(1 + pos2:pos2 + length(it), 3) = full(Q(it)); pos2 = pos2 + length(it); end end % Construct sparse constraint matrix reqmem = pos2; A2 = A2(1:pos2,:); A = sparse(A2(:,1), A2(:,2), A2(:,3), size(AA,1), B .^ 2); b = bb'; % Function that vectorizes a matrix function v = vec(M) v = M(:); % Function that matrixizes a vector function M = mat(C) r = round(sqrt(size(C, 1))); M = reshape(C, r, r);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
cca.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/cca.m
14,846
utf_8
935e971ffe825a64e0eb80c535d71ebb
function [Z, ccaEigen, ccaDetails] = cca(X, Y, EDGES, OPTS) % % Function [Z, CCAEIGEN, CCADETAILS] = CCA(X, Y, EDGES, OPTS) computes a low % dimensional embedding Z in R^d that maximally preserves angles among input % data X that lives in R^D, with the algorithm Conformal Component Analysis. % % The embedding Z is constrained to be Z = L*Y where Y is a partial basis that % spans the space of R^d. Such Y can be computed from graph Laplacian (such as % the outputs of Laplacian eigenmap and Locally Linear Embedding, ie, LLE). % The parameterization matrix L is found by this function as to maximally % prserve angles between edges coded in the sparse matrix EDGES. % % A basic usage of this function is given below: % % Inputs: % X: input data stored in matrix (D x N) where D is the dimensionality % % Y: partial basis stored in matrix (d x N) % % EDGES: a sparse matrix of (N x N). In each column i, the row indices j to % nonzero entrices define data points that are in the nearest neighbors of % data point i. % % OPTS: % OPTS.method: 'CCA' % % Outputs: % Z: low dimensional embedding (d X N) % CCAEIGN: eigenspectra of the matrix P = L'*L. If P is low-rank (say d' < d), % then Z can be cutoff at d' dimension as dimensionality reduced further. % % The CCA() function is fairly versatile. For more details, consult the file % README. % % by [email protected] Aug 18, 2006 % Feel free to use it for educational and research purpose. % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % sanity check if nargin ~= 4 error('Incorrect number of inputs supplied to cca().'); end N = size(X,2); if (N~=size(Y,2)) || (N ~= size(EDGES,1)) || (N~=size(EDGES,2)) disp('Unmatched matrix dimensions in cca().'); fprintf('# of data points: %d\n', N); fprintf('# of data points in Y: %d\n', size(Y,2)); fprintf('Size of the sparse matrix for edges: %d x %d\n', size(EDGES,1), size(EDGES,2)); error('All above 4 numbers should be the same.'); end % check necessary programs if exist('mexCCACollectData') ~= 3 error('Missing mexCCACollectData mex file on the path'); end if exist('csdp') ~= 2 error('You will need CSDP solver to run cca(). Please make sure csdp.m is in your path'); end % check options OPTS = check_opt(OPTS); D = size(X, 1); d = size(Y, 1); %disp('Step I. collect data needed for SDP formulation'); [tnn, vidx] = triangNN(EDGES, OPTS.CCA); [erow, ecol, evalue] = sparse_nn(tnn); irow = int32(erow); icol = int32(ecol); ividx = int32(vidx); ivalue = int32(evalue); [A,B, g] = mexCCACollectData(X,Y, irow, icol, int32(OPTS.relative), ivalue, ividx ); clear erow ecol irow icol tnn ividx ivalue evalue vidx; lst = find(g~=0); g = g(lst); B = B(:, lst); if OPTS.CCA == 1 BG = B*spdiags(1./sqrt(g),0, length(g),length(g)); Q = A - BG*BG'; BIAS = OPTS.regularizer*reshape(eye(d), d^2,1); else Q = A; BIAS = 2*sum(B,2)+OPTS.regularizer*reshape(eye(d), d^2,1); end [V, E] = eig(Q+eye(size(Q))); % adding an identity matrix to Q for numerical E = E-eye(size(Q)); % stability E(E<0) = 0; if ~isreal(diag(E)) warning('\tThe quadratic matrix is not positive definite..forced to be positive definite...\n'); E=real(E); V = real(V); S = sqrt(E)*V'; else S = sqrt(E)*V'; end % Formulate the SDP problem [AA, bb, cc] = formulateSDP(S, d, BIAS, (OPTS.CCA==1)); sizeSDP = d^2+1 + d + 2*(OPTS.CCA==1); csdppars.s = sizeSDP; csdpopts.printlevel = 0; % Solve it using CSDP [xx, yy, zz, info] = csdp(AA, bb, cc, csdppars,csdpopts); ccaDetails.sdpflag = info; % The negate of yy is our solution yy = -yy; idx = 0; P = zeros(d); for col=1:d for row = col:d idx=idx+1; P(row, col) = yy(idx); end end % Convert P to a positive definite matrix P = P + P' - diag(diag(P)); % Transform the original projection to the new projection [V, E] = eig(P); E(E < 0) = 0; L = diag(sqrt(diag(E))) * V'; newY = L * Y; % Eigenvalue of the new projection, doing PCA using covariance matrix [newV, newE] = eig(newY * newY'); newE = diag(newE); [dummy, idx] = sort(newE); newE = newE(idx(end:-1:1)); newY = newV' * newY; Z = newY(idx(end:-1:1),:); ccaEigen = newE; ccaDetails.cost = P(:)'*Q*P(:) - BIAS'*P(:) + sum(g(:))*(OPTS.MVU==1); if OPTS.CCA == 1 ccaDetails.c = spdiags(1./sqrt(g),0, length(g),length(g))*B'*P(:); else ccaDetails.c = []; end ccaDetails.P = P; ccaDetails.opts = OPTS; %%%%%%%%%%%%%%%%%%%% FOLLOWING IS SUPPORTING MATLAB FUNCTIONS function [A, b, c] = formulateSDP(S, D, bb, TRACE) [F0, FI, c] = localformulateSDP(S, D, bb, TRACE); [A, b, c] = sdpToSeDuMi(F0, FI, c); function [F0, FI, c] = localformulateSDP(S, D, b, TRACE) % formulate SDP problem % each FI that corresponds to the LMI for the quadratic cost function has % precisely 2*D^2 nonzero elements. But we need only D^2 storage for % indexing these elements since the FI are symmetric tempFidx = zeros(D^2, 3); dimF = (D^2+1) + D + 2*TRACE; idx= 0; tracearray = ones(TRACE,1); for col=1:D for row=col:D idx = idx+1; lindx1 = sub2ind([D D], row, col); lindx2 = sub2ind([D D], col, row); tempFidx(:,1) = [1:D^2]'; tempFidx(:,2) = D^2+1; if col==row tempFidx(:,3) = S(:, lindx1) ; FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row+D^2+1; ... % for P being p.s.d tracearray*(D^2+1+D+1); % for trace tracearray*(D^2+1+D+2); % for negate trace ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric row+D^2+1; ... % for P being p.s.d tracearray*(D^2+1+D+1); % for trace tracearray*(D^2+1+D+2); % for negate trace ],... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d tracearray*1; % for trace tracearray*(-1); % for negate trace ], dimF, dimF); else tempFidx(:,3) = S(:, lindx1) + S(:, lindx2); FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row+D^2+1; ... % for P being p.s.d col+D^2+1; ... % symmetric ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric col+D^2+1; ... % for P being p.s.d row+D^2+1; ... % being symmetric ],... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d 1; % symmetric ], dimF, dimF); end end end idx=idx+1; % for the F matrix corresponding to t FI{idx} = sparse(D^2+1, D^2+1, 1, dimF, dimF); % now for F0 if TRACE==1 F0 = sparse( [[1:D^2] dimF-1 dimF], [[1:D^2] dimF-1 dimF], [ones(1, D^2) -1 1], dimF, dimF); else F0 = sparse( [[1:D^2]], [[1:D^2]], [ones(1, D^2)], dimF, dimF); end % now for c b = reshape(-b, D, D); b = b*2 - diag(diag(b)); c = zeros(idx-1,1); kdx=0; %keyboard; for col=1:D for row=col:D kdx = kdx+1; c(kdx) = b(row, col); end end %keyboard; c = [c; 1]; % remember: we use only half of P return; function [A, b, c] = sdpToSeDuMi(F0, FI, cc) % convert the canonical SDP dual formulation: % (see Vandenberche and Boyd 1996, SIAM Review) % max -Tr(F0 Z) % s.t. Tr(Fi Z) = cci and Z is positive definite % % in which cc = (cc1, cc2, cc3,..) and FI = {F1, F2, F3,...} % % to SeDuMi format (formulated as vector decision variables ): % min c'x % s.t. Ax = b and x is positive definite (x is a vector, so SeDuMi % really means that vec2mat(x) is positive definite) % % by [email protected], June, 10, 2004 if nargin < 3 error('Cannot convert SDP formulation to SeDuMi formulation in sdpToSeDumi!'); end [m, n] = size(F0); if m ~= n error('F0 matrix must be squared matrix in sdpToSeDumi(F0, FI, b)'); end p = length(cc); if p ~= length(FI) error('FI matrix cellarray must have the same length as b in sdpToSeDumi(F0,FI,b)'); end % should check every element in the cell array FI...later.. % x = reshape(Z, n*n, 1); % optimization variables from matrix to vector % converting objective function of the canonical SDP c = reshape(F0', n*n,1); % converting equality constraints of the canonical SDP zz= 0; for idx=1:length(FI) zz= zz + nnz(FI{idx}); end A = spalloc( n*n, p, zz); for idx = 1:p temp = reshape(FI{idx}, n*n,1); lst = find(temp~=0); A(lst, idx) = temp(lst); end % The SeDuMi solver actually expects the transpose of A as in following % dual problem % max b'y % s.t. c - A'y is positive definite % Therefore, we transpose A % A = A'; % b doesn't need to be changed b = cc; return; % Check OPTS that is passed into function OPTS = check_opt(OPTS) if isfield(OPTS,'method') == 0 OPTS.method = 'cca'; disp('Options does''t have method field, so running CCA'); end if strncmpi(OPTS.method, 'MVU',3)==1 OPTS.CCA = 0; OPTS.MVU = 1; else OPTS.CCA = 1; OPTS.MVU = 0; end if isfield(OPTS, 'relative')==0 OPTS.relative = 0; end if OPTS.CCA==1 && OPTS.relative ==1 disp('Running CCA, so the .relative flag set to 0'); OPTS.relative = 0; end if isfield(OPTS, 'regularizer')==0 OPTS.regularizer = 0; end return function [tnn vidx]= triangNN(snn, TRI) % function [TNN VIDX]= triangNN(SNN) triangulates a sparse graph coded by spare matrix % SNN. TNN records the original edges in SNN as well as those that are % triangulated. Each edge is associated with a scaling factor that is specific % to a vertex. And VIDX records the id of the vertex. % % by [email protected] Aug. 15, 2006. N = size(snn,1); %fprintf('The graph has %d vertices\n', N); % figure out maximum degree a vertex has connectivs = sum(snn,1); maxDegree = max(connectivs); tnn = spalloc(N, N, round(maxDegree*N)); % prealloc estimated storage for speedup % triangulation for idx=1:N lst = find(snn(:, idx)>0); for jdx=1:length(lst) col = min (idx, lst(jdx)); row = max(idx, lst(jdx)); tnn(row, col) = tnn(row, col)+1; if TRI == 1 for kdx = jdx+1:length(lst) col = min(lst(jdx), lst(kdx)); row = max(lst(jdx), lst(kdx)); tnn(row, col) = tnn(row, col)+1; end end end end numVertexIdx = full(sum(tnn(:))); %fprintf('%d vertex entries are needed\n', numVertexIdx); rowIdx = zeros(numVertexIdx,1); colIdx = zeros(numVertexIdx,1); vidx = zeros(numVertexIdx,1); whichEdge = 0; for idx=1:N lst = find(snn(:, idx)>0); for jdx=1:length(lst) col = min(lst(jdx), idx); row = max(lst(jdx), idx); whichEdge = whichEdge+1; rowIdx(whichEdge) = row; colIdx(whichEdge) = col; vidx(whichEdge) = idx; if TRI==1 for kdx = jdx+1:length(lst) col = min(lst(jdx), lst(kdx)); row = max(lst(jdx), lst(kdx)); whichEdge = whichEdge+1; rowIdx(whichEdge) = row; colIdx(whichEdge) = col; vidx(whichEdge) = idx; end end end end linearIdx = sub2ind([N N],rowIdx, colIdx); [sa, sIdx] = sort(linearIdx); vidx = vidx(sIdx); return % turn sparse graph snn into row and col indices function [edgesrow, edgescol, value] = sparse_nn(snn) N = size(snn,1); edgescol = zeros(N+1,1); nnzer = nnz(snn); edgesrow = zeros(nnzer,1); value = zeros(nnzer,1); edgescol(1) = 0; for jdx=1:N lst = find(snn(:, jdx)>0); %lst = lst(find(lst>jdx)); edgescol(jdx+1) = edgescol(jdx)+length(lst); edgesrow(edgescol(jdx)+1:edgescol(jdx+1)) = lst-1; value(edgescol(jdx)+1:edgescol(jdx+1)) = snn(lst, jdx); end return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
x2p.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/x2p.m
3,597
utf_8
4a102e94922f4af38e36c374dccbc5a2
function [P, beta] = x2p(X, u, tol) %X2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = x2p(xx, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(X, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Compute pairwise distances % disp('Computing pairwise distances...'); D = squareform(pdist(X, 'euclidean') .^ 2); % Run over all datapoints % disp('Computing P-values...'); for i=1:n % if ~rem(i, 500) % disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); % end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision Di = D(i, [1:i-1 i+1:end]); [H, thisP] = Hbeta(Di, beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(Di, beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end % disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); % disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); % disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; P = P / sumP; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
sammon.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/sammon.m
7,108
utf_8
8a1fccbea9525bbebae4039127005ea6
function [y, E] = sammon(x, n, opts) %SAMMON Performs Sammon's MDS mapping on dataset X % % Y = SAMMON(X) applies Sammon's nonlinear mapping procedure on % multivariate data X, where each row represents a pattern and each column % represents a feature. On completion, Y contains the corresponding % co-ordinates of each point on the map. By default, a two-dimensional % map is created. Note if X contains any duplicated rows, SAMMON will % fail (ungracefully). % % [Y,E] = SAMMON(X) also returns the value of the cost function in E (i.e. % the stress of the mapping). % % An N-dimensional output map is generated by Y = SAMMON(X,N) . % % A set of optimisation options can also be specified using a third % argument, Y = SAMMON(X,N,OPTS) , where OPTS is a structure with fields: % % MaxIter - maximum number of iterations % TolFun - relative tolerance on objective function % MaxHalves - maximum number of step halvings % Input - {'raw','distance'} if set to 'distance', X is % interpreted as a matrix of pairwise distances. % Display - {'off', 'on', 'iter'} % Initialisation - {'pca', 'random'} % % The default options structure can be retrieved by calling SAMMON with % no parameters. % % References : % % [1] Sammon, John W. Jr., "A Nonlinear Mapping for Data Structure % Analysis", IEEE Transactions on Computers, vol. C-18, no. 5, % pp 401-409, May 1969. % % See also : SAMMON_TEST % % File : sammon.m % % Date : Monday 12th November 2007. % % Author : Gavin C. Cawley and Nicola L. C. Talbot % % Description : Simple vectorised MATLAB implementation of Sammon's non-linear % mapping algorithm [1]. % % References : [1] Sammon, John W. Jr., "A Nonlinear Mapping for Data % Structure Analysis", IEEE Transactions on Computers, % vol. C-18, no. 5, pp 401-409, May 1969. % % History : 10/08/2004 - v1.00 % 11/08/2004 - v1.10 Hessian made positive semidefinite % 13/08/2004 - v1.11 minor optimisation % 12/11/2007 - v1.20 initialisation using the first n principal % components. % % Thanks : Dr Nick Hamilton ([email protected]) for supplying the % code for implementing initialisation using the first n % principal components (introduced in v1.20). % % To do : The current version does not take advantage of the symmetry % of the distance matrix in order to allow for easy % vectorisation. This may not be a good choice for very large % datasets, so perhaps one day I'll get around to doing a MEX % version using the BLAS library etc. for very large datasets. % % Copyright : (c) Dr Gavin C. Cawley, November 2007. % % 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 % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % use the default options structure if nargin < 3 opts.Display = 'iter'; opts.Input = 'raw'; opts.MaxHalves = 20; opts.MaxIter = 500; opts.TolFun = 1e-9; opts.Initialisation = 'random'; end % the user has requested the default options structure if nargin == 0 y = opts; return; end % Create a two-dimensional map unless dimension is specified if nargin < 2 n = 2; end % Set level of verbosity if strcmp(opts.Display, 'iter') display = 2; elseif strcmp(opts.Display, 'on') display = 1; else display = 0; end % Create distance matrix unless given by parameters if strcmp(opts.Input, 'distance') D = x; else D = euclid(x, x); end % Remaining initialisation N = size(x, 1); scale = 0.5 / sum(D(:)); D = D + eye(N); Dinv = 1 ./ D; if strcmp(opts.Initialisation, 'pca') [UU,DD] = svd(x); y = UU(:,1:n)*DD(1:n,1:n); else y = randn(N, n); end one = ones(N,n); d = euclid(y,y) + eye(N); dinv = 1./d; delta = D - d; E = sum(sum((delta.^2).*Dinv)); % Get on with it for i=1:opts.MaxIter % Compute gradient, Hessian and search direction (note it is actually % 1/4 of the gradient and Hessian, but the step size is just the ratio % of the gradient and the diagonal of the Hessian so it doesn't % matter). delta = dinv - Dinv; deltaone = delta * one; g = delta * y - y .* deltaone; dinv3 = dinv .^ 3; y2 = y .^ 2; H = dinv3 * y2 - deltaone - 2 * y .* (dinv3 * y) + y2 .* (dinv3 * one); s = -g(:) ./ abs(H(:)); y_old = y; % Use step-halving procedure to ensure progress is made for j=1:opts.MaxHalves y(:) = y_old(:) + s; d = euclid(y, y) + eye(N); dinv = 1 ./ d; delta = D - d; E_new = sum(sum((delta .^ 2) .* Dinv)); if E_new < E break; else s = 0.5*s; end end % Bomb out if too many halving steps are required if j == opts.MaxHalves warning('MaxHalves exceeded. Sammon mapping may not converge...'); end % Evaluate termination criterion if abs((E - E_new) / E) < opts.TolFun if display fprintf(1, 'Optimisation terminated - TolFun exceeded.\n'); end break; end % Report progress E = E_new; if display > 1 fprintf(1, 'epoch = %d : E = %12.10f\n', i, E * scale); end end % Fiddle stress to match the original Sammon paper E = E * scale; end function d = euclid(x, y) d = sqrt(sum(x.^2,2)*ones(1,size(y,1))+ones(size(x,1),1)*sum(y.^2,2)'-2*(x*y')); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
sdecca2.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/sdecca2.m
7,185
utf_8
e53979561adda6a23883da0e72af5bf6
function [P, newY, L, newV, idx]= sdecca2(Y, snn, regularizer, relative) % doing semidefinitve embedding/MVU with output being parameterized by graph % laplacian's eigenfunctions.. % % the algorithm is same as conformal component analysis except that the scaling % factor there is set as 1 % % % function [P, newY, Y] = CDR2(X, Y, NEIGHBORS) implements the % CONFORMAL DIMENSIONALITY REDUCTION of data X. It finds a linear map % of Y -> L*Y such that X and L*Y is related by a conformal mapping. % % No tehtat The algorithm use the formulation of only distances. % % Input: % Y: matrix of d'xN, with each column is a point in R^d' % NEIGHBORS: matrix of KxN, each column is a list of indices (between 1 % and N) to the nearest-neighbor of the corresponding column in X % Output: % P: square of the linear map L, i.e., P = L'*L % newY: transformed data points, i.e., newY = L*Y; % Y: the linear map L itself, i.e., L = L % % The algorithm finds L by solving a semidefinite programming problem. It % calls csdp() SDP solver by default and assumes that it is on the path. % % written by [email protected] % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology % Collect the data [erow, ecol, edist] = sparse_nn(snn); irow = int32(erow); icol = int32(ecol); [A, B, g] = mexCCACollectData2(Y, irow, icol, edist, int32(relative)); BG = 2 * sum(B, 2); Q = A ; [V, E] = eig(Q + eye(size(Q))); E = E - eye(size(Q)); E(E < 0) = 0; if ~isreal(diag(E)) E = real(E); V = real(V); S = sqrt(E) * V'; else S = sqrt(E) * V'; end % Put the regularizer in there BG = BG + regularizer * reshape(eye(size(Y, 1)), size(Y, 1) ^ 2, 1); % Formulate the SDP problem [AA, bb, cc] = formulateSDP(S, size(Y, 1), BG); sizeSDP = size(Y, 1) ^ 2 + 1 + size(Y, 1); pars.s = sizeSDP; opts.printlevel = 1; % Solve it using CSDP [xx, yy] = csdp(AA, bb, cc, pars, opts); % The negate of yy is our solution yy = -yy; idx = 0; P = zeros(size(Y, 1)); for col=1:size(Y, 1) for row = col:size(Y, 1) idx = idx + 1; P(row, col) = yy(idx); end end % Convert P to a positive definite matrix P = P + P' - diag(diag(P)); % Transform the original projection to the new projection [V, E] = eig(P); E(E < 0) = 0; L = diag(sqrt(diag(E))) * V'; newY = L * Y; % multiply with Laplacian % Eigendecomposition of the new projection: doing PCA because the % dimensionality of newY or Y is definitely less than the number of % points [newV, newE] = eig(newY * newY'); newE = diag(newE); [dummy, idx] = sort(newE); newY = newV' * newY; newY = newY(idx(end:-1:1),:); return % Function that formulates the SDP problem function [A, b, c]=formulateSDP(S, D, bb) [F0, FI, c] = localformulateSDP(S, D, bb); [A, b, c] = sdpToSeDuMi(F0, FI, c); return % Function that formulates the SDP problem function [F0, FI, c] = localformulateSDP(S, D, b) % Each FI that corresponds to the LMI for the quadratic cost function has % precisely 2 * D^2 nonzero elements. But we need only D^2 storage for tempFidx = zeros(D ^ 2, 3); dimF = (D ^ 2 + 1) + D; idx = 0; for col=1:D for row=col:D idx = idx + 1; lindx1 = sub2ind([D D], row, col); lindx2 = sub2ind([D D], col, row); tempFidx(:,1) = [1:D ^ 2]'; tempFidx(:,2) = D ^ 2 + 1; if col == row tempFidx(:,3) = S(:,lindx1) ; FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row + D^2 + 1 ... % for P being p.s.d ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric row + D^2 + 1; ... % for P being p.s.d ],... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d ], dimF, dimF); else tempFidx(:,3) = S(:, lindx1) + S(:,lindx2); FI{idx} = sparse([tempFidx(:,1); ... % for cost function tempFidx(:,2); ... % symmetric row + D^2 + 1; ... % for P being p.s.d col + D^2 + 1; ... % symmetric ], ... [tempFidx(:,2); ... % for cost function tempFidx(:,1); ... % symmetric col + D^2 + 1; ... % for P being p.s.d row + D^2 + 1; ... % being symmetric ], ... [tempFidx(:,3); ... % for cost function tempFidx(:,3); ... % symmetric 1; % for P being p.s.d 1; % symmetric ], dimF, dimF); end end end idx = idx + 1; % For the F matrix corresponding to t FI{idx} = sparse(D^2 + 1, D^2 + 1, 1, dimF, dimF); % Now for F0 F0 = sparse(1:D^2, 1:D^2, ones(1, D^2), dimF, dimF); % Now for c b = reshape(-b, D, D); b = b * 2 - diag(diag(b)); c = zeros(idx - 1,1); kdx = 0; for col=1:D for row=col:D kdx = kdx + 1; c(kdx) = b(row, col); end end c = [c; 1]; return % Function that convertsthe canonical SDP dual formulation to SeDuMi format function [A, b, c] = sdpToSeDuMi(F0, FI, cc) % Check inputs if nargin < 3 error('Cannot convert SDP formulation to SeDuMi formulation.'); end [m, n] = size(F0); if m ~= n error('F0 matrix must be squared matrix.'); end p = length(cc); if p ~= length(FI) error('FI matrix cellarray must have the same length as b.'); end % Converting objective function of the canonical SDP c = reshape(F0', n * n, 1); % Converting equality constraints of the canonical SDP zz = 0; for idx=1:length(FI) zz= zz + nnz(FI{idx}); end A = spalloc(n * n, p, zz); for idx=1:p temp = reshape(FI{idx}, n * n, 1); lst = find(temp ~= 0); A(lst, idx) = temp(lst); end % We do not need to convert b b = cc; return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
sparse_nn.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/sparse_nn.m
972
utf_8
df5da172f954ec2f53125a04787cf2d3
%SPARSE_NN % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology function [edgesrow, edgescol,edgesdist] = sparse_nn(snn) % turn into sparse nearest neighbor graph snn into edgesrow and edgescol index N = size(snn,1); edgescol = zeros(N+1,1); nnzer = nnz(snn); edgesrow = zeros(nnzer,1); edgesdist = zeros(nnzer,1); edgescol(1) = 0; for jdx=1:N lst = find(snn(:, jdx)>0); %lst = lst(find(lst>jdx)); edgescol(jdx+1) = edgescol(jdx)+length(lst); edgesrow(edgescol(jdx)+1:edgescol(jdx+1)) = lst-1; edgesdist(edgescol(jdx)+1:edgescol(jdx+1))=snn(lst,jdx); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
jdqz.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/techniques/jdqz.m
78,986
utf_8
be67a038982588a6ac9cbc2d36f009e8
function varargout=jdqz(varargin) %JDQZ computes a partial generalized Schur decomposition (or QZ % decomposition) of a pair of square matrices or operators. % % LAMBDA=JDQZ(A,B) and JDQZ(A,B) return K eigenvalues of the matrix pair % (A,B), where K=min(5,N) and N=size(A,1) if K has not been specified. % % [X,JORDAN]=JDQZ(A,B) returns the eigenvectors X and the Jordan % structure JORDAN: A*X=B*X*JORDAN. The diagonal of JORDAN contains the % eigenvalues: LAMBDA=DIAG(JORDAN). JORDAN is an K by K matrix with the % eigenvalues on the diagonal and zero or one on the first upper diagonal % elements. The other entries are zero. % % [X,JORDAN,HISTORY]=JDQZ(A,B) returns also the convergence history. % % [X,JORDAN,Q,Z,S,T,HISTORY]=JDQZ(A,B) % If between four and seven output arguments are required, then Q and Z % are N by K orthonormal, S and T are K by K upper triangular such that % they form a partial generalized Schur decomposition: A*Q=Z*S and % B*Q=Z*T. Then LAMBDA=DIAG(S)./DIAG(T) and X=Q*Y with Y the eigenvectors % of the pair (S,T): S*Y=T*Y*JORDAN (see also OPTIONS.Schur). % % JDQZ(A,B) % JDQZ('Afun','Bfun') % The first input argument is either a square matrix (which can be full % or sparse, symmetric or nonsymmetric, real or complex), or a string % containing the name of an M-file which applies a linear operator to the % columns of a given matrix. In the latter case, the M-file, say Afun.m, % must return the dimension N of the problem with N = Afun([],'dimension'). % For example, JDQZ('fft',...) is much faster than JDQZ(F,...), where F is % the explicit FFT matrix. % If another input argument is a square N by N matrix or the name of an % M-file, then B is this argument (regardless whether A is an M-file or a % matrix). If B has not been specified, then B is assumed to be the % identity unless A is an M-file with two output vectors of dimension N % with [AV,BV]=Afun(V), or with AV=Afun(V,'A') and BV=Afun(V,'B'). % % The remaining input arguments are optional and can be given in % practically any order: % % [X,JORDAN,Q,Z,S,T,HISTORY] = JDQZ(A,B,K,SIGMA,OPTIONS) % [X,JORDAN,Q,Z,S,T,HISTORY] = JDQZ('Afun','Bfun',K,SIGMA,OPTIONS) % % where % % K an integer, the number of desired eigenvalues. % SIGMA a scalar shift or a two letter string. % OPTIONS a structure containing additional parameters. % % If K is not specified, then K = MIN(N,5) eigenvalues are computed. % % If SIGMA is not specified, then the Kth eigenvalues largest in % magnitude are computed. If SIGMA is a real or complex scalar, then the % Kth eigenvalues nearest SIGMA are computed. If SIGMA is column vector % of size (L,1), then the Jth eigenvalue nearest to SIGMA(MIN(J,L)) % is computed for J=1:K. SIGMA is the "target" for the desired eigenvalues. % If SIGMA is one of the following strings, then it specifies the desired % eigenvalues. % % SIGMA Specified eigenvalues % % 'LM' Largest Magnitude % 'SM' Smallest Magnitude (same as SIGMA = 0) % 'LR' Largest Real part % 'SR' Smallest Real part % 'BE' Both Ends. Computes K/2 eigenvalues % from each end of the spectrum (one more % from the high end if K is odd.) % % If 'TestSpace' is 'Harmonic' (see OPTIONS), then SIGMA = 0 is the % default, otherwise SIGMA = 'LM' is the default. % % % The OPTIONS structure specifies certain parameters in the algorithm. % % Field name Parameter Default % % OPTIONS.Tol Convergence tolerance: 1e-8 % norm(r) <= Tol/SQRT(K) % OPTIONS.jmin Minimum dimension search subspace V K+5 % OPTIONS.jmax Maximum dimension search subspace V jmin+5 % OPTIONS.MaxIt Maximum number of iterations. 100 % OPTIONS.v0 Starting space ones+0.1*rand % OPTIONS.Schur Gives schur decomposition 'no' % If 'yes', then X and JORDAN are % not computed and [Q,Z,S,T,HISTORY] % is the list of output arguments. % OPTIONS.TestSpace Defines the test subspace W 'Harmonic' % 'Standard': W=sigma*A*V+B*V % 'Harmonic': W=A*V-sigma*B*V % 'SearchSpace': W=V % W=V is justified if B is positive % definite. % OPTIONS.Disp Shows size of intermediate residuals 'no' % and the convergence history % OPTIONS.NSigma Take as target for the second and 'no' % following eigenvalues, the best % approximate eigenvalues from the % test subspace. % OPTIONS.Pairs Search for conjugated eigenpairs 'no' % OPTIONS.LSolver Linear solver 'GMRES' % OPTIONS.LS_Tol Residual reduction linear solver 1,0.7,0.7^2,.. % OPTIONS.LS_MaxIt Maximum number it. linear solver 5 % OPTIONS.LS_ell ell for BiCGstab(ell) 4 % OPTIONS.Precond Preconditioner (see below) identity. % OPTIONS.Type_Precond Way of using preconditioner 'left' % % For instance % % options=struct('Tol',1.0e-8,'LSolver','BiCGstab','LS_ell',4,'Precond',M); % % changes the convergence tolerance to 1.0e-8, takes BiCGstab as linear % solver, and takes M as preconditioner (for ways of defining M, see below). % % % PRECONDITIONING. The action M-inverse of the preconditioner M (an % approximation of A-lamda*B) on an N-vector V can be defined in the % OPTIONS % % OPTIONS.Precond % OPTIONS.L_Precond same as OPTIONS.Precond % OPTIONS.U_Precond % OPTIONS.P_Precond % % If no preconditioner has been specified (or is []), then M\V=V (M is % the identity). % If Precond is an N by N matrix, say, K, then % M\V = K\V. % If Precond is an N by 2*N matrix, say, K, then % M\V = U\L\V, where K=[L,U], and L and U are N by N matrices. % If Precond is a string, say, 'Mi', then % if Mi(V,'L') and Mi(V,'U') return N-vectors % M\V = Mi(Mi(V,'L'),'U') % otherwise % M\V = Mi(V) or M\V=Mi(V,'preconditioner'). % Note that Precond and A can be the same string. % If L_Precond and U_Precond are strings, say, 'Li' and 'Ui', % respectively, then % M\V=Ui(Li(V)). % If (P_precond,) L_Precond, and U_precond are N by N matrices, say, % (P,) L, and U, respectively, then % M\V=U\L\(P*V) (P*M=L*U) % % OPTIONS.Type_Precond % The preconditioner can be used as explicit left preconditioner % ('left', default), as explicit right preconditioner ('right') or % implicitly ('impl'). % % % JDQZ without input arguments returns the options and its defaults. % % Gerard Sleijpen. % Copyright (c) 2002 % % % This file is part of the Matlab Toolbox for Dimensionality Reduction. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, Delft University of Technology global Qschur Zschur Sschur Tschur ... Operator_MVs Precond_Solves ... MinvZ QastMinvZ if nargin==0 possibilities, return, end %%% Read/set parameters [n,nselect,Sigma,kappa,SCHUR,... jmin,jmax,tol0,maxit,V,AV,BV,TS,DISP,PAIRS,JDV0,FIX_tol,track,NSIGMA,... lsolver,LSpar] = ReadOptions(varargin{1:nargin}); Qschur = zeros(n,0); Zschur=zeros(n,0);; MinvZ = zeros(n,0); QastMinvZ=zeros(0,0); Sschur = []; Tschur=[]; history = []; %%% Return if eigenvalueproblem is trivial if n<2 if n==1, Qschur=1; Zschur=1; [Sschur,Tschur]=MV(1); end if nargout == 0, Lambda=Sschur/Tschur, else [varargout{1:nargout}]=output(history,SCHUR,1,Sschur/Tschur); end, return, end %---------- SET PARAMETERS & STRINGS FOR OUTPUT ------------------------- if TS==0, testspace='sigma(1)''*Av+sigma(2)''*Bv'; elseif TS==1, testspace='sigma(2)*Av-sigma(1)*Bv'; elseif TS==2, testspace='v'; elseif TS==3, testspace='Bv'; elseif TS==4, testspace='Av'; end String=['\r#it=%i #MV=%3i, dim(V)=%2i, |r_%2i|=%6.1e ']; %------------------- JDQZ ----------------------------------------------- % fprintf('Scaling with kappa=%6.4g.',kappa) k=0; nt=0; j=size(V,2); nSigma=size(Sigma,1); it=0; extra=0; Zero=[]; target=[]; tol=tol0/sqrt(nselect); INITIATE=1; JDV=0; rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; time=clock; if TS ~=2 while (k<nselect & it<maxit) %%% Initialize target, test space and interaction matrices if INITIATE, % set new target nt=min(nt+1,nSigma); sigma = Sigma(nt,:); nlit=0; lit=0; if j<2 [V,AV,BV]=Arnoldi(V,AV,BV,sigma,jmin,nselect,tol); rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; target=[]; j=min(jmin,n-k); end if DETECTED & NSIGMA [Ur,Ul,St,Tt] = SortQZ(WAV,WBV,sigma,kappa); y=Ur(:,1); q=V*y; Av=AV*y; Bv=BV*y; [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); sigma=ScaleEig(theta); USE_OLD=NSIGMA; rKNOWN=1; lit=10; end NEWSHIFT= 1; if DETECTED & TS<2, NEWSHIFT= ~min(target==sigma); end target=sigma; ttarget=sigma; if ischar(ttarget), ttrack=0; else, ttrack=track; end if NEWSHIFT v=V; Av=AV; Bv=BV; W=eval(testspace); %%% V=RepGS(Qschur,V); [AV,BV]=MV(V); %%% more stability?? %%% W=RepGS(Zschur,eval(testspace)); %%% dangerous if sigma~lambda if USE_OLD, W(:,1)=V(:,1); end, W=RepGS(Zschur,W); WAV=W'*AV; WBV=W'*BV; end INITIATE=0; DETECTED=0; JDV=0; end % if INITIATE %%% Solve the preconditioned correction equation if rKNOWN, if JDV, z=W; q=V; extra=extra+1; if DISP, fprintf(' %2i-d proj.\n',k+j-1), end end if FIX_tol*nr>1 & ~ischar(target), theta=target; else, FIX_tol=0; end t=SolvePCE(theta,q,z,r,lsolver,LSpar,lit); nlit=nlit+1; lit=lit+1; it=it+1; EXPAND=1; rKNOWN=0; JDV=0; end % if rKNOWN %%% Expand the subspaces and the interaction matrices if EXPAND [v,zeta]=RepGS([Qschur,V],t); V=[V,v]; [Av,Bv]=MV(v); AV=[AV,Av]; BV=[BV,Bv]; w=eval(testspace); w=RepGS([Zschur,W],w); WAV=[WAV,W'*Av;w'*AV]; WBV=[WBV,W'*Bv;w'*BV]; W=[W,w]; j=j+1; EXPAND=0; %%% Check for stagnation if abs(zeta(size(zeta,1),1))/norm(zeta)<0.06, JDV=JDV0; end end % if EXPAND %%% Solve projected eigenproblem if USE_OLD [Ur,Ul,St,Tt]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin,y); else [Ur,Ul,St,Tt]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin); end %%% Compute approximate eigenpair and residual y=Ur(:,1); q=V*y; Av=AV*y; Bv=BV*y; [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); %%%=== an alternative, but less stable way of computing z ===== % beta=Tt(1,1); alpha=St(1,1); theta=[alpha,beta]; % r=RepGS(Zschur,beta*Av-alpha*Bv,0); nr=norm(r); z=W*Ul(:,1); rKNOWN=1; if nr<ttrack, ttarget=ScaleEig(theta); end if DISP, %%% display history fprintf(String,it,Operator_MVs,j,nlit,nr), end history=[history;nr,it,Operator_MVs]; %%% save history %%% check convergence if (nr<tol) %%% EXPAND Schur form Qschur=[Qschur,q]; Zschur=[Zschur,z]; Sschur=[[Sschur;zeros(1,k)],Zschur'*Av]; Tschur=[[Tschur;zeros(1,k)],Zschur'*Bv]; Zero=[Zero,0]; k=k+1; if ischar(target), Target(k,:)=[nt,0,0]; else, Target(k,:)=[0,target]; end if DISP, ShowEig(theta,target,k); end if (k>=nselect), break; end; %%% Expand preconditioned Schur matrix MinvZ=M\Zschur UpdateMinvZ; J=[2:j]; j=j-1; Ur=Ur(:,J); Ul=Ul(:,J); V=V*Ur; AV=AV*Ur; BV=BV*Ur; W=W*Ul; WAV=St(J,J); WBV=Tt(J,J); rKNOWN=0; DETECTED=1; USE_OLD=0; %%% check for conjugate pair if PAIRS & (abs(imag(theta(1)/theta(2)))>tol) t=ImagVector(q); % t=conj(q); t=t-q*(q'*t); if norm(t)>tol, t=RepGS([Qschur,V],t,0); if norm(t)>200*tol target=ScaleEig(conj(theta)); EXPAND=1; DETECTED=0; if DISP, fprintf('--- Checking for conjugate pair ---\n'), end end end end INITIATE = ( j==0 & DETECTED); elseif DETECTED %%% To detect whether another eigenpair is accurate enough INITIATE=1; end % if (nr<tol) %%% restart if dim(V)> jmax if j==jmax j=jmin; J=[1:j]; Ur=Ur(:,J); Ul=Ul(:,J); V=V*Ur; AV=AV*Ur; BV=BV*Ur; W=W*Ul; WAV=St(J,J); WBV=Tt(J,J); end % if j==jmax end % while k end % if TS~=2 if TS==2 Q0=Qschur; ZastQ=[]; % WAV=V'*AV; WBV=V'*BV; while (k<nselect & it<maxit) %%% Initialize target, test space and interaction matrices if INITIATE & ( nSigma>k | NSIGMA), % set new target nt=min(nt+1,nSigma); sigma = Sigma(nt,:); nlit=0; lit=0; if j<2 [V,AV,BV]=Arnoldi(V,AV,BV,sigma,jmin,nselect,tol); rKNOWN=0; EXPAND=0; USE_OLD=0; DETECTED=0; target=[]; j=min(jmin,n-k);; end if DETECTED & NSIGMA [Ur,Ul,St,Tt]=SortQZ(WAV,WBV,sigma,kappa,1); q=RepGS(Zschur,V*Ur(:,1)); [Av,Bv]=MV(q); [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); sigma=ScaleEig(theta); USE_OLD=NSIGMA; rKNOWN=1; lit=10; end target=sigma; ttarget=sigma; if ischar(ttarget), ttrack=0; else, ttrack=track; end if ~DETECTED %%% additional stabilisation. May not be needed %%% V=RepGS(Zschur,V); [AV,BV]=MV(V); %%% end add. stab. WAV=V'*AV; WBV=V'*BV; end DETECTED=0; INITIATE=0; JDV=0; end % if INITIATE %%% Solve the preconditioned correction equation if rKNOWN, if JDV, z=V; q=V; extra=extra+1; if DISP, fprintf(' %2i-d proj.\n',k+j-1), end end if FIX_tol*nr>1 & ~ischar(target), theta=target; else, FIX_tol=0; end t=SolvePCE(theta,q,z,r,lsolver,LSpar,lit); nlit=nlit+1; lit=lit+1; it=it+1; EXPAND=1; rKNOWN=0; JDV=0; end % if rKNOWN %%% expand the subspaces and the interaction matrices if EXPAND [v,zeta]=RepGS([Zschur,V],t); [Av,Bv]=MV(v); WAV=[WAV,V'*Av;v'*AV,v'*Av]; WBV=[WBV,V'*Bv;v'*BV,v'*Bv]; V=[V,v]; AV=[AV,Av]; BV=[BV,Bv]; j=j+1; EXPAND=0; %%% Check for stagnation if abs(zeta(size(zeta,1),1))/norm(zeta)<0.06, JDV=JDV0; end end % if EXPAND %%% compute approximate eigenpair if USE_OLD [Ur,Ul]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin,Ur(:,1)); else [Ur,Ul]=SortQZ(WAV,WBV,ttarget,kappa,(j>=jmax)*jmin); end %%% Compute approximate eigenpair and residual q=V*Ur(:,1); Av=AV*Ur(:,1); Bv=BV*Ur(:,1); [r,z,nr,theta]=Comp_rz(RepGS(Zschur,[Av,Bv],0),kappa); rKNOWN=1; if nr<ttrack, ttarget=ScaleEig(theta); end if DISP, %%% display history fprintf(String,it,Operator_MVs, j,nlit,nr), end history=[history;nr,it,Operator_MVs]; %%% save history %%% check convergence if (nr<tol) %%% expand Schur form [q,a]=RepGS(Q0,q); a1=a(k+1,1); a=a(1:k,1); %%% ZastQ=Z'*Q0 Q0=[Q0,q]; %%% the final Qschur ZastQ=[ZastQ,Zschur'*q;z'*Q0]; Zschur=[Zschur,z]; Qschur=[Qschur,z]; Sschur=[[Sschur;Zero],a1\(Zschur'*Av-[Sschur*a;0])]; Tschur=[[Tschur;Zero],a1\(Zschur'*Bv-[Tschur*a;0])]; Zero=[Zero,0]; k=k+1; if ischar(target), Target(k,:)=[nt,0,0]; else, Target(k,:)=[0,target]; end if DISP, ShowEig(theta,target,k); end if (k>=nselect), break; end; UpdateMinvZ; J=[2:j]; j=j-1; rKNOWN=0; DETECTED=1; Ul=Ul(:,J); V=V*Ul; AV=AV*Ul; BV=BV*Ul; WAV=Ul'*WAV*Ul; WBV=Ul'*WBV*Ul; Ul=eye(j); Ur=Ul; %%% check for conjugate pair if PAIRS & (abs(imag(theta(2)/theta(1)))>tol) t=ImagVector(q); if norm(t)>tol, %%% t perp Zschur, t in span(Q0,imag(q)) t=t-Q0*(ZastQ\(Zschur'*t)); if norm(t)>100*tol target=ScaleEig(conj(theta)); EXPAND=1; DETECTED=0; USE_OLD=0; if DISP, fprintf('--- Checking for conjugate pair ---\n'), end end end end INITIATE = ( j==0 & DETECTED); elseif DETECTED %%% To detect whether another eigenpair is accurate enough INITIATE=1; end % if (nr<tol) %%% restart if dim(V)> jmax if j==jmax j=jmin; J=[1:j]; Ur=Ur(:,J); V=V*Ur; AV=AV*Ur; BV=BV*Ur; WAV=Ur'*WAV*Ur; WBV=Ur'*WBV*Ur; Ur=eye(j); end % if jmax end % while k Qschur=Q0; end time_needed=etime(clock,time); if JDV0 & extra>0 & DISP fprintf('\n\n# j-dim. proj.: %2i\n\n',extra) end I=CheckSortSchur(Sigma,kappa); Target(1:length(I),:)=Target(I,:); XKNOWN=0; if nargout == 0 if ~DISP eigenvalues=diag(Sschur)./diag(Tschur) % Result(eigenvalues) return, end else Jordan=[]; X=zeros(n,0); if SCHUR ~= 1 if k>0 [Z,D,Jor]=FindJordan(Sschur,Tschur,SCHUR); DT=abs(diag(D)); DS=abs(diag(Jor)); JT=find(DT<=tol & DS>tol); JS=find(DS<=tol & DT<=tol); msg=''; DT=~isempty(JT); DS=~isempty(JS); if DT msg1='The eigenvalues'; msg2=sprintf(', %i',JT); msg=[msg1,msg2,' are numerically ''Inf''']; end, if DS msg1='The pencil is numerically degenerated in the directions'; msg2=sprintf(', %i',JS); if DT, msg=[msg,sprintf('\n\n')]; end, msg=[msg,msg1,msg2,'.']; end, if (DT | DS), warndlg(msg,'Unreliable directions'), end Jordan=Jor/D; X=Qschur*Z; XKNOWN=1; end end [varargout{1:nargout}]=output(history,SCHUR,X,Jordan); end %-------------- display results ----------------------------------------- if DISP & size(history,1)>0 rs=history(:,1); mrs=max(rs); if mrs>0, rs=rs+0.1*eps*mrs; subplot(2,1,1); t=history(:,2); plot(t,log10(rs),'*-',t,log10(tol)+0*t,':') legend('log_{10} || r_{#it} ||_2') String=sprintf('The test subspace is computed as %s.',testspace); title(String) subplot(2,1,2); t=history(:,3); plot(t,log10(rs),'-*',t,log10(tol)+0*t,':') legend('log_{10} || r_{#MV} ||_2') String=sprintf('JDQZ with jmin=%g, jmax=%g, residual tolerance %g.',... jmin,jmax,tol); title(String) String=sprintf('Correction equation solved with %s.',lsolver); xlabel(String), date=fix(clock); String=sprintf('%2i-%2i-%2i, %2i:%2i:%2i',date(3:-1:1),date(4:6)); ax=axis; text(0.2*ax(1)+0.8*ax(2),1.2*ax(3)-0.2*ax(4),String) drawnow end Result(Sigma,Target,diag(Sschur),diag(Tschur),tol) end %------------------------ TEST ACCURACY --------------------------------- if k>nselect & DISP fprintf('\n%i additional eigenpairs have been detected.\n',k-nselect) end if k<nselect & DISP fprintf('\nFailed to detect %i eigenpairs.\n',nselect-k) end if (k>0) & DISP Str='time_needed'; texttest(Str,eval(Str)) fprintf('\n%39s: %9i','Number of Operator actions',Operator_MVs) if Precond_Solves fprintf('\n%39s: %9i','Number of preconditioner solves',Precond_Solves) end if 1 if SCHUR ~= 1 & XKNOWN % Str='norm(Sschur*Z-Tschur*Z*Jordan)'; texttest(Str,eval(Str),tol0) ok=1; eval('[AX,BX]=MV(X);','ok=0;') if ~ok, for j=1:size(X,2), [AX(:,j),BX(:,j)]=MV(X(:,j)); end, end Str='norm(AX*D-BX*Jor)'; texttest(Str,eval(Str),tol0) end ok=1; eval('[AQ,BQ]=MV(Qschur);','ok=0;') if ~ok, for j=1:size(Qschur,2), [AQ(:,j),BQ(:,j)]=MV(Qschur(:,j)); end, end if kappa == 1 Str='norm(AQ-Zschur*Sschur)'; texttest(Str,eval(Str),tol0) else Str='norm(AQ-Zschur*Sschur)/kappa'; texttest(Str,eval(Str),tol0) end Str='norm(BQ-Zschur*Tschur)'; texttest(Str,eval(Str),tol0) I=eye(k); Str='norm(Qschur''*Qschur-I)'; texttest(Str,eval(Str)) Str='norm(Zschur''*Zschur-I)'; texttest(Str,eval(Str)) nrmSschur=max(norm(Sschur),1.e-8); nrmTschur=max(norm(Tschur),1.e-8); Str='norm(tril(Sschur,-1))/nrmSschur'; texttest(Str,eval(Str)) Str='norm(tril(Tschur,-1))/nrmTschur'; texttest(Str,eval(Str)) end fprintf('\n==================================================\n') end if k==0 disp('no eigenvalue could be detected with the required precision') end return %%%======== END JDQZ ==================================================== %%%====================================================================== %%%======== PREPROCESSING =============================================== %%%====================================================================== %%%======== ARNOLDI (for initial spaces) ================================ function [V,AV,BV]=Arnoldi(v,Av,Bv,sigma,jmin,nselect,tol) % Apply Arnoldi with M\(A*sigma(1)'+B*sigma(2)'), to construct an % initial search subspace % global Qschur if ischar(sigma), sigma=[0,1]; end [n,j]=size(v); k=size(Qschur,2); jmin=min(jmin,n-k); if j==0 & k>0 v=RepGS(Qschur,rand(n,1)); [Av,Bv]=MV(v); j=1; end V=v; AV=Av; BV=Bv; while j<jmin; v=[Av,Bv]*sigma'; v0=SolvePrecond(v); if sigma(1)==0 & norm(v0-v)<tol, %%%% then precond=I and target = 0: apply Arnoldi with A sigma=[1,0]; v0=Av; end v=RepGS([Qschur,V],v0); V=[V,v]; [Av,Bv]=MV(v); AV=[AV,Av]; BV=[BV,Bv]; j=j+1; end % while return %%%======== END ARNOLDI ================================================= %%%====================================================================== %%%======== POSTPROCESSING ============================================== %%%====================================================================== %%%======== SORT QZ DECOMPOSITION INTERACTION MATRICES ================== function I=CheckSortSchur(Sigma,kappa) % I=CheckSortSchur(Sigma) % Scales Qschur, Sschur, and Tschur such that diag(Tschur) in [0,1] % Reorders the Partial Schur decomposition such that the `eigenvalues' % (diag(S),diag(T)) appear in increasing chordal distance w.r.t. to % Sigma. % If diag(T) is non-singular then Lambda=diag(S)./diag(T) are the % eigenvalues. global Qschur Zschur Sschur Tschur k=size(Sschur,1); if k==0, I=[]; return, end % [AQ,BQ]=MV(Qschur); % Str='norm(AQ-Zschur*Sschur)'; texttest(Str,eval(Str)) % Str='norm(BQ-Zschur*Tschur)'; texttest(Str,eval(Str)) %--- scale such that diag(Tschur) in [0,1] ---- [Tschur,D]=ScaleT(Tschur); Sschur=D\Sschur; % kappa=max(norm(Sschur,inf)/norm(Tschur,inf),1); s=diag(Sschur); t=diag(Tschur); I=(1:k)'; l=size(Sigma,1); for j=1:k J0=(j:k)'; J=SortEig(s(I(J0)),t(I(J0)),Sigma(min(j,l),:),kappa); I(J0)=I(J0(J)); end if ~min((1:k)'==I) [Q,Z,Sschur,Tschur]=SwapQZ(eye(k),eye(k),Sschur,Tschur,I); [Tschur,D2]=ScaleT(Tschur); Sschur=D2\Sschur; Qschur=Qschur*Q; Zschur=Zschur*(D*Z*D2); else Zschur=Zschur*D; end return %======================================================================== function [T,D]=ScaleT(T) % scale such that diag(T) in [0,1] ---- n=sign(diag(T)); n=n+(n==0); D=diag(n); T=D\T; IT=imag(T); RT=real(T); T=RT+IT.*(abs(IT)>eps*abs(RT))*sqrt(-1); return %%%======== COMPUTE SORTED JORDAN FORM ================================== function [X,D,Jor]=FindJordan(S,T,SCHUR) % [X,D,J]=FINDJORDAN(S,T) % For S and T k by k upper triangular matrices % FINDJORDAN computes the Jordan decomposition. % X is a k by k matrix of eigenvectors and principal vectors % D and J are k by matrices, D is diagonal, J is Jordan % such that S*X*D=T*X*J. (diag(D),diag(J)) are the eigenvalues. % If D is non-singular then Lambda=diag(J)./diag(D) % are the eigenvalues. % coded by Gerard Sleijpen, May, 2002 k=size(S,1); s=diag(S); t=diag(T); n=sign(t); n=n+(n==0); D=sqrt(conj(s).*s+conj(t).*t).*n; S=diag(D)\S; T=diag(D)\T; D=diag(diag(T)); if k<1, if k==0, X=[]; D=[]; Jor=[]; end if k==1, X=1; Jor=s; end return end tol=k*(norm(S,1)+norm(T,1))*eps; [X,Jor,I]=PseudoJordan(S,T,tol); if SCHUR == 0 for l=1:length(I)-1 if I(l)<I(l+1)-1, J=[I(l):I(l+1)-1]; [U,JJor]=JordanBlock(Jor(J,J),tol); X(:,J)=X(:,J)*U; Jor(J,J)=JJor; end end end Jor=Jor+diag(diag(S)); Jor=Jor.*(abs(Jor)>tol); return %================================================== function [X,Jor,J]=PseudoJordan(S,T,delta) % Computes a pseudo-Jordan decomposition for the upper triangular % matrices S and T with ordered diagonal elements. % S*X*(diag(diag(T)))=T*X*(diag(diag(S))+Jor) % with X(:,i:j) orthonormal if its % columns span an invariant subspace of (S,T). k=size(S,1); s=diag(S); t=diag(T); Jor=zeros(k); X=eye(k); J=1; for i=2:k I=[1:i]; C=t(i,1)*S(I,I)-s(i,1)*T(I,I); C(i,i)=norm(C,inf); if C(i,i)>0 tol=delta*C(i,i); for j=i:-1:1 if j==1 | abs(C(j-1,j-1))>tol, break; end end e=zeros(i,1); e(i,1)=1; if j==i J=[J,i]; q=C\e; X(I,i)=q/norm(q); else q=X(I,j:i-1); q=[C,T(I,I)*q;q',zeros(i-j)]\[e;zeros(i-j,1)]; q=q/norm(q(I,1)); X(I,i)=q(I,1); Jor(j:i-1,i)=-q(i+1:2*i-j,1); end end end J=[J,k+1]; return %================================================== function [X,Jor,U]=JordanBlock(A,tol) % If A is nilpotent, then A*X=X*Jor with % Jor a Jordan block % k=size(A,1); Id=eye(k); U=Id; aa=A; j=k; jj=[]; J=1:k; while j>0 [u,s,v]=svd(aa); U(:,J)=U(:,J)*v; sigma=diag(s); delta=tol; J=find(sigma<delta); if isempty(J),j=0; else, j=min(J)-1; end jj=[jj,j]; if j==0, break, end aa=v'*u*s; J=1:j; aa=aa(J,J); end Jor=U'*A*U; Jor=Jor.*(abs(Jor)>tol); l=length(jj); jj=[jj(l:-1:1),k]; l2=jj(2)-jj(1); J=jj(1)+(1:l2); JX=Id(:,J); X=Id; for j=2:l l1=l2+1; l2=jj(j+1)-jj(j); J2=l1:l2; J=jj(j)+(1:l2); JX=Jor*JX; D=diag(sqrt(diag(JX'*JX))); JX=JX/D; [Q,S,V]=svd(JX(J,:)); JX=[JX,Id(:,J)*Q(:,J2)]; X(:,J)=JX; end J=[]; for i=1:l2 for k=l:-1:1 j=jj(k)+i; if j<=jj(k+1), J=[J,j]; end end end X=X(:,J); Jor=X\(Jor*X); X=U*X; Jor=Jor.*(abs(Jor)>100*tol); return %%%======== END JORDAN FORM ============================================= %%%======== OUTPUT ====================================================== function varargout=output(history,SCHUR,X,Lambda) global Qschur Zschur Sschur Tschur if nargout == 1, varargout{1}=diag(Sschur)./diag(Tschur); return, end if nargout > 2, varargout{nargout}=history; end if nargout < 6 & SCHUR == 1 if nargout >1, varargout{1}=Qschur; varargout{2}=Zschur; end if nargout >2, varargout{3}=Sschur; end if nargout >3, varargout{4}=Tschur; end end %-------------- compute eigenpairs -------------------------------------- if SCHUR ~= 1 varargout{1}=X; varargout{2}=Lambda; if nargout >3, varargout{3}=Qschur; varargout{4}=Zschur; end if nargout >4, varargout{5}=Sschur; end if nargout >5, varargout{6}=Tschur; end end return %%%====================================================================== %%%======== UPDATE PRECONDITIONED SCHUR VECTORS ========================= %%%====================================================================== function UpdateMinvZ global Qschur Zschur MinvZ QastMinvZ [n,k]=size(Qschur); if k==1, MinvZ=zeros(n,0); QastMinvZ = []; end Minv_z=SolvePrecond(Zschur(:,k)); QastMinvZ=[[QastMinvZ;Qschur(:,k)'*MinvZ],Qschur'*Minv_z]; MinvZ=[MinvZ,Minv_z]; return %%%====================================================================== %%%======== SOLVE CORRECTION EQUATION =================================== %%%====================================================================== function [t,xtol]=SolvePCE(theta,q,z,r,lsolver,par,nit) global Qschur Zschur Q=[Qschur,q]; Z=[Zschur,z]; switch lsolver case 'exact' [t,xtol] = exact(theta,Q,Z,r); case {'gmres','cgstab','olsen'} [MZ,QMZ]=FormPM(q,z); %%% solve preconditioned system [t,xtol] = feval(lsolver,theta,Q,Z,MZ,QMZ,r,spar(par,nit)); end return %------------------------------------------------------------------------ function [MZ,QMZ]=FormPM(q,z) % compute vectors and matrices for skew projection global Qschur MinvZ QastMinvZ Minv_z=SolvePrecond(z); QMZ=[QastMinvZ,Qschur'*Minv_z;q'*MinvZ,q'*Minv_z]; MZ=[MinvZ,Minv_z]; return %%%====================================================================== %%%======== LINEAR SOLVERS ============================================== %%%====================================================================== function [x,xtol] = exact(theta,Q,Z,r) % produces the exact solution if matrices are given % Is only feasible for low dimensional matrices % Only of interest for experimental purposes % global Operator_A Operator_B n=size(r,1); if ischar(Operator_A) [MZ,QMZ]=FormPM(Q(:,end),Z(:,end)); if n>200 [x,xtol]=SolvePCE(theta,Q,Z,MZ,QMZ,r,'cgstab',[1.0e-10,500,4]); else [x,xtol]=SolvePCE(theta,Q,Z,MZ,QMZ,r,'gmres',[1.0e-10,100]); end return end k=size(Q,2); Aug=[theta(2)*Operator_A-theta(1)*Operator_B,Z;Q',zeros(k,k)]; x=Aug\[r;zeros(k,1)]; x([n+1:n+k],:)=[]; xtol=1; % L=eig(full(Aug)); plot(real(L),imag(L),'*'), pause %%% [At,Bt]=MV(x); At=theta(2)*At-theta(1)*Bt; %%% xtol=norm(r-At+Z*(Z'*At))/norm(r); return %%%===== Iterative methods ============================================== function [r,xtol] = olsen(theta,Q,Z,MZ,M,r,par) % returns the preconditioned residual as approximate solution % May be sufficient in case of an excellent preconditioner r=SkewProj(Q,MZ,M,SolvePrecond(r)); xtol=0; return %------------------------------------------------------------------------ function [x,rnrm] = cgstab(theta,Q,Z,MZ,M,r,par) % BiCGstab(ell) with preconditioning % [x,rnrm] = cgstab(theta,Q,Z,MZ,M,r,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=r % where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q'). % using (I-MZ*(M\Q'))*inv(K) as preconditioner % % This function is specialized for use in JDQZ. % integer nmv: number of matrix multiplications % rnrm: relative residual norm % % par=[tol,mxmv,ell] where % integer m: max number of iteration steps % real tol: residual reduction % % rnrm: obtained residual reduction % % -- References: ETNA % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization -- % global Precond_Type tol=par(1); max_it=par(2); l=par(3); n=size(r,1); rnrm=1; nmv=0; if max_it < 2 | tol>=1, x=r; return, end %%% 0 step of bicgstab eq. 1 step of bicgstab %%% Then x is a multiple of b TP=Precond_Type; if TP==0, r=SkewProj(Q,MZ,M,SolvePrecond(r)); tr=r; else, tr=RepGS(Z,r); end rnrm=norm(r); snrm=rnrm; tol=tol*snrm; sigma=1; omega=1; x=zeros(n,1); u=zeros(n,1); J1=2:l+1; %%% HIST=[0,1]; if TP <2 %% explicit preconditioning % -- Iteration loop while (nmv < max_it) sigma=-omega*sigma; for j = 1:l, rho=tr'*r(:,j); bet=rho/sigma; u=r-bet*u; u(:,j+1)=PreMV(theta,Q,MZ,M,u(:,j)); sigma=tr'*u(:,j+1); alp=rho/sigma; r=r-alp*u(:,2:j+1); r(:,j+1)=PreMV(theta,Q,MZ,M,r(:,j)); x=x+alp*u(:,1); G(1,1)=r(:,1)'*r(:,1); rnrm=sqrt(G(1,1)); if rnrm<tol, l=j; J1=2:l+1; r=r(:,1:l+1); break, end end nmv = nmv+2*l; for i=2:l+1 G(i,1:i)=r(:,i)'*r(:,1:i); G(1:i,i)=G(i,1:i)'; end if TP, g=Z'*r; G=G-g'*g; end d=G(J1,1); gamma=G(J1,J1)\d; rnrm=sqrt(real(G(1,1)-d'*gamma)); %%% compute norm in l-space %%% HIST=[HIST;[nmv,rnrm/snrm]]; x=x+r(:,1:l)*gamma; if rnrm < tol, break, end %%% sufficient accuracy. No need to update r,u omega=gamma(l,1); gamma=[1;-gamma]; u=u*gamma; r=r*gamma; if TP, g=g*gamma; r=r-Z*g; end % rnrm = norm(r); end else %% implicit preconditioning I=eye(2*l); v0=I(:,1:l); s0=I(:,l+1:2*l); y0=zeros(2*l,1); V=zeros(n,2*l); while (nmv < max_it) sigma=-omega*sigma; y=y0; v=v0; s=s0; for j = 1:l, rho=tr'*r(:,j); bet=rho/sigma; u=r-bet*u; if j>1, %%% collect the updates for x in l-space v(:,1:j-1)=s(:,1:j-1)-bet*v(:,1:j-1); end [u(:,j+1),V(:,j)]=PreMV(theta,Q,MZ,M,u(:,j)); sigma=tr'*u(:,j+1); alp=rho/sigma; r=r-alp*u(:,2:j+1); if j>1, s(:,1:j-1)=s(:,1:j-1)-alp*v(:,2:j); end [r(:,j+1),V(:,l+j)]=PreMV(theta,Q,MZ,M,r(:,j)); y=y+alp*v(:,1); G(1,1)=r(:,1)'*r(:,1); rnrm=sqrt(G(1,1)); if rnrm<tol, l=j; J1=2:l+1; s=s(:,1:l); break, end end nmv = nmv+2*l; for i=2:l+1 G(i,1:i)=r(:,i)'*r(:,1:i); G(1:i,i)=G(i,1:i)'; end g=Z'*r; G=G-g'*g; %%% but, do the orth to Z implicitly d=G(J1,1); gamma=G(J1,J1)\d; rnrm=sqrt(real(G(1,1)-d'*gamma)); %%% compute norm in l-space x=x+V*(y+s*gamma); %%% HIST=[HIST;[nmv,rnrm/snrm]]; if rnrm < tol, break, end %%% sufficient accuracy. No need to update r,u omega=gamma(l,1); gamma=[1;-gamma]; u=u*gamma; r=r*gamma; g=g*gamma; r=r-Z*g; %%% Do the orth to Z explicitly %%% In exact arithmetic not needed, but %%% appears to be more stable. end end if TP==1, x=SkewProj(Q,MZ,M,SolvePrecond(x)); end rnrm = rnrm/snrm; %%% plot(HIST(:,1),log10(HIST(:,2)+eps),'*'), drawnow return %---------------------------------------------------------------------- function [v,rnrm] = gmres0(theta,Q,Z,MZ,M,v,par) % GMRES % [x,rnrm] = gmres(theta,Q,Z,MZ,M,v,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=b % where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q'). % using (I-MZ*(M\Q'))*inv(K) as preconditioner % % If used as implicit preconditioner then FGMRES. % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % rnrm: obtained residual reduction % % -- References: Saad & Schultz SISC 1986 % Gerard Sleijpen ([email protected]) % Copyright (c) 1998, Gerard Sleijpen % -- Initialization global Precond_Type tol=par(1); max_it=par(2); n = size(v,1); rnrm = 1; j=0; if max_it < 2 | tol>=1, return, end %%% 0 step of gmres eq. 1 step of gmres %%% Then x is a multiple of b H = zeros(max_it +1,max_it); Rot=[ones(1,max_it);zeros(1,max_it)]; TP=Precond_Type; TP=Precond_Type; if TP==0 v=SkewProj(Q,MZ,M,SolvePrecond(v)); rho0 = norm(v); v = v/rho0; else v=RepGS(Z,v); end V = [v]; tol = tol * rnrm; y = [ rnrm ; zeros(max_it,1) ]; while (j < max_it) & (rnrm > tol), j=j+1; [v,w]=PreMV(theta,Q,MZ,M,v); if TP if TP == 2, W=[W,w]; end v=RepGS(Z,v,0); end [v,h] = RepGS(V,v); H(1:size(h,1),j) = h; V = [V, v]; for i = 1:j-1, a = Rot(:,i); H(i:i+1,j) = [a'; -a(2) a(1)]*H(i:i+1,j); end J=[j, j+1]; a=H(J,j); if a(2) ~= 0 cs = norm(a); a = a/cs; Rot(:,j) = a; H(J,j) = [cs; 0]; y(J) = [a'; -a(2) a(1)]*y(J); end rnrm = abs(y(j+1)); end J=[1:j]; if TP == 2 v = W(:,J)*(H(J,J)\y(J)); else v = V(:,J)*(H(J,J)\y(J)); end if TP==1, v=SkewProj(Q,MZ,M,SolvePrecond(v)); end return %%%====================================================================== function [v,rnrm] = gmres(theta,Q,Z,MZ,M,v,par) % GMRES % [x,nmv,rnrm] = gmres(theta,Q,Z,MZ,M,v,par) % Computes iteratively an approximation to the solution % of the linear system Q'*x = 0 and Atilde*x=r % where Atilde=(I-Z*Z)*(A-theta*B)*(I-Q*Q'). % using (I-MZ*(M\Q'))*inv(K) as preconditioner. % % If used as implicit preconditioner, then FGMRES. % % par=[tol,m] where % integer m: degree of the minimal residual polynomial % real tol: residual reduction % % nmv: number of MV with Atilde % rnrm: obtained residual reduction % % -- References: Saad % Same as gmres0. However this variant uses MATLAB built-in functions % slightly more efficient (see Sleijpen and van den Eshof). % % % Gerard Sleijpen ([email protected]) % Copyright (c) 2002, Gerard Sleijpen global Precond_Type % -- Initialization tol=par(1); max_it=par(2); n = size(v,1); j=0; if max_it < 2 | tol>=1, rnrm=1; return, end %%% 0 step of gmres eq. 1 step of gmres %%% Then x is a multiple of b H = zeros(max_it +1,max_it); Gamma=1; rho=1; TP=Precond_Type; if TP==0 v=SkewProj(Q,MZ,M,SolvePrecond(v)); rho0 = norm(v); v = v/rho0; else v=RepGS(Z,v); rho0=1; end V = zeros(n,0); W=zeros(n,0); tol0 = 1/(tol*tol); %% HIST=1; while (j < max_it) & (rho < tol0) V=[V,v]; j=j+1; [v,w]=PreMV(theta,Q,MZ,M,v); if TP if TP == 2, W=[W,w]; end v=RepGS(Z,v,0); end [v,h] = RepGS(V,v); H(1:size(h,1),j)=h; gamma=H(j+1,j); if gamma==0, break %%% Lucky break-down else gamma= -Gamma*h(1:j)/gamma; Gamma=[Gamma,gamma]; rho=rho+gamma'*gamma; end %% HIST=[HIST;(gamma~=0)/sqrt(rho)]; end if gamma==0; %%% Lucky break-down e1=zeros(j,1); e1(1)=rho0; rnrm=0; if TP == 2 v=W*(H(1:j,1:j)\e1); else v=V*(H(1:j,1:j)\e1); end else %%% solve in least square sense e1=zeros(j+1,1); e1(1)=rho0; rnrm=1/sqrt(rho); if TP == 2 v=W*(H(1:j+1,1:j)\e1); else v=V*(H(1:j+1,1:j)\e1); end end if TP==1, v=SkewProj(Q,MZ,M,SolvePrecond(v)); end %% HIST=log10(HIST+eps); J=[0:size(HIST,1)-1]'; %% plot(J,HIST(:,1),'*'); drawnow return %%%======== END SOLVE CORRECTION EQUATION =============================== %%%====================================================================== %%%======== BASIC OPERATIONS ============================================ %%%====================================================================== function [Av,Bv]=MV(v) % [y,z]=MV(x) % y=A*x, z=B*x % y=MV(x,theta) % y=(A-theta*B)*x % global Operator_Form Operator_MVs Operator_A Operator_B Operator_Params Bv=v; switch Operator_Form case 1 % both Operator_A and B are strings Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=feval(Operator_B,Operator_Params{:}); case 2 Operator_Params{1}=v; [Av,Bv]=feval(Operator_A,Operator_Params{:}); case 3 Operator_Params{1}=v; Operator_Params{2}='A'; Av=feval(Operator_A,Operator_Params{:}); Operator_Params{2}='B'; Bv=feval(Operator_A,Operator_Params{:}); case 4 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=Operator_B*v; case 5 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); case 6 Av=Operator_A*v; Operator_Params{1}=v; Bv=feval(Operator_B,Operator_Params{:}); case 7 Av=Operator_A*v; Bv=Operator_B*v; case 8 Av=Operator_A*v; end Operator_MVs = Operator_MVs +size(v,2); % [Av(1:5,1),Bv(1:5,1)], pause return %------------------------------------------------------------------------ function y=SolvePrecond(y); global Precond_Form Precond_L Precond_U Precond_P Precond_Params Precond_Solves switch Precond_Form case 0, case 1, Precond_Params{1}=y; y=feval(Precond_L,Precond_Params{:}); case 2, Precond_Params{1}=y; Precond_Params{2}='preconditioner'; y=feval(Precond_L,Precond_Params{:}); case 3, Precond_Params{1}=y; Precond_Params{1}=feval(Precond_L,Precond_Params{:}); y=feval(Precond_U,Precond_Params{:}); case 4, Precond_Params{1}=y; Precond_Params{2}='L'; Precond_Params{1}=feval(Precond_L,Precond_Params{:}); Precond_Params{2}='U'; y=feval(Precond_L,Precond_Params{:}); case 5, y=Precond_L\y; case 6, y=Precond_U\(Precond_L\y); case 7, y=Precond_U\(Precond_L\(Precond_P*y)); end if Precond_Form Precond_Solves = Precond_Solves +size(y,2); end %% y(1:5,1), pause return %------------------------------------------------------------------------ function [v,u]=PreMV(theta,Q,Z,M,v) % v=Atilde*v global Precond_Type if Precond_Type u=SkewProj(Q,Z,M,SolvePrecond(v)); [v,w]=MV(u); v=theta(2)*v-theta(1)*w; else [v,u]=MV(v); u=theta(2)*v-theta(1)*u; v=SkewProj(Q,Z,M,SolvePrecond(u)); end return %------------------------------------------------------------------------ function r=SkewProj(Q,Z,M,r); if ~isempty(Q), r=r-Z*(M\(Q'*r)); end return %------------------------------------------------------------------------ function ppar=spar(par,nit) k=size(par,2)-2; ppar=par(1,k:k+2); if k>1 if nit>k ppar(1,1)=par(1,k)*((par(1,k)/par(1,k-1))^(nit-k)); else ppar(1,1)=par(1,max(nit,1)); end end ppar(1,1)=max(ppar(1,1),1.0e-8); return %------------------------------------------------------------------------ function u=ImagVector(u) % computes "essential" imaginary part of a vector maxu=max(u); maxu=maxu/abs(maxu); u=imag(u/maxu); return %------------------------------------------------------------------------ function Sigma=ScaleEig(Sigma) % % n=sign(Sigma(:,2)); n=n+(n==0); d=sqrt((Sigma.*conj(Sigma))*[1;1]).*n; Sigma=diag(d)\Sigma; return %%%======== COMPUTE r AND z ============================================= function [r,z,nrm,theta]=Comp_rz(E,kappa) % % [r,z,nrm,theta]=Comp_rz(E) % computes the direction r of the minimal residual, % the left projection vector z, % the approximate eigenvalue theta % % [r,z,nrm,theta]=Comp_rz(E,kappa) % kappa is a scaling factor. % % coded by Gerard Sleijpen, version Januari 7, 1998 if nargin == 1 kappa=norm(E(:,1))/norm(E(:,2)); kappa=2^(round(log2(kappa))); end if kappa ~=1, E(:,1)=E(:,1)/kappa; end [Q,sigma,u]=svd(E,0); %%% E*u=Q*sigma, sigma(1,1)>sigma(2,2) r=Q(:,2); z=Q(:,1); nrm=sigma(2,2); % nrm=nrm/sigma(1,1); nrmz=sigma(1,1) u(1,:)=u(1,:)/kappa; theta=[-u(2,2),u(1,2)]; return %%%======== END computation r and z ===================================== %%%====================================================================== %%%======== Orthogonalisation =========================================== %%%====================================================================== function [V,R]=RepGS(Z,V,gamma) % % Orthonormalisation using repeated Gram-Schmidt % with the Daniel-Gragg-Kaufman-Stewart (DGKS) criterion % % Q=RepGS(V) % The n by k matrix V is orthonormalized, that is, % Q is an n by k orthonormal matrix and % the columns of Q span the same space as the columns of V % (in fact the first j columns of Q span the same space % as the first j columns of V for all j <= k). % % Q=RepGS(Z,V) % Assuming Z is n by l orthonormal, V is orthonormalized against Z: % [Z,Q]=RepGS([Z,V]) % % Q=RepGS(Z,V,gamma) % With gamma=0, V is only orthogonalized against Z % Default gamma=1 (the same as Q=RepGS(Z,V)) % % [Q,R]=RepGS(Z,V,gamma) % if gamma == 1, V=[Z,Q]*R; else, V=Z*R+Q; end % coded by Gerard Sleijpen, March, 2002 % if nargin == 1, V=Z; Z=zeros(size(V,1),0); end if nargin <3, gamma=1; end [n,dv]=size(V); [m,dz]=size(Z); if gamma, l0=min(dv+dz,n); else, l0=dz; end R=zeros(l0,dv); if dv==0, return, end if dz==0 & gamma==0, return, end % if m~=n % if m<n, Z=[Z;zeros(n-m,dz)]; end % if m>n, V=[V;zeros(m-n,dv)]; n=m; end % end if (dz==0 & gamma) j=1; l=1; J=1; q=V(:,1); nr=norm(q); R(1,1)=nr; while nr==0, q=rand(n,1); nr=norm(q); end, V(:,1)=q/nr; if dv==1, return, end else j=0; l=0; J=[]; end while j<dv, j=j+1; q=V(:,j); nr_o=norm(q); nr=eps*nr_o; if dz>0, yz=Z'*q; q=q-Z*yz; end if l>0, y=V(:,J)'*q; q=q-V(:,J)*y; end nr_n=norm(q); while (nr_n<0.5*nr_o & nr_n > nr) if dz>0, sz=Z'*q; q=q-Z*sz; yz=yz+sz; end if l>0, s=V(:,J)'*q; q=q-V(:,J)*s; y=y+s; end nr_o=nr_n; nr_n=norm(q); end if dz>0, R(1:dz,j)=yz; end if l>0, R(dz+J,j)=y; end if ~gamma V(:,j)=q; elseif l+dz<n, l=l+1; if nr_n <= nr % expand with a random vector % if nr_n==0 V(:,l)=RepGS([Z,V(:,J)],rand(n,1)); % else % which can be numerical noice % V(:,l)=q/nr_n; % end else V(:,l)=q/nr_n; R(dz+l,j)=nr_n; end J=[1:l]; end end % while j if gamma & l<dv, V=V(:,J); end return %%%======== END Orthogonalisation ====================================== %%%====================================================================== %%%======== Sorts Schur form ============================================ %%%====================================================================== function [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma,u) % % [Q,Z,S,T]=SortQZ(A,B,tau) % A and B are k by k matrices, tau is a complex pair [alpha,beta]. % SortQZ computes the qz-decomposition of (A,B) with prescribed % ordering: A*Q=Z*S, B*Q=Z*T; % Q and Z are unitary k by k matrices, % S and T are upper triangular k by k matrices. % The ordering is as follows: % (diag(S),diag(T)) are the eigenpairs of (A,B) ordered % with increasing "chordal distance" w.r.t. tau. % % If tau is a scalar then [tau,1] is used. % Default value for tau is tau=0, i.e., tau=[0,1]. % % [Q,Z,S,T]=SortQZ(A,B,tau,kappa) % kappa scales A first: A/kappa. Default kappa=1. % % [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma) % Sorts the first MAX(gamma,1) elements. Default: gamma=k % % [Q,Z,S,T]=SortQZ(A,B,tau,kappa,gamma,u) % Now, with ordering such that angle u and Q(:,1) is less than 45o, % and, except for the first pair, (diag(S),diag(T)) are % with increasing "chordal distance" w.r.t. tau. % If such an ordering does not exist, ordering is as without u. % % coded by Gerard Sleijpen, version April, 2002 k=size(A,1); if k==1, Q=1; Z=1; S=A;T=B; return, end kk=k-1; if nargin < 3, tau=[0,1]; end if nargin < 4, kappa=1; end if nargin > 4, kk=max(1,min(gamma,k-1)); end %% kappa=max(norm(A,inf)/max(norm(B,inf),1.e-12),1); %% kappa=2^(round(log2(kappa))); %%%------ compute the qz factorization ------- [S,T,Z,Q]=qz(A,B); Z=Z'; % kkappa=max(norm(A,inf),norm(B,inf)); % Str='norm(A*Q-Z*S)';texttest(Str,eval(Str)) % Str='norm(B*Q-Z*T)';texttest(Str,eval(Str)) %%%------ scale the eigenvalues -------------- t=diag(T); n=sign(t); n=n+(n==0); D=diag(n); Q=Q/D; S=S/D; T=T/D; %%%------ sort the eigenvalues --------------- I=SortEig(diag(S),real(diag(T)),tau,kappa); %%%------ swap the qz form ------------------- [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I(1:kk)); % Str='norm(A*Q-Z*S)';texttest(Str,eval(Str)) % Str='norm(B*Q-Z*T)';texttest(Str,eval(Str)) if nargin < 6 | size(u,2) ~= 1 return else %%% repeat SwapQZ if angle is too small kk=min(size(u,1),k); J=1:kk; u=u(J,1)'*Q(J,:); if abs(u(1,1))>0.7, return, end for j=2:kk J=1:j; if norm(u(1,J))>0.7 J0=[j,1:j-1]; [Qq,Zz,Ss,Tt]=SwapQZ(eye(j),eye(j),S(J,J),T(J,J),J0); if abs(u(1,J)*Qq(:,1))>0.71 Q(:,J)=Q(:,J)*Qq; Z(:,J)=Z(:,J)*Zz; S(J,J)=Ss; S(J,j+1:k)=Zz'*S(J,j+1:k); T(J,J)=Tt; T(J,j+1:k)=Zz'*T(J,j+1:k); % Str='norm(A*Q-Z*S)';texttest(Str,eval(Str)) % Str='norm(B*Q-Z*T)';texttest(Str,eval(Str)) fprintf(' Took %2i:%6.4g\n',j,S(1,1)./T(1,1)) return end end end disp([' Selection problem: took ',num2str(1)]) return end %%%====================================================================== function I=SortEig(s,t,sigma,kappa); % % I=SortEig(S,T,SIGMA) sorts the indices of [S,T] as prescribed by SIGMA % S and T are K-vectors. % % If SIGMA=[ALPHA,BETA] is a complex pair then % if CHORDALDISTANCE % sort [S,T] with increasing chordal distance w.r.t. SIGMA. % else % sort S./T with increasing distance w.r.t. SIGMA(1)/SIGMA(2) % % The chordal distance D between a pair A and a pair B is % defined as follows. % Scale A by a scalar F such that NORM(F*A)=1. % Scale B by a scalar G such that NORM(G*B)=1. % Then D(A,B)=SQRT(1-ABS((F*A)*(G*B)')). % % I=SortEig(S,T,SIGMA,KAPPA). Kappa is a caling that effects the % chordal distance: [S,KAPPA*T] w.r.t. [SIGMA(1),KAPPA*SIGMA(2)]. % coded by Gerard Sleijpen, version April 2002 global CHORDALDISTANCE if ischar(sigma) warning off, s=s./t; warning on switch sigma case 'LM' [s,I]=sort(-abs(s)); case 'SM' [s,I]=sort(abs(s)); case 'LR'; [s,I]=sort(-real(s)); case 'SR'; [s,I]=sort(real(s)); case 'BE'; [s,I]=sort(real(s)); I=twistdim(I,1); end elseif CHORDALDISTANCE if kappa~=1, t=kappa*t; sigma(2)=kappa*sigma(2); end n=sqrt(s.*conj(s)+t.*t); [s,I]=sort(-abs([s,t]*sigma')./n); else warning off, s=s./t; warning on if sigma(2)==0; [s,I]=sort(-abs(s)); else, [s,I]=sort(abs(s-sigma(1)/sigma(2))); end end return %------------------------------------------------------------------------ function t=twistdim(t,k) d=size(t,k); J=1:d; J0=zeros(1,2*d); J0(1,2*J)=J; J0(1,2*J-1)=flipdim(J,2); I=J0(1,J); if k==1, t=t(I,:); else, t=t(:,I); end return %%%====================================================================== function [Q,Z,S,T]=SwapQZ(Q,Z,S,T,I) % [Q,Z,S,T]=SwapQZ(QQ,ZZ,SS,TT,P) % QQ and ZZ are K by K unitary, SS and TT are K by K uper triangular. % P is the first part of a permutation of (1:K)'. % % Then Q and Z are K by K unitary, S and T are K by K upper triangular, % such that, for A = ZZ*SS*QQ' and B = ZZ*T*QQ', we have % A*Q = Z*S, B*Q = Z*T and LAMBDA(1:LENGTH(P))=LLAMBDA(P) where % LAMBDA=DIAG(S)./DIAGg(T) and LLAMBDA=DIAG(SS)./DIAG(TT). % % Computation uses Givens rotations. % % coded by Gerard Sleijpen, version October 12, 1998 kk=min(length(I),size(S,1)-1); j=1; while (j<=kk & j==I(j)), j=j+1; end while j<=kk i=I(j); for k = i-1:-1:j, %%% i>j, move ith eigenvalue to position j J = [k,k+1]; q = T(k+1,k+1)*S(k,J) - S(k+1,k+1)*T(k,J); if q(1) ~= 0 q = q/norm(q); G = [[q(2);-q(1)],q']; Q(:,J) = Q(:,J)*G; S(:,J) = S(:,J)*G; T(:,J) = T(:,J)*G; end if abs(S(k+1,k))<abs(T(k+1,k)), q=T(J,k); else q=S(J,k); end if q(2) ~= 0 q=q/norm(q); G = [q';q(2),-q(1)]; Z(:,J) = Z(:,J)*G'; S(J,:) = G*S(J,:); T(J,:) = G*T(J,:); end T(k+1,k) = 0; S(k+1,k) = 0; end I=I+(I<i); j=j+1; while (j<=kk & j==I(j)), j=j+1; end end return %------------------------------------------------------------------------ function [Q,Z,S,T]=SwapQZ0(Q,Z,S,T,I) % % [Q,Z,S,T]=sortqz0(A,B,s,t,k) % A and B are k by k matrices, t and s are k vectors such that % (t(i),s(i)) eigenpair (A,B), i.e. t(i)*A-s(i)*B singular. % Computes the Schur form with a ordering prescribed by (t,s): % A*Q=Z*S, B*Q=Z*T such that diag(S)./diag(T)=s./t. % Computation uses Householder reflections. % % coded by Gerard Sleijpen, version October 12, 1997 k=size(S,1); s=diag(S); t=diag(T); s=s(I,1); t=t(I,1); for i=1:k-1 %%% compute q s.t. C*q=(t(i,1)*S-s(i,1)*T)*q=0 C=t(i,1)*S(i:k,i:k)-s(i,1)*T(i:k,i:k); [q,r,p]=qr(C); %% C*P=Q*R %% check whether last but one diag. elt r nonzero j=k-i; while abs(r(j,j))<eps*norm(r); j=j-1; end; j=j+1; r(j,j)=1; e=zeros(j,1); e(j,1)=1; q=p*([r(1:j,1:j)\e;zeros(k-i+1-j,1)]); q=q/norm(q);%% C*q %%% end computation q z=conj(s(i,1))*S(i:k,i:k)*q+conj(t(i,1))*T(i:k,i:k)*q; z=z/norm(z); a=q(1,1); if a ~=0, a=abs(a)/a; q=a*q; end a=z(1,1); if a ~=0, a=abs(a)/a; z=a*z; end q(1,1)=q(1,1)+1; q=q/norm(q); q=[zeros(i-1,1);q]; z(1,1)=z(1,1)+1; z=z/norm(z); z=[zeros(i-1,1);z]; S=S-(S*q)*(2*q)'; S=S-(2*z)*(z'*S); T=T-(T*q)*(2*q)'; T=T-(2*z)*(z'*T); Q=Q-(Q*q)*(2*q)'; Z=Z-(Z*z)*(2*z)'; end return %%%======== END sort QZ decomposition interaction matrices ============== %%%====================================================================== %%%======== INITIALIZATION ============================================== %%%====================================================================== function MyClear global Operator_Form Operator_A Operator_B Operator_Params ... Precond_L Precond_U Precond_P Precond_Params ... Precond_Form Precond_Type ... Operator_MVs Precond_Solves ... CHORDALDISTANCE ... Qschur Zschur Sschur Tschur ... MinvZ QastMinvZ return %%%====================================================================== function [n,nselect,Sigma,kappa,SCHUR,... jmin,jmax,tol,maxit,V,AV,BV,TS,DISP,PAIRS,JDV,FIX,track,NSIGMA,... lsolver,par] = ReadOptions(varargin) % Read options and set defaults global Operator_Form Operator_A Operator_B Operator_Params ... Precond_Form Precond_L Precond_U Precond_P Precond_Params ... CHORDALDISTANCE Operator_A = varargin{1}; n=CheckMatrix(Operator_A,1); % defaults %%%% search for 'xx' in fieldnames nselect0= 5; maxit = 200; %%%% 'ma' SCHUR = 0; %%%% 'sch' tol = 1e-8; %%%% 'to' DISP = 0; %%%% 'di' p0 = 5; %%% jmin=nselect+p0 %%%% 'jmi' p1 = 5; %%% jmax=jmin+p1 %%%% 'jma' TS = 1; %%%% 'te' PAIRS = 0; %%%% 'pai' JDV = 0; %%%% 'av' track = 1e-4; %%%% 'tr' FIX = 1000; %%%% 'fix' NSIGMA = 0; %%%% 'ns' CHORD = 1; %%%% 'ch' lsolver = 'gmres'; %%%% 'lso' ls_maxit= 200; %%%% 'ls_m' ls_tol = [0.7,0.49]; %%%% 'ls_t' ell = 4; %%%% 'ls_e' TP = 0; %%%% 'ty' L = []; %%%% 'l_' U = []; %%%% 'u_' P = []; %%%% 'p_' kappa = 1; %%%% 'sca' V0 = 'ones(n,1)+rand(n,1)'; %%%% 'v0' %% initiation nselect=[]; Sigma=[]; options=[]; Operator_B=[]; jmin=-1; jmax=-1; V=[]; AV=[]; BV=[]; par=[]; %------------------------------------------------ %------- Find quantities ------------------------ %------------------------------------------------ jj=[]; for j = 2:nargin if isstruct(varargin{j}) options = varargin{j}; elseif ischar(varargin{j}) s=varargin{j}; if exist(s)==2 & isempty(Operator_B) Operator_B=s; elseif length(s) == 2 & isempty(Sigma) s=upper(s); switch s case {'LM','SM','LR','SR','BE'}, Sigma=s; otherwise jj=[jj,j]; end else jj=[jj,j]; end elseif min([n,n]==size(varargin{j})) & isempty(Operator_B) Operator_B=varargin{j}; elseif length(varargin{j}) == 1 s = varargin{j}; if isempty(nselect) & isreal(s) & (s == fix(s)) & (s > 0) nselect = min(n,s); elseif isempty(Sigma) Sigma = s; else jj=[jj,j]; end elseif min(size(varargin{j}))==1 & isempty(Sigma) Sigma = varargin{j}; if size(Sigma,1)==1, Sigma=Sigma'; end elseif min(size(varargin{j}))==2 & isempty(Sigma) Sigma = varargin{j}; if size(Sigma,2)>2 , Sigma=Sigma'; end else jj=[jj,j]; end end %------- find parameters for operators ----------- Operator_Params=[]; Operator_Params{2}=''; k=length(jj); if k>0 Operator_Params(3:k+2)=varargin(jj); if ~ischar(Operator_A) msg=sprintf(', %i',jj); msg=sprintf('Input argument, number%s, not recognized.',msg); button=questdlg(msg,'Input arguments','Ignore','Stop','Ignore'); if strcmp(button,'Stop'), n=-1; return, end end end %------- operator B ----------------------------- if isempty(Operator_B) if ischar(Operator_A) Operator_Form=2; % or Operator_Form=3, or Operator_Form=5; else Operator_Form=8; end else if ischar(Operator_B) if ischar(Operator_A), Operator_Form=1; else, Operator_Form=6; end elseif ischar(Operator_A) Operator_Form=4; else Operator_Form=7; end end if n<2, return, end %------- number of eigs to be computed ---------- if isempty(nselect), nselect=min(n,nselect0); end %------------------------------------------------ %------- Analyse Options ------------------------ %------------------------------------------------ fopts = []; if ~isempty(options), fopts = fieldnames(options); end %------- preconditioner ------------------------- Precond_L=findfield(options,fopts,'pr',[]); [L,ok]=findfield(options,fopts,'l_',Precond_L); if ok & ~isempty(Precond_L), msg =sprintf('A preconditioner is defined in'); msg =[msg,sprintf('\n''Precond'', but also in ''L_precond''.')]; msg=[msg,sprintf('\nWhat is the correct one?')]; button=questdlg(msg,'Preconditioner','L_Precond','Precond','L_Precond'); if strcmp(button,'L_Precond'), Precond_L = L; end else Precond_L = L; end if ~isempty(Precond_L) Precond_U=findfield(options,fopts,'u_',[]); Precond_P=findfield(options,fopts,'p_',[]); end Precond_Params=[]; Precond_Params{2}=''; Params=findfield(options,fopts,'par',[]); [l,k]=size(Params); if k>0, if iscell(Params), Precond_Params(3:k+2)=Params; else, Precond_Params{3}=Params; end end TP=findfield(options,fopts,'ty',TP); n=SetPrecond(n,TP); if n<2, return, end %------- max, min dimension search subspace ------ jmin=min(n,findfield(options,fopts,'jmi',jmin)); jmax=min(n,findfield(options,fopts,'jma',jmax)); if jmax < 0 if jmin<0, jmin=min(n,nselect+p0); end jmax=min(n,jmin+p1); else if jmin<0, jmin=max(1,jmax-p1); end end maxit=findfield(options,fopts,'ma',maxit); %------- initial search subspace ---------------- V=findfield(options,fopts,'v',[]); [m,d]=size(V); if m~=n if m>n, V = V(1:n,:); end if m<n, V = [V;0.001*rand(n-m-1,d)]; end end V=orth(V); [m,d]=size(V); if d==0, nr=0; while nr==0, V=eval(V0); nr=norm(V); V=V/nr; end, end %------- Check definition B, Compute AV, BV ----- [AV,BV,n]=CheckDimMV(V); if n<2, return, end %------- Other options -------------------------- tol=findfield(options,fopts,'to',tol); kappa = findfield(options,fopts,'sca',kappa); kappa = abs(kappa(1,1)); if kappa==0, kappa=1; end PAIRS = findfield(options,fopts,'pai',PAIRS,[0,1]); SCHUR = findfield(options,fopts,'sch',SCHUR,[0,1,0.5]); DISP = findfield(options,fopts,'di',DISP,[0,1]); JDV = findfield(options,fopts,'av',JDV,[0,1]); track = max(abs(findfield(options,fopts,'tr',track,[0,track,inf])),0); NSIGMA = findfield(options,fopts,'ns',NSIGMA,[0,1]); FIX = max(abs(findfield(options,fopts,'fix',0,[0,FIX,inf])),0); CHORDALDISTANCE = findfield(options,fopts,'ch',CHORD,[0,1]); [TS0,ok] = findfield(options,fopts,'te',TS); if ok & ischar(TS0) if strncmpi(TS0,'st',2), TS=0; %% 'standard' elseif strncmpi(TS0,'ha',2), TS=1; %% 'harmonic' elseif strncmpi(TS0,'se',2), TS=2; %% 'searchspace' elseif strncmpi(TS0,'bv',2), TS=3; elseif strncmpi(TS0,'av',2), TS=4; end else TS=max(0,min(4,round(TS0(1,1)))); end %------- set targets ---------------- if isempty(Sigma) if TS==1, Sigma=[0,1]; else, Sigma = 'LM'; end elseif ischar(Sigma) switch Sigma case {'LM','LR','SR','BE','SM'} if ~ok, TS=3; end end else [k,l]=size(Sigma); if l==1, Sigma=[Sigma,ones(k,1)]; l=2; end Sigma=ScaleEig(Sigma); end if ischar(Sigma) & TS<2 msg1=sprintf(' The choice sigma = ''%s'' does not match the\n',Sigma); msg2=sprintf(' selected test subspace. Specify a numerical\n'); msg3=sprintf(' value for sigma (e.g. sigma = '); msg4=''; switch Sigma case {'LM','LR'} msg4=sprintf('[1,0]'); case {'SM','SR','BE'} msg4=sprintf(' [0,1]'); end msg5=sprintf('),\n or continue with ''TestSpace''=''B*V''.'); msg=[msg1,msg2,msg3,msg4,msg5]; button=questdlg(msg,'Targets and test subspaces','Continue','Stop','Continue'); if strcmp(button,'Continue'), TS=3; else, n=-1; return, end end %------- linear solver -------------------------- lsolver = findfield(options,fopts,'lso',lsolver); method=strvcat('exact','olsen','iluexact','gmres','cgstab','bicgstab'); j=strmatch(lower(lsolver),method); if isempty(j), msg=['The linear solver ''',lsolver,''' is not included.']; msg=[msg,sprintf('\nIs GMRES ok?')]; button=questdlg(msg,'Linear solver','Yes','No','Yes'); if strcmp(button,'Yes'), j=4; ls_maxit=5; else, n=-1; return, end end if j==1, lsolver='exact'; Precond_Form = 0; elseif j==2 | j==3, lsolver='olsen'; elseif j==4, lsolver='gmres'; ls_maxit=5; else, lsolver='cgstab'; ls_tol=1.0e-10; end ls_maxit= findfield(options,fopts,'ls_m',ls_maxit); ls_tol = findfield(options,fopts,'ls_t',ls_tol); ell = findfield(options,fopts,'ls_e',ell); par=[ls_tol,ls_maxit,ell]; %----- Display the parameters that are used ---------------- if DISP fprintf('\n'),fprintf('PROBLEM\n') switch Operator_Form case {1,4,6,7} fprintf('%13s: %s\n','A',StrOp(Operator_A)); fprintf('%13s: %s\n','B',StrOp(Operator_B)); case 2 fprintf('%13s: ''%s'' ([Av,Bv] = %s(v))\n','A,B',Operator_A,Operator_A); case 3 fprintf('%13s: ''%s''\n','A,B',Operator_A); fprintf('%15s(Av = %s(v,''A''), Bv = %s(v,''B''))\n',... '',Operator_A,Operator_A); case {5,8} fprintf('%13s: %s\n','A',StrOp(Operator_A)); fprintf('%13s: %s\n','B','Identity (B*v = v)'); end fprintf('%13s: %i\n','dimension',n); fprintf('%13s: %i\n\n','nselect',nselect); if length(jj)>0 & (ischar(Operator_A) | ischar(Operator_B)) msgj=sprintf(', %i',jj); msgo=''; if ischar(Operator_A), msgo=sprintf(' ''%s''',Operator_A); end if ischar(Operator_B), msgo=sprintf('%s ''%s''.',msgo,Operator_B); end fprintf(' The JDQZ input arguments, number%s, are\n',msgj) fprintf(' taken as input parameters 3:%i for%s.\n\n',length(jj)+2,msgo); end fprintf('TARGET\n') if ischar(Sigma) fprintf('%13s: ''%s''\n','sigma',Sigma) else fprintf('%13s: %s\n','sigma',mydisp(Sigma(1,:))) for j=2:size(Sigma,1), fprintf('%13s: %s\n','',mydisp(Sigma(j,:))) end end fprintf('\nOPTIONS\n') fprintf('%13s: %g\n','Schur',SCHUR) fprintf('%13s: %g\n','Tol',tol) fprintf('%13s: %i\n','Disp',DISP) fprintf('%13s: %i\n','jmin',jmin) fprintf('%13s: %i\n','jmax',jmax) fprintf('%13s: %i\n','MaxIt',maxit) fprintf('%13s: %s\n','v0',StrOp(V)) fprintf('%13s: %i\n','Pairs',PAIRS) fprintf('%13s: %i\n','AvoidStag',JDV) fprintf('%13s: %i\n','NSigma',NSIGMA) fprintf('%13s: %g\n','Track',track) fprintf('%13s: %g\n','FixShift',FIX) fprintf('%13s: %i\n','Chord',CHORDALDISTANCE) fprintf('%13s: ''%s''\n','LSolver',lsolver) str=sprintf('%g ',ls_tol); fprintf('%13s: [ %s]\n','LS_Tol',str) fprintf('%13s: %i\n','LS_MaxIt',ls_maxit) if strcmp(lsolver,'cgstab') fprintf('%13s: %i\n','LS_ell',ell) end DisplayPreconditioner(n); fprintf('\n') switch TS case 0, str='Standard, W = alpha''*A*V + beta''*B*V'; case 1, str='Harmonic, W = beta*A*V - alpha*B*V'; case 2, str='SearchSpace, W = V'; case 3, str='Petrov, W = B*V'; case 4, str='Petrov, W = A*V'; end fprintf('%13s: %s\n','TestSpace',str); fprintf('\n\n'); end return %------------------------------------------------------------------------ function msg=StrOp(Op) if ischar(Op) msg=sprintf('''%s''',Op); elseif issparse(Op), [n,k]=size(Op); msg=sprintf('[%ix%i sparse]',n,k); else, [n,k]=size(Op); msg=sprintf('[%ix%i double]',n,k); end return %------------------------------------------------------------------------ function DisplayPreconditioner(n) global Precond_Form Precond_Type ... Precond_L Precond_U Precond_P FP=Precond_Form; switch Precond_Form case 0, fprintf('%13s: %s\n','Precond','No preconditioner'); case {1,2,5} fprintf('%13s: %s','Precond',StrOp(Precond_L)); if FP==2, fprintf(' (M\\v = %s(v,''preconditioner''))',Precond_L); end fprintf('\n') case {3,4,6,7} fprintf('%13s: %s\n','L precond',StrOp(Precond_L)); fprintf('%13s: %s\n','U precond',StrOp(Precond_U)); if FP==7, fprintf('%13s: %s\n','P precond',StrOp(Precond_P)); end if FP==4,fprintf('%15s(M\\v = %s(%s(v,''L''),''U''))\n',... '',Precond_L,Precond_L); end end if FP switch Precond_Type case 0, str='explicit left'; case 1, str='explicit right'; case 2, str='implicit'; end fprintf('%15sTo be used as %s preconditioner.\n','',str) end return %------------------------------------------------------------------------ function possibilities fprintf('\n') fprintf('PROBLEM\n') fprintf(' A: [ square matrix | string ]\n'); fprintf(' B: [ square matrix {identity} | string ]\n'); fprintf(' nselect: [ positive integer {5} ]\n\n'); fprintf('TARGET\n') fprintf(' sigma: [ vector of scalars | \n'); fprintf(' pair of vectors of scalars |\n'); fprintf(' {''LM''} | {''SM''} | ''LR'' | ''SR'' | ''BE'' ]\n\n'); fprintf('OPTIONS\n'); fprintf(' Schur: [ yes | {no} ]\n'); fprintf(' Tol: [ positive scalar {1e-8} ]\n'); fprintf(' Disp: [ yes | {no} ]\n'); fprintf(' jmin: [ positive integer {nselect+5} ]\n'); fprintf(' jmax: [ positive integer {jmin+5} ]\n'); fprintf(' MaxIt: [ positive integer {200} ]\n'); fprintf(' v0: '); fprintf('[ size(A,1) by p vector of scalars {rand(size(A,1),1)} ]\n'); fprintf(' TestSpace: '); fprintf('[ Standard | {Harmonic} | SearchSpace | BV | AV ]\n'); fprintf(' Pairs: [ yes | {no} ] \n'); fprintf(' AvoidStag: [ yes | {no} ]\n'); fprintf(' Track: [ {yes} | no non-negative scalar {1e-4} ]\n'); fprintf(' NSigma: [ yes | {no} ]\n'); fprintf(' FixShift: [ yes | {no} | non-negative scalar {1e+3} ]\n'); fprintf(' Chord: [ {yes} | no ]\n'); fprintf(' Scale: [ positive scalar {1} ]\n'); fprintf(' LSolver: [ {gmres} | bicgstab ]\n'); fprintf(' LS_Tol: [ row of positive scalar {[0.7,0.49]} ]\n'); fprintf(' LS_MaxIt: [ positive integer {5} ]\n'); fprintf(' LS_ell: [ positive integer {4} ]\n'); fprintf(' Precond: '); fprintf('[ n by n matrix {identity} | n by 2n matrix | string ]\n'); fprintf(' L_Precond: same as ''Precond''\n'); fprintf(' U_Precond: [ n by n matrix {identity} | string ]\n'); fprintf(' P_Precond: [ n by n matrix {identity} ]\n'); fprintf(' Type_Precond: [ {left} | right | implicit ]\n'); fprintf('\n') return %------------------------------------------------------------------------ function x = boolean(x,gamma,string) %Y = BOOLEAN(X,GAMMA,STRING) % GAMMA(1) is the default. % If GAMMA is not specified, GAMMA = 0. % STRING is a cell of accepted strings. % If STRING is not specified STRING = {'n' 'y'} % STRING{I} and GAMMA(I) are accepted expressions for X % If X=GAMMA(I) then Y=X. If the first L characters % of X matches those of STRING{I}, then Y=GAMMA(I+1). % Here L=SIZE({STRING{1},2). % For other values of X, Y=GAMMA(1); if nargin < 2, gamma=[0,0,1]; end if nargin < 3, string={'n' 'y'}; end if ischar(x) l=size(string{1},2); i=min(find(strncmpi(x,string,l))); if isempty(i), i=0; end, x=gamma(i+1); elseif max((gamma-x)==0) elseif gamma(end) == inf else, x=gamma(1); end return %------------------------------------------------------------------------ function [a,ok]=findfield(options,fopts,str,default,gamma,stri) % Searches the fieldnames in FOPTS for the string STR. % The field is detected if only the first part of the fieldname % matches the string STR. The search is case insensitive. % If the field is detected, then OK=1 and A is the fieldvalue. % Otherwise OK=0 and A=DEFAULT l=size(str,2); j=min(find(strncmpi(str,fopts,l))); if ~isempty(j) a=getfield(options,char(fopts(j,:))); ok=1; if nargin == 5, a = boolean(a,[default,gamma]); elseif nargin == 6, a = boolean(a,[default,gamma],stri); end elseif nargin>3 a=default; ok=0; else a=[]; ok=0; end return %%%====================================================================== function n=CheckMatrix(A,gamma) if ischar(A), n=-1; if exist(A) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',A); errordlg(msg,'MATRIX'),n=-2; end if n==-1 & gamma, eval('n=feval(A,[],''dimension'');','n=-1;'), end else, [n,n] = size(A); if any(size(A) ~= n) msg=sprintf(' The operator must be a square matrix or a string. '); errordlg(msg,'MATRIX'),n=-3; end end return %------------------------------------------------------------------------ function [Av,Bv,n]=CheckDimMV(v) % [Av,Bv]=CheckDimMV(v) % Av=A*v, Bv=B*v Checks correctness operator definitions global Operator_Form Operator_MVs Operator_A Operator_B Operator_Params [n,k]=size(v); if k>1, V=v(:,2:k); v=v(:,1); end Bv=v; switch Operator_Form case 1 % both Operator_A and B are strings Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=feval(Operator_B,Operator_Params{:}); case 2 %%% or Operator_Form=3 or Operator_Form=5??? Operator_Params{1}=v; eval('[Av,Bv]=feval(Operator_A,Operator_Params{:});','Operator_Form=3;') if Operator_Form==3, ok=1; Operator_Params{2}='A'; eval('Av=feval(Operator_A,Operator_Params{:});','ok=0;') if ok, Operator_Params{2}='B'; eval('Bv=feval(Operator_A,Operator_Params{:});','ok=0;'), end if ~ok, Operator_Form=5; Operator_Params{2}=''; Av=feval(Operator_A,Operator_Params{:}); end end case 3 Operator_Params{1}=v; Operator_Params{2}='A'; Av=feval(Operator_A,Operator_Params{:}); Operator_Params{2}='B'; Bv=feval(Operator_A,Operator_Params{:}); case 4 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); Bv=Operator_B*v; case 5 Operator_Params{1}=v; Av=feval(Operator_A,Operator_Params{:}); case 6 Av=Operator_A*v; Operator_Params{1}=v; Bv=feval(Operator_B,Operator_Params{:}); case 7 Av=Operator_A*v; Bv=Operator_B*v; case 8 Av=Operator_A*v; end Operator_MVs = 1; ok_A=min(size(Av)==size(v)); ok_B=min(size(Bv)==size(v)); if ok_A & ok_B if k>1, ok=1; eval('[AV,BV]=MV(V);','ok=0;') if ok Av=[Av,AV]; Bv=[Bv,BV]; else for j=2:k, [Av(:,j),Bv(:,j)]=MV(V(:,j-1)); end end end return end if ~ok_A Operator=Operator_A; elseif ~ok_B Operator=Operator_B; end msg=sprintf(' %s does not produce a vector of size %d',Operator,n) errordlg(msg,'MATRIX'), n=-1; return %------------------------------------------------------------------------ function n=SetPrecond(n,TP) % finds out how the preconditioners are defined (Precond_Form) % and checks consistency of the definitions. % % If M is the preconditioner then P*M=L*U. Defaults: L=U=P=I. % % Precond_Form % 0: no L % 1: L M-file, no U, L ~= A % 2: L M-file, no U, L == A % 3: L M-file, U M-file, L ~= A, U ~= A, L ~=U % 4: L M-file, U M-file, L == U % 5: L matrix, no U % 6: L matrix, U matrix no P % 7: L matrix, U matrix, P matrix % % Precond_Type % 0: Explicit left % 1: Explicit right % 2: Implicit % global Operator_A ... Precond_Form Precond_Solves ... Precond_Type ... Precond_L Precond_U Precond_P Precond_Params Precond_Type = 0; if ischar(TP) TP=lower(TP(1,1)); switch TP case 'l' Precond_Type = 0; case 'r' Precond_Type = 1; case 'i' Precond_Type = 2; end else Precond_Type=max(0,min(fix(TP),2)); end Precond_Solves = 0; % Set type preconditioner Precond_Form=0; if isempty(Precond_L), return, end if ~isempty(Precond_U) & ischar(Precond_L)~=ischar(Precond_U) msg=sprintf(' L and U should both be strings or matrices'); errordlg(msg,'PRECONDITIONER'), n=-1; return end if ~isempty(Precond_P) & (ischar(Precond_P) | ischar(Precond_L)) msg=sprintf(' P can be specified only if P, L and U are matrices'); errordlg(msg,'PRECONDITIONER'), n=-1; return end tp=1+4*~ischar(Precond_L)+2*~isempty(Precond_U)+~isempty(Precond_P); if tp==1, tp = tp + strcmp(Precond_L,Operator_A); end if tp==3, tp = tp + strcmp(Precond_L,Precond_U); end if tp==3 & strcmp(Precond_U,Operator_A) msg=sprintf(' If L and A use the same M-file,') msg=[msg,sprintf('\n then so should U.')]; errordlg(msg,'PRECONDITIONER'), n=-1; return end if tp>5, tp=tp-1; end, Precond_Form=tp; % Check consistency definitions if tp<5 & exist(Precond_L) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',Precond_L); errordlg(msg,'PRECONDITIONER'), n=-1; return end ok=1; if tp == 2 Precond_Params{1}=zeros(n,1); Precond_Params{2}='preconditioner'; eval('v=feval(Operator_A,Precond_Params{:});','ok=0;') if ~ok msg='Preconditioner and matrix use the same M-file'; msg=[msg,sprintf(' ''%s.m'' \n',Precond_L)]; msg=[msg,'Therefore the preconditioner is called as']; msg=[msg,sprintf('\n\n\tw=%s(v,''preconditioner'')\n\n',Precond_L)]; msg=[msg,sprintf('Put this "switch" in ''%s.m''.',Precond_L)]; end end if tp == 4 | ~ok ok1=1; Precond_Params{1}=zeros(n,1); Precond_Params{2}='L'; eval('v=feval(Precond_L,Precond_Params{:});','ok1=0;') Precond_Params{2}='U'; eval('v=feval(Precond_L,Precond_Params{:});','ok1=0;') if ok1 Precond_Form = 4; Precond_U = Precond_L; ok=1; else if tp == 4 msg='L and U use the same M-file'; msg=[msg,sprintf(' ''%s.m'' \n',Precond_L)]; msg=[msg,'Therefore L and U are called']; msg=[msg,sprintf(' as\n\n\tw=%s(v,''L'')',Precond_L)]; msg=[msg,sprintf(' \n\tw=%s(v,''U'')\n\n',Precond_L)]; msg=[msg,sprintf('Check the dimensions and/or\n')]; msg=[msg,sprintf('put this "switch" in ''%s.m''.',Precond_L)]; end errordlg(msg,'PRECONDITIONER'), n=-1; return end end if tp==1 | tp==3 Precond_Params{1}=zeros(n,1); Precond_Params{2}=''; eval('v=feval(Precond_L,Precond_Params{:});','ok=0') if ~ok msg=sprintf('''%s'' should produce %i-vectors',Precond_L,n); errordlg(msg,'PRECONDITIONER'), n=-1; return end end if tp==3 if exist(Precond_U) ~=2 msg=sprintf(' Can not find the M-file ''%s.m'' ',Precond_U); errordlg(msg,'PRECONDITIONER'), n=-1; return else Precond_Params{1}=zeros(n,1); Precond_Params{2}=''; eval('v=feval(Precond_U,Precond_Params{:});','ok=0') if ~ok msg=sprintf('''%s'' should produce %i-vectors',Precond_U,n); errordlg(msg,'PRECONDITIONER'), n=-1; return end end end if tp==5 if min([n,2*n]==size(Precond_L)) Precond_U=Precond_L(:,n+1:2*n); Precond_L=Precond_L(:,1:n); Precond_Form=6; elseif min([n,3*n]==size(Precond_L)) Precond_U=Precond_L(:,n+1:2*n); Precond_P=Precond_L(:,2*n+1:3*n); Precond_L=Precond_L(:,1:n); Precond_Form=7; elseif ~min([n,n]==size(Precond_L)) msg=sprintf('The preconditioning matrix\n'); msg2=sprintf('should be %iX%i or %ix%i ([L,U])\n',n,n,n,2*n); msg3=sprintf('or %ix%i ([L,U,P])\n',n,3*n); errordlg([msg,msg2,msg3],'PRECONDITIONER'), n=-1; return end end if tp==6 & ~min([n,n]==size(Precond_L) & [n,n]==size(Precond_U)) msg=sprintf('Both L and U should be %iX%i.',n,n); n=-1; errordlg(msg,'PRECONDITIONER'), n=-1; return end if tp==7 & ~min([n,n]==size(Precond_L) & ... [n,n]==size(Precond_U) & [n,n]==size(Precond_P)) msg=sprintf('L, U, and P should all be %iX%i.',n,n); n=-1; errordlg(msg,'PRECONDITIONER'), n=-1; return end return %%%====================================================================== %%%========= DISPLAY FUNCTIONS =========================================== %%%====================================================================== function Result(Sigm,Target,S,T,tol) if nargin == 1 fprintf('\n\n %20s\n','Eigenvalues') for j=1:size(Sigm,1), fprintf('%2i %s\n',j,mydisp(Sigm(j,:),5)) end return end fprintf('\n\n%17s %25s%18s\n','Targets','Eigenvalues','RelErr/Cond') for j=1:size(S,1), l=Target(j,1); s=S(j,:); t=T(j,:); lm=mydisp(s/t,5); if l>0 fprintf('%2i %8s ''%s'' %9s %23s',j,'',Sigm(l,:),'',lm) else fprintf('%2i %23s %23s',j,mydisp(Target(j,2:3),5),lm) end re=1-tol/abs(t); if re>0, re=(1+tol/abs(s))/re; re=min(re-1,1); else, re=1; end if re>0.999, fprintf(' 1\n'), else, fprintf(' %5.0e\n',re), end end return %------------------------------------------------------------------------ function s=mydisp(lambda,d) if nargin <2, d=4; end if size(lambda,2)==2, if lambda(:,2)==0, s='Inf'; return, end lambda=lambda(:,1)/lambda(:,2); end a=real(lambda); b=imag(lambda); if max(a,b)==inf, s='Inf'; return, end e=0; if abs(a)>0; e= floor(log10(abs(a))); end if abs(b)>0; e= max(e,floor(log10(abs(b)))); end p=10^d; q=p/(10^e); a=round(a*q)/p; b=round(b*q)/p; st=['%',num2str(d+2),'.',num2str(d),'f']; ab=abs(b)==0; if ab, str=[''' ']; else, str=['''(']; end if a>=0, str=[str,'+']; a=abs(a); end, str=[str,st]; if ab, str=[str,'e']; else if b>=0, str=[str,'+']; b=abs(b); end, str=[str,st,'i)e']; end if e>=0, str=[str,'+']; else, str=[str,'-']; e=-e; end if e<10, str=[str,'0%i''']; else, str=[str,'%i''']; end if ab, s=eval(sprintf(str,a,e)); else, s=eval(sprintf(str,a,b,e)); end return %%%====================================================================== function ShowEig(theta,target,k) if ischar(target) fprintf('\n target=''%s'', ',target) else fprintf('\n target=%s, ',mydisp(target,5)) end fprintf('lambda_%i=%s\n',k,mydisp(theta,5)); return %%%====================================================================== function texttest(s,nr,gamma) if nargin<3, gamma=100*eps; end if nr > gamma % if nr>100*eps fprintf('\n %35s is: %9.3g\t',s,nr) end return %%%======================================================================
github
umariqb/3D_Pose_Estimation_CVPR2016-master
lnst.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/lnst.m
891
utf_8
93ca6136f90181897631256d58517558
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function lnst(hs,he) ls=get(he,'value'); switch ls case 1 set(hs,'LineStyle','-','marker','x','color','b'); case 2 set(hs,'LineStyle','-','marker','o','color','r'); case 3 set(hs,'LineStyle','none','marker','o','color','b'); case 4 set(hs,'LineStyle','-','marker','none','color','g'); case 5 set(hs,'LineStyle','--','marker','d','color','b'); end drawnow;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
scatter12n.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/scatter12n.m
1,348
utf_8
65c091a54cbbe59f0a7ddef27fcc2c3f
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function scatter12n(name,data,labels) ld=length(data(1,:)); if ld==2 hf=figure; set(hf,'name',name,'NumberTitle','off'); %if handles.islb scatter(data(:,1),data(:,2),5,labels); % else % scatter(data(:,1),data(:,2),5); % end title(name); else if ld==1 hf=figure; set(hf,'name',name,'NumberTitle','off'); %if handles.islb scatter(data(:,1),zeros(length(data(:,1)),1),5,labels); % else % scatter(data(:,1),zeros(length(data(:,1)),1),5); % end title(name); else %if handles.islb scattern(name,data,labels); % else % scattern('Result of dimensionality reduction',data); % end end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
not_calculated.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/not_calculated.m
7,818
utf_8
07c7ebdd2ecb821df6d1b4ccd5f47662
function varargout = not_calculated(varargin) % NOT_CALCULATED M-file for not_calculated.fig % NOT_CALCULATED by itself, creates a new NOT_CALCULATED or raises the % existing singleton*. % % H = NOT_CALCULATED returns the handle to a new NOT_CALCULATED or the handle to % the existing singleton*. % % NOT_CALCULATED('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NOT_CALCULATED.M with the given input arguments. % % NOT_CALCULATED('Property','Value',...) creates a new NOT_CALCULATED or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before not_calculated_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to not_calculated_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help not_calculated % Last Modified by GUIDE v2.5 30-Jul-2008 11:02:27 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @not_calculated_OpeningFcn, ... 'gui_OutputFcn', @not_calculated_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before not_calculated is made visible. function not_calculated_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to not_calculated (see VARARGIN) % Choose default command line output for not_calculated handles.output = 'Yes'; % Update handles structure guidata(hObject, handles); % Insert custom Title and Text if specified by the user % Hint: when choosing keywords, be sure they are not easily confused % with existing figure properties. See the output of set(figure) for % a list of figure properties. if(nargin > 3) for index = 1:2:(nargin-3), if nargin-3==index, break, end switch lower(varargin{index}) case 'title' set(hObject, 'Name', varargin{index+1}); case 'string' set(handles.text1, 'String', varargin{index+1}); end end end % Determine the position of the dialog - centered on the callback figure % if available, else, centered on the screen FigPos=get(0,'DefaultFigurePosition'); OldUnits = get(hObject, 'Units'); set(hObject, 'Units', 'pixels'); OldPos = get(hObject,'Position'); FigWidth = OldPos(3); FigHeight = OldPos(4); if isempty(gcbf) ScreenUnits=get(0,'Units'); set(0,'Units','pixels'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',ScreenUnits); FigPos(1)=1/2*(ScreenSize(3)-FigWidth); FigPos(2)=2/3*(ScreenSize(4)-FigHeight); else GCBFOldUnits = get(gcbf,'Units'); set(gcbf,'Units','pixels'); GCBFPos = get(gcbf,'Position'); set(gcbf,'Units',GCBFOldUnits); FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ... (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2]; end FigPos(3:4)=[FigWidth FigHeight]; set(hObject, 'Position', FigPos); set(hObject, 'Units', OldUnits); % Show a question icon from dialogicons.mat - variables questIconData % and questIconMap load dialogicons.mat IconData=questIconData; questIconMap(256,:) = get(handles.figure1, 'Color'); IconCMap=questIconMap; Img=image(IconData, 'Parent', handles.axes1); set(handles.figure1, 'Colormap', IconCMap); set(handles.axes1, ... 'Visible', 'off', ... 'YDir' , 'reverse' , ... 'XLim' , get(Img,'XData'), ... 'YLim' , get(Img,'YData') ... ); % Make the GUI modal set(handles.figure1,'WindowStyle','modal') % UIWAIT makes not_calculated wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = not_calculated_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % The figure can be deleted now delete(handles.figure1); % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on key press over figure1 with no controls selected. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check for "enter" or "escape" if isequal(get(hObject,'CurrentKey'),'escape') % User said no by hitting escape handles.output = 'No'; % Update handles structure guidata(hObject, handles); uiresume(handles.figure1); end if isequal(get(hObject,'CurrentKey'),'return') uiresume(handles.figure1); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
choose_method.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/choose_method.m
5,483
utf_8
7fcb2ff0eb7f662fc75d652d9c440d65
function varargout = choose_method(varargin) % CHOOSE_METHOD M-file for choose_method.fig % CHOOSE_METHOD, by itself, creates a new CHOOSE_METHOD or raises the existing % singleton*. % % H = CHOOSE_METHOD returns the handle to a new CHOOSE_METHOD or the handle to % the existing singleton*. % % CHOOSE_METHOD('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CHOOSE_METHOD.M with the given input arguments. % % CHOOSE_METHOD('Property','Value',...) creates a new CHOOSE_METHOD or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before choose_method_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to choose_method_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help choose_method % Last Modified by GUIDE v2.5 25-Jul-2008 10:40:42 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @choose_method_OpeningFcn, ... 'gui_OutputFcn', @choose_method_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before choose_method is made visible. function choose_method_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to choose_method (see VARARGIN) % Choose default command line output for choose_method handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes choose_method wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = choose_method_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in listbox1. function listbox1_Callback(hObject, eventdata, handles) vl=get(hObject,'Value'); switch vl case 1 str='CorrDim'; case 2 str='NearNbDim'; case 3 str='GMST'; case 4 str='PackingNumbers'; case 5 str='EigValue'; case 6 str='MLE'; end set(handles.str,'string',str); drawnow; % --- Executes during object creation, after setting all properties. function listbox1_CreateFcn(hObject, eventdata, handles) % hObject handle to listbox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_Callback(hObject, eventdata, handles) % hObject handle to str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str as text % str2double(get(hObject,'String')) returns contents of str as a double % --- Executes during object creation, after setting all properties. function str_CreateFcn(hObject, eventdata, handles) % hObject handle to str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
load_data_1_var.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/load_data_1_var.m
4,902
utf_8
5b70e8dd70f9e4386ea769372ed55ffe
function varargout = load_data_1_var(varargin) % LOAD_DATA_1_VAR M-file for load_data_1_var.fig % LOAD_DATA_1_VAR, by itself, creates a new LOAD_DATA_1_VAR or raises the existing % singleton*. % % H = LOAD_DATA_1_VAR returns the handle to a new LOAD_DATA_1_VAR or the handle to % the existing singleton*. % % LOAD_DATA_1_VAR('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_DATA_1_VAR.M with the given input arguments. % % LOAD_DATA_1_VAR('Property','Value',...) creates a new LOAD_DATA_1_VAR or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_data_1_var_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_data_1_var_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_data_1_var % Last Modified by GUIDE v2.5 23-Jul-2008 17:31:19 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_data_1_var_OpeningFcn, ... 'gui_OutputFcn', @load_data_1_var_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_data_1_var is made visible. function load_data_1_var_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_data_1_var (see VARARGIN) % Choose default command line output for load_data_1_var handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes load_data_1_var wait for user response (see UIRESUME) uiwait(handles.figure1); % uiwait; % --- Outputs from this function are returned to the command line. function varargout = load_data_1_var_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function cn_Callback(hObject, eventdata, handles) % hObject handle to cn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of cn as text % str2double(get(hObject,'String')) returns contents of cn as a double % --- Executes during object creation, after setting all properties. function cn_CreateFcn(hObject, eventdata, handles) % hObject handle to cn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % -------------------------------------------------------------------- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.i,'value') set(handles.cn,'Enable','on'); set(handles.cnt,'ForegroundColor',[0 0 0]); else set(handles.cn,'Enable','off'); set(handles.cnt,'ForegroundColor',[0.4 0.4 0.4]); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
plotn.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/plotn.m
4,103
utf_8
e9c0840dca614923d10952e9b37f06c5
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function plotn(name,data) % plot if dimensionality>=3 % format: plotn(name,data) % name - text that will be dispayed as name of figure % data - multidimentional data, row - is one datapoint bgc=[0.8313725490196079 0.8156862745098039 0.7843137254901961]; bgc1=[1 1 1]; bgc1=bgc; % if length(varargin)==1 % labels=varargin{1}; % islb=true; % else islb=false; % end hf=figure; set(hf,'name',name,'NumberTitle','off'); set(hf,'units','normalized'); set(hf,'position',[0.1 0.1 0.7 0.75]); set(hf,'color',bgc); ha=axes; set(ha,'units','normalized'); set(ha,'position',[0.1 0.1 0.8 0.7]); % if islb % hs=scatter3(data(:,1),data(:,2),data(:,3),5,labels,'parent',ha); % else hs=plot3(data(:,1),data(:,2),data(:,3),'x-','parent',ha); % end set(hs,'UserData',data); % memorize data in userdata of plot % title as text contol: xc=0.5; yc=0.94; dx=0.8; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', name,... 'units','normalized',... 'fontunits','normalized',... 'HorizontalAlignment','center',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % dimensionality text xc=0.5; yc=0.9; dx=0.2; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', ['dimensionality=' num2str(length(data(1,:)))],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % edits: xc=0.5; yc=0.86; dy=0.04; dytx=0.03; x0=0.03; dxg=0.03; xt=x0; for cc=1:3 switch cc case 1 ls='X'; case 2 ls='Y'; case 3 ls='Z'; end dx1=0.07; uicontrol('Style', 'text',... 'parent',hf,... 'String', [ls ' ' 'data:'],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; dx1=0.07; he=uicontrol('Style', 'edit',... 'parent',hf,... 'String', num2str(cc),... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dy/2 dx1 dy],... 'backgroundcolor',[1 1 1]); set(he,'callback',['ded(' num2str(cc) ',' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']); xt=xt+dx1+0.005; dx1=0.065; uicontrol('Style', 'text',... 'parent',hf,... 'String', 'column',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; xt=xt+dxg; end dx1=0.1; uicontrol('Style', 'text',... 'parent',hf,... 'String', 'line style:',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; dx1=0.07; he=uicontrol('Style', 'popupmenu',... 'parent',hf,... 'String', '1|2|3|4|5',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dy/2 dx1 dy],... 'backgroundcolor',[1 1 1]); set(he,'callback',['lnst(' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']); xlabel(ha,'X'); ylabel(ha,'Y'); zlabel(ha,'Z'); set(hf,'Toolbar','figure');
github
umariqb/3D_Pose_Estimation_CVPR2016-master
scattern.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/scattern.m
3,651
utf_8
bf506a19215a7e0b4cb62da12fa09d16
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function scattern(name,data,varargin) % scatter plot if dimensionality>=3 % format: scattern(name,data) % name - text that will be dispayed as name of figure % data - multidimentional data, row - is one datapoint % scattern(name,data,labels) - if labels spacified, used for color of points bgc=[0.8313725490196079 0.8156862745098039 0.7843137254901961]; bgc1=[1 1 1]; bgc1=bgc; if length(varargin)==1 labels=varargin{1}; islb=true; else islb=false; end hf=figure; set(hf,'name',name,'NumberTitle','off'); set(hf,'units','normalized'); set(hf,'position',[0.1 0.1 0.7 0.75]); set(hf,'color',bgc); ha=axes; set(ha,'units','normalized'); set(ha,'position',[0.1 0.1 0.8 0.7]); if islb && size(data, 1) == numel(labels) hs=scatter3(data(:,1),data(:,2),data(:,3),5,labels,'parent',ha); else hs=scatter3(data(:,1),data(:,2),data(:,3),5,'parent',ha); end if size(data, 1) ~= numel(labels) warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.'); end set(hs,'UserData',data); % memorize data in userdata of plot % title as text contol: xc=0.5; yc=0.94; dx=0.8; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', name,... 'units','normalized',... 'fontunits','normalized',... 'HorizontalAlignment','center',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % dimensionality text xc=0.5; yc=0.9; dx=0.2; dy=0.04; uicontrol('Style', 'text',... 'parent',hf,... 'String', ['dimensionality=' num2str(length(data(1,:)))],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xc-dx/2 yc dx dy],... 'backgroundcolor',bgc1); % edits: xc=0.5; yc=0.86; dy=0.04; dytx=0.03; x0=0.12; dxg=0.05; xt=x0; for cc=1:3 switch cc case 1 ls='X'; case 2 ls='Y'; case 3 ls='Z'; end dx1=0.07; uicontrol('Style', 'text',... 'parent',hf,... 'String', [ls ' ' 'data:'],... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; dx1=0.07; he=uicontrol('Style', 'edit',... 'parent',hf,... 'String', num2str(cc),... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dy/2 dx1 dy],... 'backgroundcolor',[1 1 1]); set(he,'callback',['ded(' num2str(cc) ',' num2str(hs,'%20.20f') ',' num2str(he,'%20.20f') ')']); xt=xt+dx1+0.005; dx1=0.065; uicontrol('Style', 'text',... 'parent',hf,... 'String', 'column',... 'units','normalized',... 'fontunits','normalized',... 'Position', [xt yc-dytx/2 dx1 dytx],... 'backgroundcolor',bgc1); xt=xt+dx1+0.005; xt=xt+dxg; end xlabel(ha,'X'); ylabel(ha,'Y'); zlabel(ha,'Z'); set(hf,'Toolbar','figure');
github
umariqb/3D_Pose_Estimation_CVPR2016-master
no_history.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/no_history.m
7,508
utf_8
d5c85b897eeca97b3e37ea41551de2b1
function varargout = no_history(varargin) % NO_HISTORY M-file for no_history.fig % NO_HISTORY by itself, creates a new NO_HISTORY or raises the % existing singleton*. % % H = NO_HISTORY returns the handle to a new NO_HISTORY or the handle to % the existing singleton*. % % NO_HISTORY('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NO_HISTORY.M with the given input arguments. % % NO_HISTORY('Property','Value',...) creates a new NO_HISTORY or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before no_history_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to no_history_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help no_history % Last Modified by GUIDE v2.5 16-Sep-2008 15:57:20 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @no_history_OpeningFcn, ... 'gui_OutputFcn', @no_history_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before no_history is made visible. function no_history_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to no_history (see VARARGIN) % Choose default command line output for no_history handles.output = 'Yes'; % Update handles structure guidata(hObject, handles); % Insert custom Title and Text if specified by the user % Hint: when choosing keywords, be sure they are not easily confused % with existing figure properties. See the output of set(figure) for % a list of figure properties. if(nargin > 3) for index = 1:2:(nargin-3), if nargin-3==index, break, end switch lower(varargin{index}) case 'title' set(hObject, 'Name', varargin{index+1}); case 'string' set(handles.text1, 'String', varargin{index+1}); end end end % Determine the position of the dialog - centered on the callback figure % if available, else, centered on the screen FigPos=get(0,'DefaultFigurePosition'); OldUnits = get(hObject, 'Units'); set(hObject, 'Units', 'pixels'); OldPos = get(hObject,'Position'); FigWidth = OldPos(3); FigHeight = OldPos(4); if isempty(gcbf) ScreenUnits=get(0,'Units'); set(0,'Units','pixels'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',ScreenUnits); FigPos(1)=1/2*(ScreenSize(3)-FigWidth); FigPos(2)=2/3*(ScreenSize(4)-FigHeight); else GCBFOldUnits = get(gcbf,'Units'); set(gcbf,'Units','pixels'); GCBFPos = get(gcbf,'Position'); set(gcbf,'Units',GCBFOldUnits); FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ... (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2]; end FigPos(3:4)=[FigWidth FigHeight]; set(hObject, 'Position', FigPos); set(hObject, 'Units', OldUnits); % Show a question icon from dialogicons.mat - variables questIconData % and questIconMap load dialogicons.mat IconData=questIconData; questIconMap(256,:) = get(handles.figure1, 'Color'); IconCMap=questIconMap; Img=image(IconData, 'Parent', handles.axes1); set(handles.figure1, 'Colormap', IconCMap); set(handles.axes1, ... 'Visible', 'off', ... 'YDir' , 'reverse' , ... 'XLim' , get(Img,'XData'), ... 'YLim' , get(Img,'YData') ... ); % Make the GUI modal set(handles.figure1,'WindowStyle','modal') % UIWAIT makes no_history wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = no_history_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % The figure can be deleted now delete(handles.figure1); % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on key press over figure1 with no controls selected. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check for "enter" or "escape" if isequal(get(hObject,'CurrentKey'),'escape') % User said no by hitting escape handles.output = 'No'; % Update handles structure guidata(hObject, handles); uiresume(handles.figure1); end if isequal(get(hObject,'CurrentKey'),'return') uiresume(handles.figure1); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
load_data_vars.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/load_data_vars.m
7,943
utf_8
3e892de48b2b883da0e7121eb6b7cfbc
function varargout = load_data_vars(varargin) % LOAD_DATA_VARS M-file for load_data_vars.fig % LOAD_DATA_VARS, by itself, creates a new LOAD_DATA_VARS or raises the existing % singleton*. % % H = LOAD_DATA_VARS returns the handle to a new LOAD_DATA_VARS or the handle to % the existing singleton*. % % LOAD_DATA_VARS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_DATA_VARS.M with the given input arguments. % % LOAD_DATA_VARS('Property','Value',...) creates a new LOAD_DATA_VARS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_data_vars_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_data_vars_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_data_vars % Last Modified by GUIDE v2.5 23-Jul-2008 18:19:22 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_data_vars_OpeningFcn, ... 'gui_OutputFcn', @load_data_vars_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_data_vars is made visible. function load_data_vars_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_data_vars (see VARARGIN) % Choose default command line output for load_data_vars handles.output = hObject; % Update handles structure guidata(hObject, handles); vn=varargin{1}; % variable names str=''; for vnc=1:length(vn) str=[str vn{vnc}]; if vnc~=length(vn) str=[str ' ']; end end set(handles.lv,'string',str); set(handles.d,'string',vn{1}); set(handles.ivn,'string',vn{2}); % UIWAIT makes load_data_vars wait for user response (see UIRESUME) uiwait(handles.figure1); %uiwait; % --- Outputs from this function are returned to the command line. function varargout = load_data_vars_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function lv_Callback(hObject, eventdata, handles) % hObject handle to lv (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of lv as text % str2double(get(hObject,'String')) returns contents of lv as a double % --- Executes during object creation, after setting all properties. function lv_CreateFcn(hObject, eventdata, handles) % hObject handle to lv (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function d_Callback(hObject, eventdata, handles) % hObject handle to d (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of d as text % str2double(get(hObject,'String')) returns contents of d as a double % --- Executes during object creation, after setting all properties. function d_CreateFcn(hObject, eventdata, handles) % hObject handle to d (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ivn_Callback(hObject, eventdata, handles) % hObject handle to ivn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ivn as text % str2double(get(hObject,'String')) returns contents of ivn as a double % --- Executes during object creation, after setting all properties. function ivn_CreateFcn(hObject, eventdata, handles) % hObject handle to ivn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function icn_Callback(hObject, eventdata, handles) % hObject handle to icn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of icn as text % str2double(get(hObject,'String')) returns contents of icn as a double % --- Executes during object creation, after setting all properties. function icn_CreateFcn(hObject, eventdata, handles) % hObject handle to icn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % -------------------------------------------------------------------- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.iv,'value') set(handles.ivn,'Enable','on'); else set(handles.ivn,'Enable','off'); end if get(handles.ic,'value') set(handles.icn,'Enable','on'); else set(handles.icn,'Enable','off'); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
mapping_parameters.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/mapping_parameters.m
24,066
utf_8
ddb259e8821b5440a07fc05910595864
function varargout = mapping_parameters(varargin) % MAPPING_PARAMETERS M-file for mapping_parameters.fig % MAPPING_PARAMETERS, by itself, creates a new MAPPING_PARAMETERS or raises the existing % singleton*. % % H = MAPPING_PARAMETERS returns the handle to a new MAPPING_PARAMETERS or the handle to % the existing singleton*. % % MAPPING_PARAMETERS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MAPPING_PARAMETERS.M with the given input arguments. % % MAPPING_PARAMETERS('Property','Value',...) creates a new MAPPING_PARAMETERS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before mapping_parameters_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to mapping_parameters_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Last Modified by GUIDE v2.5 28-Jul-2008 16:23:20 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @mapping_parameters_OpeningFcn, ... 'gui_OutputFcn', @mapping_parameters_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before mapping_parameters is made visible. function mapping_parameters_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to mapping_parameters (see VARARGIN) % Choose default command line output for mapping_parameters handles.output = hObject; no_dims=varargin{1}; handles.islb=varargin{2}; if length(no_dims)~=0 set(handles.nd,'string',num2str(round(no_dims))); else set(handles.nd,'string','2'); end case1; % case one is default for start % Update handles structure guidata(hObject, handles); % handles % UIWAIT makes mapping_parameters wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = mapping_parameters_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in listbox1. function listbox1_Callback(hObject, eventdata, handles) % figure1: 218.0023 % sm: 240.0021 % na: 239.0021 % nat: 238.0021 % uipanel_tp: 235.0021 % prp: 234.0021 % prpt: 233.0021 % kpd: 232.0021 % kpdt: 231.0021 % kpR: 230.0021 % kpRt: 229.0021 % kgs: 228.0021 % kgst: 227.0021 % uipanel_k: 223.0022 % uipanel_ft: 220.0022 % sig: 53.0027 % sigt: 52.0027 % uipanel_ei: 49.0027 % prc: 48.0027 % prct: 47.0027 % k: 46.0028 % kt: 45.0028 % mi: 44.0028 % mit: 43.0029 % nd: 42.0029 % text3: 41.0034 % wl: 40.0029 % text1: 39.0033 % listbox1: 219.0023 % tl: 237.0021 % tg: 236.0021 % kp: 226.0022 % kg: 225.0022 % kl: 224.0022 % ftn: 222.0022 % fty: 221.0022 % eij: 51.0027 % eim: 50.0027 % output: 218.0023 % islb: % PCA % LDA % MDS % SimplePCA % ProbPCA % FactorAnalysis % Isomap % LandmarkIsomap % LLE % Laplacian % HessianLLE % LTSA % MVU % CCA % LandmarkMVU % FastMVU % DiffusionMaps % KernelPCA % GDA % SNE % SymSNE % t-SNE % LPP % NPE % LLTSA % SPE % Autoencoder % LLC % ManifoldChart % CFA % GPLVM switch get(hObject,'Value') case 1 % PCA % no parameters; case1; case 2 % LDA % no parameters; case1; if handles.islb set(handles.wl,'visible','off'); set(handles.sm,'Enable','on'); else set(handles.wl,'visible','on'); set(handles.sm,'Enable','off'); end case 3 % MDS % no parameters; case1; case 4 % SimplePCA % no parameters; case1; case 5 % ProbPCA case1; % hide all contols first set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); case 6 % FactorAnalysis % no parameters; case1; case 7 % Isomap case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; case 8 % LandmarkIsomap case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.prc,'Visible','on'); set(handles.prct,'Visible','on'); case 9 % LLE case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 10 % Laplacian case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 11 % HessianLLE case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 12 % LTSA case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 13 % MVU case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 14 % CCA case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 15 % LandmarkMVU case1; % hide all contols first set(handles.k,'Visible','on','string',5); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; case 16 % FastMVU case1; % hide all contols first set(handles.k,'Visible','on','string',5); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); set(handles.uipanel_ft,'Visible','on'); case 17 % DiffusionMaps case1; % hide all contols first set(handles.t,'Visible','on'); set(handles.tt,'Visible','on'); set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); case 18 % KernelPCA case1; % hide all contols first set(handles.uipanel_k,'Visible','on'); update_kernel_uipanel; case 19 % GDA case1; % hide all contols first if handles.islb set(handles.wl,'visible','off'); set(handles.sm,'Enable','on'); set(handles.uipanel_k,'Visible','on'); update_kernel_uipanel; else set(handles.wl,'visible','on'); set(handles.sm,'Enable','off'); end case 20 % SNE case1; % hide all contols first set(handles.prp,'Visible','on'); set(handles.prpt,'Visible','on'); case 21 % SymSNE case1; % hide all contols first set(handles.prp,'Visible','on'); set(handles.prpt,'Visible','on'); case 22 % t-SNE case1; % hide all contols first set(handles.prp,'Visible','on'); set(handles.prpt,'Visible','on'); case 23 % LPP case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 24 % NPE case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 25 % LLTSA case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.uipanel_ei,'Visible','on'); case 26 % SPE case1; % hide all contols first set(handles.uipanel_tp,'Visible','on'); update_type_uipanel; set(handles.k,'Enable','on'); adaptive_callback; case 27 % Autoencoder % no parameters; case1; case 28 % LLC case1; % hide all contols first set(handles.k,'Visible','on','string',12); set(handles.kt,'Visible','on'); set(handles.ka,'Visible','on'); adaptive_callback; set(handles.na,'Visible','on'); set(handles.nat,'Visible','on'); set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 29 % ManifoldChart case1; % hide all contols first set(handles.na,'Visible','on'); set(handles.nat,'Visible','on'); set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); set(handles.uipanel_ei,'Visible','on'); case 30 % CFA case1; % hide all contols first set(handles.na,'Visible','on'); set(handles.nat,'Visible','on'); set(handles.mi,'Visible','on'); set(handles.mit,'Visible','on'); case 31 % GPLVM case1; % hide all contols first set(handles.sig,'Visible','on'); set(handles.sigt,'Visible','on'); case 32 % NCA case1; case 33 % MCML case1; end % --- Executes during object creation, after setting all properties. function listbox1_CreateFcn(hObject, eventdata, handles) % hObject handle to listbox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nd_Callback(hObject, eventdata, handles) % hObject handle to nd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of nd as text % str2double(get(hObject,'String')) returns contents of nd as a double % --- Executes during object creation, after setting all properties. function nd_CreateFcn(hObject, eventdata, handles) % hObject handle to nd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function mi_Callback(hObject, eventdata, handles) % hObject handle to mi (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of mi as text % str2double(get(hObject,'String')) returns contents of mi as a double % --- Executes during object creation, after setting all properties. function mi_CreateFcn(hObject, eventdata, handles) % hObject handle to mi (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function k_Callback(hObject, eventdata, handles) % hObject handle to k (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of k as text % str2double(get(hObject,'String')) returns contents of k as a double % --- Executes during object creation, after setting all properties. function k_CreateFcn(hObject, eventdata, handles) % hObject handle to k (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function prc_Callback(hObject, eventdata, handles) % hObject handle to prc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of prc as text % str2double(get(hObject,'String')) returns contents of prc as a double % --- Executes during object creation, after setting all properties. function prc_CreateFcn(hObject, eventdata, handles) % hObject handle to prc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sig_Callback(hObject, eventdata, handles) % hObject handle to sig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sig as text % str2double(get(hObject,'String')) returns contents of sig as a double % --- Executes during object creation, after setting all properties. function sig_CreateFcn(hObject, eventdata, handles) % hObject handle to sig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kgs_Callback(hObject, eventdata, handles) % hObject handle to kgs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of kgs as text % str2double(get(hObject,'String')) returns contents of kgs as a double % --- Executes during object creation, after setting all properties. function kgs_CreateFcn(hObject, eventdata, handles) % hObject handle to kgs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kpR_Callback(hObject, eventdata, handles) % hObject handle to kpR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of kpR as text % str2double(get(hObject,'String')) returns contents of kpR as a double % --- Executes during object creation, after setting all properties. function kpR_CreateFcn(hObject, eventdata, handles) % hObject handle to kpR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kpd_Callback(hObject, eventdata, handles) % hObject handle to kpd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of kpd as text % str2double(get(hObject,'String')) returns contents of kpd as a double % --- Executes during object creation, after setting all properties. function kpd_CreateFcn(hObject, eventdata, handles) % hObject handle to kpd (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function prp_Callback(hObject, eventdata, handles) % hObject handle to prp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of prp as text % str2double(get(hObject,'String')) returns contents of prp as a double % --- Executes during object creation, after setting all properties. function prp_CreateFcn(hObject, eventdata, handles) % hObject handle to prp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function na_Callback(hObject, eventdata, handles) % hObject handle to na (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of na as text % str2double(get(hObject,'String')) returns contents of na as a double % --- Executes during object creation, after setting all properties. function na_CreateFcn(hObject, eventdata, handles) % hObject handle to na (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in sm. function sm_Callback(hObject, eventdata, handles) set(handles.sm,'Enable','off'); drawnow; uiresume(handles.figure1); function t_Callback(hObject, eventdata, handles) % hObject handle to t (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of t as text % str2double(get(hObject,'String')) returns contents of t as a double % --- Executes during object creation, after setting all properties. function t_CreateFcn(hObject, eventdata, handles) % hObject handle to t (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % -------------------------------------------------------------------- function uipanel_k_SelectionChangeFcn(hObject, eventdata, handles) update_kernel_uipanel; % -------------------------------------------------------------------- function uipanel_tp_SelectionChangeFcn(hObject, eventdata, handles) update_type_uipanel; % --- Executes on button press in ka. function ka_Callback(hObject, eventdata, handles) adaptive_callback;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
load_xls.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/load_xls.m
4,845
utf_8
98f040ec0685b024ddf99d454fea770d
function varargout = load_xls(varargin) % LOAD_XLS M-file for load_xls.fig % LOAD_XLS, by itself, creates a new LOAD_XLS or raises the existing % singleton*. % % H = LOAD_XLS returns the handle to a new LOAD_XLS or the handle to % the existing singleton*. % % LOAD_XLS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_XLS.M with the given input arguments. % % LOAD_XLS('Property','Value',...) creates a new LOAD_XLS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_xls_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_xls_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_xls % Last Modified by GUIDE v2.5 11-Sep-2008 10:53:04 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_xls_OpeningFcn, ... 'gui_OutputFcn', @load_xls_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_xls is made visible. function load_xls_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_xls (see VARARGIN) % Choose default command line output for load_xls handles.output = hObject; nmc=varargin{1}; % number of columns % Update handles structure guidata(hObject, handles); set(handles.noc,'string',num2str(nmc)); set(handles.col,'string',num2str(nmc)); cl=[0.4 0.4 0.4]; set(handles.coltxt,'ForegroundColor',cl); set(handles.col,'Enable','off'); % UIWAIT makes load_xls wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = load_xls_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function col_Callback(hObject, eventdata, handles) % hObject handle to col (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of col as text % str2double(get(hObject,'String')) returns contents of col as a double % --- Executes during object creation, after setting all properties. function col_CreateFcn(hObject, eventdata, handles) % hObject handle to col (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % --- Executes when selected object is changed in uipanel1. function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.uc,'value') cl=[0 0 0]; set(handles.coltxt,'ForegroundColor',cl); set(handles.col,'Enable','on'); else cl=[0.4 0.4 0.4]; set(handles.coltxt,'ForegroundColor',cl); set(handles.col,'Enable','off'); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
drtool.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/drtool.m
53,877
utf_8
25abf1c6522b90b00b1c29d7d4f4c091
function varargout = drtool(varargin) % DRTOOL M-file for drtool.fig % DRTOOL, by itself, creates a new DRTOOL or raises the existing % singleton*. % % H = DRTOOL returns the handle to a new DRTOOL or the handle to % the existing singleton*. % % DRTOOL('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DRTOOL.M with the given input arguments. % % DRTOOL('Property','Value',...) creates a new DRTOOL or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before drtool_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to drtool_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help drtool % Last Modified by GUIDE v2.5 16-Sep-2008 12:18:29 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @drtool_OpeningFcn, ... 'gui_OutputFcn', @drtool_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before drtool is made visible. function drtool_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to drtool (see VARARGIN) % Choose default command line output for drtool handles.output = hObject; set(handles.edr,'UserData',[]); % demention not estimated at begining % here data will be stored: handles.X=[]; handles.labels=[]; handles.islb=false; % if labels provided handles.isl=false; % if data loaded handles.mcd=false; % if mapping was calculated handles.mX=[]; % mapped X handles.m1={}; % m-code from part1 handles.m2={}; % m-code from part2 handles.m21={}; % addition with no_dims handles.m3={}; % m-code from part3 handles.a2=false; % if code part with no_dims was writed handles.mstf={}; % save to file part handles.isxls=[]; % if data loaded as xls-file (will be used before save history) %handles.ndr=[]; % rounded number of dimention from intrinsic_dim, need for m-file % Update handles structure guidata(hObject, handles); % UIWAIT makes drtool wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = drtool_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in ld. function ld_Callback(hObject, eventdata, handles) handles.a2=false; set(handles.ld,'Enable','off'); drawnow; % load data lead to clear mapped data handles.mcd=false; % if mapping was calculated handles.mX=[]; % mapped X set(handles.cd,'Visible','off'); try hs=load_data; catch set(handles.ld,'Enable','on'); return end hands_l_d=guidata(hs); if (~get(hands_l_d.file,'value'))&&(~get(hands_l_d.xls,'value')) %if not from file and not from xls-file handles.isxls=[]; set(hands_l_d.ok,'Enable','off'); drawnow; if get(hands_l_d.sw,'value') dataname='swiss'; end if get(hands_l_d.hl,'value') dataname='helix'; end if get(hands_l_d.tp,'value') dataname='twinpeaks'; end if get(hands_l_d.cl,'value') dataname='3d_clusters'; end if get(hands_l_d.is,'value') dataname='intersect'; end n=str2num(get(hands_l_d.ndp,'string')); noise=str2num(get(hands_l_d.nl,'string')); [X, labels] = generate_data(dataname, n,noise); handles.X=X; handles.labels=labels; handles.islb=true; handles.isl=true; set(handles.dld,'visible','on'); % m-file memorizing: % clear all previose history because new original dataset generated: handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; handles.m1={ '% generate data'; ['n = ' num2str(n) '; % number of datapoints' ]; ['noise = ' num2str(noise) '; % noise level' ]; ['[X, labels] = generate_data(''' dataname ''', n,noise); % generate ' dataname ' data']}; delete(hands_l_d.figure1); drawnow; else if get(hands_l_d.file,'value') % here if need to load data from file handles.isxls=false; delete(hands_l_d.figure1); drawnow; S = uiimport; if length(S)==0 handles.X=[]; handles.labels=[]; handles.islb=false; handles.isl=false; set(handles.dld,'visible','off'); handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; else vn=fieldnames(S); if length(vn)==1 X = getfield(S, vn{1}); hs1=load_data_1_var; hld1=guidata(hs1); if get(hld1.i,'value') cn=str2num(get(hld1.cn,'string')); lX=length(X(1,:)); ncn1=1:lX; ncni=find(ncn1~=cn); ncn=ncn1(ncni); handles.X=X(:,ncn); handles.isl=true; set(handles.dld,'visible','on'); labels=X(:,cn); handles.labels=labels; handles.islb=true; else % one variable without labels handles.X=X; handles.isl=true; set(handles.dld,'visible','on'); handles.labels=[]; handles.islb=false; end delete(hld1.figure1); else hss=load_data_vars(vn); hlds=guidata(hss); Xn=get(hlds.d,'string'); X = getfield(S, Xn); if get(hlds.ni,'value') % not include handles.labels=[]; handles.islb=false; handles.X=X; handles.isl=true; set(handles.dld,'visible','on'); end if get(hlds.iv,'value') % include from variable ivn=get(hlds.ivn,'String'); labels = getfield(S, ivn); handles.labels=labels; handles.islb=true; handles.X=X; handles.isl=true; set(handles.dld,'visible','on'); end if get(hlds.ic,'value') % include from column cn=str2num(get(hlds.icn,'String')); lX=length(X(1,:)); ncn1=1:lX; ncni=find(ncn1~=cn); ncn=ncn1(ncni); handles.X=X(:,ncn); handles.isl=true; set(handles.dld,'visible','on'); labels=X(:,cn); handles.labels=labels; handles.islb=true; end delete(hlds.figure1); end % history: % clear: handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; if handles.islb handles.m1={'load(''X.mat''); % load data'; 'load(''labels.mat''); % load labels';}; else handles.m1={'load(''X.mat''); % load data'}; end end else % here if load from xls file handles.isxls=true; delete(hands_l_d.figure1); drawnow; [FileName,PathName] = uigetfile({'*.xls';'*.xlsx'},'Select the xls-file'); if (FileName==0) % do nothing if click cancel else X = xlsread([PathName FileName]); % load fom xls numbers only handles.m1={}; handles.m2={}; handles.m3={}; handles.mstf={}; hstmp=load_xls(length(X(1,:))); drawnow; hands_l_x=guidata(hstmp); if get(hands_l_x.wl,'value') % if not use labels handles.labels=[]; handles.islb=false; handles.X=X; handles.isl=true; % history: handles.m1={['PathName = ''' PathName '''; % path to xls-file']; ['FileName = ''' FileName '''; % file name of xls-file']; 'X = xlsread([PathName FileName]); % load xls file'}; set(handles.dld,'visible','on'); else % if use labels cn=str2num(get(hands_l_x.col,'String')); lX=length(X(1,:)); ncn1=1:lX; ncni=find(ncn1~=cn); ncn=ncn1(ncni); handles.X=X(:,ncn); handles.isl=true; set(handles.dld,'visible','on'); labels=X(:,cn); handles.labels=labels; handles.islb=true; % history: handles.m1={['PathName = ''' PathName '''; % path to xls-file']; ['FileName = ''' FileName '''; % file name of xls-file']; 'X = xlsread([PathName FileName]); % load xls file'; ['cn = ' num2str(cn) '; % column number where labels are placed']; 'lX=length(X(1,:)); % total number of column'; 'ncn1=1:lX;'; 'ncni=find(ncn1~=cn); % indexes of data columns'; 'ncn=ncn1(ncni); % data columns'; 'labels=X(:,cn); % get labels'; 'X=X(:,ncn); % get data'}; end delete(hands_l_x.figure1); drawnow; end end end set(handles.edr,'String',''); set(handles.cd,'visible','off'); handles.mcd=false; guidata(handles.figure1, handles); set(handles.ld,'Enable','on'); drawnow; % --- Executes on button press in sp. function sp_Callback(hObject, eventdata, handles) if handles.isl ld=length(handles.X(1,:)); if ld==2 hf=figure; set(hf,'name','Original dataset','NumberTitle','off'); if handles.islb scatter(handles.X(:,1),handles.X(:,2),5,handles.labels); else scatter(handles.X(:,1),handles.X(:,2),5); end title('Original dataset'); else if handles.islb scattern('Original dataset',handles.X,handles.labels); else scattern('Original dataset',handles.X); end end else % 'not loaded' not_loaded; end % --- Executes on button press in p. function p_Callback(hObject, eventdata, handles) if handles.isl ld=length(handles.X(1,:)); if ld==2 hf=figure; set(hf,'name','Original dataset','NumberTitle','off'); % if handles.islb % plot(handles.X(:,1),handles.X(:,2),5,handles.labels); % else plot(handles.X(:,1),handles.X(:,2),'.r'); % end title('Original dataset'); else % if handles.islb % scattern('Original dataset',handles.X,handles.labels); % else plotn('Original dataset',handles.X); % end end else % 'not loaded' not_loaded; end % --- Executes on button press in ed. function ed_Callback(hObject, eventdata, handles) handles.a2=false; if handles.isl try s=choose_method; catch return end hs1=guidata(s); set(hs1.ok,'Enable','off'); drawnow; method=get(hs1.str,'string'); no_dims = intrinsic_dim(handles.X, method); % estimate dimention lead to clear calculated data: handles.mcd=false; % if mapping was calculated handles.mX=[]; % mapped X set(handles.cd,'Visible','off'); % history: handles.m2={}; handles.m3={}; handles.mstf={}; % get detailed method name from listbox: lstbs=get(hs1.listbox1,'string'); lstv=get(hs1.listbox1,'value'); mthds=lstbs{lstv}; handles.m2={['method_ed = ''' method '''; % (' mthds ') method of estimation of dimensionality']; ['no_dims = intrinsic_dim(X, method_ed); % estimate intrinsic dimensionality']}; delete(hs1.figure1); drawnow; set(handles.edr,'string',num2str(no_dims)); set(handles.edr,'UserData',no_dims); % memorize pricise value in userdata guidata(handles.figure1, handles); else % 'not loaded' not_loaded; end function edr_Callback(hObject, eventdata, handles) % hObject handle to edr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edr as text % str2double(get(hObject,'String')) returns contents of edr as a double % --- Executes during object creation, after setting all properties. function edr_CreateFcn(hObject, eventdata, handles) % hObject handle to edr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in cm. function cm_Callback(hObject, eventdata, handles) if handles.isl handles.m3={}; % eraise priviose history handles.mstf={}; no_dims=get(handles.edr,'UserData'); no_dims_old=no_dims; try s=mapping_parameters(no_dims,handles.islb); catch return end hs1=guidata(s); %mappedA = compute_mapping(A, type, no_dims, parameters, eig_impl) no_dims=str2num(get(hs1.nd,'string')); %if (~handles.a2)||(round(no_dims_old)~=no_dims) % if was not added or if changed handles.a2=true; if ~isempty(no_dims_old) if round(no_dims_old)~=no_dims % if demetion was changed handles.m21={' '; ['no_dims = ' num2str(no_dims) '; % supposed number of dimensions']; ' '}; else handles.m21={' '; ['no_dims = round(no_dims); % round number of dimensions to have integer number']; ' '}; end else handles.m21={' '; ['no_dims = ' num2str(no_dims) '; % supposed number of dimensions']; ' '}; end if isempty(handles.m2) handles.m21={' '; ['no_dims = ' num2str(no_dims) '; % supposed number of dimensions']; ' '}; end %handles.m2=vertcat(handles.m2,m2t); %end mappedA=[]; try noparam=false; % if no parameters mthd=''; % method when no parameters switch get(hs1.listbox1,'Value') case 1 % PCA % no parameters; mappedA = compute_mapping(handles.X, 'PCA', no_dims); noparam=true; mthd='PCA'; case 2 % LDA % no parameters; % correct lables only to column-vector: lb=handles.labels; slb=size(lb); if min(slb)>1 warning('slb must be vector'); end if slb(1)<slb(2) lb=lb'; end if handles.islb mappedA = compute_mapping([lb handles.X], 'LDA', no_dims); % set labels through first column if slb(1)<slb(2) handles.m3={['labels=labels''; % labels must be a vector-column ']; ['mappedX = compute_mapping([labels X], ''LDA'', no_dims); % set labels through first column']}; else handles.m3={['mappedX = compute_mapping([labels X], ''LDA'', no_dims); % set labels through first column']}; end else % imposible because data without labels warning('it is imposible to be here'); end case 3 % MDS % no parameters; mappedA = compute_mapping(handles.X, 'MDS', no_dims); noparam=true; mthd='MDS'; case 4 % SimplePCA % no parameters; mappedA = compute_mapping(handles.X, 'SimplePCA', no_dims); noparam=true; mthd='SimplePCA'; case 5 % ProbPCA mi=str2num(get(hs1.mi,'string')); mappedA = compute_mapping(handles.X, 'ProbPCA', no_dims, mi); handles.m3={['mi = ' num2str(mi) '; % max iterations']; ['mappedX = compute_mapping(X, ''ProbPCA'', no_dims, mi);']}; case 6 % FactorAnalysis % no parameters; mappedA = compute_mapping(handles.X, 'FactorAnalysis', no_dims); noparam=true; mthd='FactorAnalysis'; case 7 % Isomap if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end mappedA = compute_mapping(handles.X, 'Isomap', no_dims, k); m3t={['mappedX = compute_mapping(X, ''Isomap'', no_dims, k);']}; handles.m3=vertcat(handles.m3,m3t); case 8 % LandmarkIsomap if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end prc=str2num(get(hs1.prc,'string')); m3t={['prc = ' num2str(prc) '; % percentage']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LandmarkIsomap', no_dims, k, prc); m3t={['mappedX = compute_mapping(X, ''LandmarkIsomap'', no_dims, k, prc);']}; handles.m3=vertcat(handles.m3,m3t); case 9 % LLE if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); [mappedA, mapping] = compute_mapping(handles.X, 'LLE', no_dims, k, eim); m3t={['[mappedX, mapping] = compute_mapping(X, ''LLE'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 10 % Laplacian if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'Laplacian', no_dims, k, sig, eim); m3t={['mappedX = compute_mapping(X, ''Laplacian'', no_dims, k, sig, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 11 % HessianLLE if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'HessianLLE', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''HessianLLE'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 12 % LTSA if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LTSA', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''LTSA'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 13 % MVU if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'MVU', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''MVU'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 14 % CCA if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'CCA', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''CCA'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 15 % LandmarkMVU if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end mappedA = compute_mapping(handles.X, 'LandmarkMVU', no_dims, k); m3t={['mappedX = compute_mapping(X, ''LandmarkMVU'', no_dims, k);']}; handles.m3=vertcat(handles.m3,m3t); case 16 % FastMVU if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end ft=get(hs1.fty,'value'); if ft m3t={['ft = true; % finetune']}; else m3t={['ft = false; % finetune']}; end handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'FastMVU', no_dims, k, ft, eim); m3t={['mappedX = compute_mapping(X, ''FastMVU'', no_dims, k, ft, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 17 % DiffusionMaps t=str2num(get(hs1.t,'string')); handles.m3={['t = ' num2str(t) ';']}; sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'DiffusionMaps', no_dims, t, sig); m3t={['mappedX = compute_mapping(X, ''DiffusionMaps'', no_dims, t, sig);']}; handles.m3=vertcat(handles.m3,m3t); case 18 % KernelPCA kernel='gauss'; if get(hs1.kl,'value') kernel='linear'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel); handles.m3={['kernel = ''linear'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel);']}; end if get(hs1.kg,'value') s=str2num(get(hs1.kgs,'string')); handles.m3={['s = ' num2str(s) '; % variance']}; kernel='gauss'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,s); m3t={['kernel = ''gauss'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, s);']}; handles.m3=vertcat(handles.m3,m3t); end if get(hs1.kp,'value') R=str2num(get(hs1.kpR,'string')); handles.m3={['R = ' num2str(R) '; % additional value']}; d=str2num(get(hs1.kpd,'string')); m3t={['d = ' num2str(d) '; % power number']}; handles.m3=vertcat(handles.m3,m3t); kernel='poly'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,R,d); m3t={['kernel = ''poly'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, R, d);']}; handles.m3=vertcat(handles.m3,m3t); end case 19 % GDA % correct lables only to column-vector: lb=handles.labels; slb=size(lb); if min(slb)>1 warning('slb must be vector'); end if slb(1)<slb(2) lb=lb'; end if slb(1)<slb(2) m3t={['labels=labels''; % labels must be a vector-column ']}; else m3t={}; end if handles.islb kernel='gauss'; if get(hs1.kl,'value') kernel='linear'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel); handles.m3={['kernel = ''linear'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel);']}; handles.m3=vertcat(m3t,handles.m3); end if get(hs1.kg,'value') s=str2num(get(hs1.kgs,'string')); handles.m3={['s = ' num2str(s) '; % variance']}; handles.m3=vertcat(m3t,handles.m3); kernel='gauss'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,s); m3t={['kernel = ''gauss'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, s);']}; handles.m3=vertcat(handles.m3,m3t); end if get(hs1.kp,'value') R=str2num(get(hs1.kpR,'string')); handles.m3={['R = ' num2str(R) '; % additional value']}; handles.m3=vertcat(m3t,handles.m3); d=str2num(get(hs1.kpd,'string')); m3t={['d = ' num2str(d) '; % power number']}; handles.m3=vertcat(handles.m3,m3t); kernel='poly'; mappedA = compute_mapping(handles.X, 'KernelPCA', no_dims,kernel,R,d); m3t={['kernel = ''poly'';']; ['mappedX = compute_mapping(X, ''KernelPCA'', no_dims, kernel, R, d);']}; handles.m3=vertcat(handles.m3,m3t); end else % imposible because data without labels warning('it is imposible to be here'); end case 20 % SNE prp=str2num(get(hs1.prp,'string')); handles.m3={['prp = ' num2str(prp) '; % perplexity']}; mappedA = compute_mapping(handles.X, 'SNE', no_dims, prp); m3t={['mappedX = compute_mapping(X, ''SNE'', no_dims, prp);']}; handles.m3=vertcat(handles.m3,m3t); case 21 % SymSNE prp=str2num(get(hs1.prp,'string')); handles.m3={['prp = ' num2str(prp) '; % perplexity']}; mappedA = compute_mapping(handles.X, 'SymSNE', no_dims, prp); m3t={['mappedX = compute_mapping(X, ''SymSNE'', no_dims, prp);']}; handles.m3=vertcat(handles.m3,m3t); case 22 % t-SNE prp=str2num(get(hs1.prp,'string')); handles.m3={['prp = ' num2str(prp) '; % perplexity']}; mappedA = compute_mapping(handles.X, 't-SNE', no_dims, prp); m3t={['mappedX = compute_mapping(X, ''t-SNE'', no_dims, prp);']}; handles.m3=vertcat(handles.m3,m3t); case 23 % LPP if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LPP', no_dims, k, sig, eim); m3t={['mappedX = compute_mapping(X, ''LPP'', no_dims, k, sig, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 24 % NPE if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'NPE', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''NPE'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 25 % LLTSA if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'LLTSA', no_dims, k, eim); m3t={['mappedX = compute_mapping(X, ''LLTSA'', no_dims, k, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 26 % SPE tp='Global'; if get(hs1.tg,'value') tp='Global'; mappedA = compute_mapping(handles.X, 'SPE', no_dims, tp); handles.m3={'tp = ''Global''; % type of stress function that minimized'; ['mappedX = compute_mapping(X, ''SPE'', no_dims, tp);']}; end if get(hs1.tl,'value') tp='Local'; k=str2num(get(hs1.k,'string')); mappedA = compute_mapping(handles.X, 'SPE', no_dims, tp, k); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']; 'tp = ''Local''; % type of stress function that minimized'; ['mappedX = compute_mapping(X, ''SPE'', no_dims, tp, k);']}; end case 27 % AutoEncoder % no parameters; mappedA = compute_mapping(handles.X, 'Autoencoder', no_dims); noparam=true; mthd='Autoencoder'; case 28 % LLC % no parameters; mappedA = compute_mapping(handles.X, 'LLC', no_dims); noparam=true; mthd='LLC'; case 29 % LLC if get(hs1.ka,'value') k='adaptive'; handles.m3={['k = ''adaptive''; % adaptive number of nearest neighbors in a neighborhood graph']}; else k=str2num(get(hs1.k,'string')); handles.m3={['k = ' num2str(k) '; % number of nearest neighbors in a neighborhood graph']}; end na=str2num(get(hs1.na,'string')); m3t={['na = ' num2str(na) '; % number of factor analyzers']}; handles.m3=vertcat(handles.m3,m3t); mi=str2num(get(hs1.mi,'string')); m3t={['mi = ' num2str(mi) '; % max iterations']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end mappedA = compute_mapping(handles.X, 'LLC', no_dims, k, na, mi, eim); m3t={['mappedX = compute_mapping(X, ''LLC'', no_dims, k, na, mi, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 30 % ManifoldChart na=str2num(get(hs1.na,'string')); handles.m3={['na = ' num2str(na) '; % number of factor analyzers']}; mi=str2num(get(hs1.mi,'string')); m3t={['mi = ' num2str(mi) '; % max iterations']}; handles.m3=vertcat(handles.m3,m3t); if get(hs1.eim,'value') eim='Matlab'; m3t={'eim = ''Matlab''; % eigenanalysis implementation'}; else eim='JDQR'; m3t={'eim = ''JDQR''; % eigenanalysis implementation'}; end mappedA = compute_mapping(handles.X, 'ManifoldChart', no_dims, na, mi, eim); m3t={['mappedX = compute_mapping(X, ''ManifoldChart'', no_dims, na, mi, eim);']}; handles.m3=vertcat(handles.m3,m3t); case 31 % CFA na=str2num(get(hs1.na,'string')); handles.m3={['na = ' num2str(na) '; % number of factor analyzers']}; mi=str2num(get(hs1.mi,'string')); m3t={['mi = ' num2str(mi) '; % max iterations']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'CFA', no_dims, na, mi); m3t={['mappedX = compute_mapping(X, ''CFA'', no_dims, na, mi);']}; handles.m3=vertcat(handles.m3,m3t); case 32 % GPLVM sig=str2num(get(hs1.sig,'string')); m3t={['sig = ' num2str(sig) '; % variance of a Gaussian kernel']}; handles.m3=vertcat(handles.m3,m3t); mappedA = compute_mapping(handles.X, 'GPLVM', no_dims, sig); m3t={['mappedX = compute_mapping(X, ''GPLVM'', no_dims, sig);']}; handles.m3=vertcat(handles.m3,m3t); case 33 % NCA mappedA = compute_mapping(handles.X, 'NCA', no_dims); m3t={'mappedX = compute_mapping(X, ''NCA'', no_dims);'}; handles.m3=vertcat(handles.m3,m3t); case 34 % MCML mappedA = compute_mapping(handles.X, 'MCML', no_dims); m3t={'mappedX = compute_mapping(X, ''MCML'', no_dims);'}; handles.m3=vertcat(handles.m3,m3t); end if noparam handles.m3={['mappedX = compute_mapping(X, ''' mthd ''', no_dims); % compute mapping using ' mthd ' method']}; end catch set(handles.cd,'visible','off'); handles.mcd=false; warning('mapping was not calculated'); handles.m3={}; handles.mstf={}; guidata(handles.figure1, handles); delete(hs1.figure1); drawnow; rethrow(lasterror); return end if length(mappedA)~=0 set(handles.cd,'visible','on'); handles.mX=mappedA; handles.mcd=true; else set(handles.cd,'visible','off'); handles.mcd=false; warning('mapping was not calculated'); handles.m3={}; handles.mstf={}; end guidata(handles.figure1, handles); delete(hs1.figure1); drawnow; else % 'not loaded' not_loaded; end % --- Executes on button press in pushbutton6. function pushbutton6_Callback(hObject, eventdata, handles) if handles.mcd ld=length(handles.mX(1,:)); if ld==2 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); if handles.islb && size(handles.mX, 1) == numel(handles.labels) scatter(handles.mX(:,1),handles.mX(:,2),5,handles.labels); else scatter(handles.mX(:,1),handles.mX(:,2),5); end title('Result of dimensionality reduction'); if size(handles.mX, 1) ~= numel(handles.labels) warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.'); end else if ld==1 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); if handles.islb && size(handles.mX, 1) == numel(handles.labels) scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5,handles.labels); else scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5); end title('Result of dimensionality reduction'); if size(handles.mX, 1) ~= numel(handles.labels) warning('The GUI cannot yet deal properly with disconnected parts in the neighborhood graph.'); end else if handles.islb scattern('Result of dimensionality reduction',handles.mX,handles.labels); else scattern('Result of dimensionality reduction',handles.mX); end end end else % 'not calulated' not_calculated; end % --- Executes on button press in pushbutton7. function pushbutton7_Callback(hObject, eventdata, handles) if handles.mcd ld=length(handles.mX(1,:)); if ld==2 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); % if handles.islb % scatter(handles.mX(:,1),handles.mX(:,2),5,handles.labels); % else plot(handles.mX(:,1),handles.mX(:,2),'.r'); % end title('Result of dimensionality reduction'); else if ld==1 hf=figure; set(hf,'name','Result of dimensionality reduction','NumberTitle','off'); %if handles.islb %scatter(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),5,handles.labels); %else plot(handles.mX(:,1),zeros(length(handles.mX(:,1)),1),'.k'); %end title('Result of dimensionality reduction'); else %if handles.islb % scattern('Result of dimensionality reduction',handles.mX,handles.labels); %else plotn('Result of dimensionality reduction',handles.mX); %end end end else % 'not calulated' not_calculated; end % --- Executes on button press in stmf. function stmf_Callback(hObject, eventdata, handles) [file,path] = uiputfile('*.mat','Save Mapped Data As'); if length(file)==1 if file==0 return end end mX=handles.mX; save([path file], 'mX'); % --- Executes on button press in sttf. function sttf_Callback(hObject, eventdata, handles) [file,path] = uiputfile('*.txt','Save Mapped Data As'); if length(file)==1 if file==0 return end end mX=handles.mX; save([path file], 'mX','-ascii', '-tabs'); % --- Executes on button press in stf. function stf_Callback(hObject, eventdata, handles) set(handles.stf,'Enable','off'); drawnow; if handles.mcd if get(handles.stmfr,'value') [file,path] = uiputfile('*.mat','Save Mapped Data As'); if length(file)==1 if file==0 set(handles.stf,'Enable','on'); drawnow; return end end mX=handles.mX; save([path file], 'mX'); handles.mstf={['save(''' path file ''', ''mappedX''); % save result to mat-file']}; end if get(handles.sttfr,'value') [file,path] = uiputfile('*.txt','Save Mapped Data As'); if length(file)==1 if file==0 set(handles.stf,'Enable','on'); drawnow; return end end mX=handles.mX; save([path file], 'mX','-ascii', '-tabs'); handles.mstf={['save(''' path file ''', ''mappedX'',''-ascii'', ''-tabs''); % save result to txt-file']}; end if get(handles.stxfr,'value') [file,path] = uiputfile('*.xls','Save Mapped Data As'); if length(file)==1 if file==0 set(handles.stf,'Enable','on'); drawnow; return end end mX=handles.mX; xlswrite([path file], mX); handles.mstf={['xlswrite(''' path file ''', mappedX); % save result to xls-file']}; end guidata(handles.figure1, handles); else % 'not calulated' not_calculated; end set(handles.stf,'Enable','on'); drawnow; % --- Executes when selected object is changed in uipanel1. function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) % hObject handle to the selected object in uipanel1 % eventdata structure with the following fields (see UIBUTTONGROUP) % EventName: string 'SelectionChanged' (read only) % OldValue: handle of the previously selected object or empty if none was selected % NewValue: handle of the currently selected object % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in sh. function sh_Callback(hObject, eventdata, handles) set(handles.sh,'enable','off'); drawnow; if (isempty(handles.m1))&&(isempty(handles.m2))&&(isempty(handles.m3)) no_history; else [file,path] = uiputfile('*.m','Save History As'); if length(file)==1 if file==0 set(handles.sh,'enable','on'); drawnow; return end end fid = fopen([path file],'w'); fprintf(fid,'%s\r\n',['% this file was generated by drtool at ' datestr(now)]); fprintf(fid,'%s\r\n',' '); % empty line - delimeter if ~isempty(handles.isxls) if ~handles.isxls % here if txt/mat file was loaded so it is need save data and labels X=handles.X; save([path 'X.mat'],'X'); if handles.islb % save labells if any labels=handles.labels; save([path 'labels.mat'],'labels'); fprintf(fid,'%s\r\n','% Note: data and labels were saved in X.mat and labels.mat together with this m-file in the same folder'); else fprintf(fid,'%s\r\n','% Note: data was saved in X.mat together with this m-file in the same folder'); end end end fprintf(fid,'%s\r\n',' '); fprintf(fid,'%s\r\n','% 1.'); fprintf(fid,'%s\r\n','% get data'); for mc=1:length(handles.m1) fprintf(fid,'%s\r\n',handles.m1{mc}); end % plot original data: mpod={'% plot original data:'}; ld=length(handles.X(1,:)); if ld==2 mpodt={'hf=figure;'; 'set(hf,''name'',''Original dataset'',''NumberTitle'',''off'');'}; mpod=vertcat(mpod,mpodt); if handles.islb mpodt={'scatter(X(:,1),X(:,2),5,labels);'}; else mpodt={'plot(X(:,1),X(:,2),''x-'');'}; end mpod=vertcat(mpod,mpodt); mpodt={'title(''Original dataset'');'}; mpod=vertcat(mpod,mpodt); else if handles.islb mpodt={'scattern(''Original dataset'',X,labels);'}; else mpodt={'plotn(''Original dataset'',X);'}; end mpod=vertcat(mpod,mpodt); end fprintf(fid,'%s\r\n',' '); for mc=1:length(mpod) fprintf(fid,'%s\r\n',mpod{mc}); end fprintf(fid,'%s\r\n',' '); if length(handles.m2)~=0 fprintf(fid,'%s\r\n',' '); % empty line - delimeter handles.m2=vertcat(handles.m2,handles.m21); fprintf(fid,'%s\r\n','% 2.'); fprintf(fid,'%s\r\n','% estimate intrinsic dimensionality'); for mc=1:length(handles.m2) fprintf(fid,'%s\r\n',handles.m2{mc}); end else if length(handles.m3)~=0 % if was not dimetion estimation thet it is need to set it for % part 3 for mc=1:length(handles.m21) fprintf(fid,'%s\r\n',handles.m21{mc}); end end end if length(handles.m3)~=0 fprintf(fid,'%s\r\n',' '); % empty line - delimeter fprintf(fid,'%s\r\n','% 3.'); fprintf(fid,'%s\r\n','% compute mapping'); for mc=1:length(handles.m3) fprintf(fid,'%s\r\n',handles.m3{mc}); end % plot result mpod={'% plot result of dimensionality reduction:'}; if handles.islb mpodt={'scatter12n(''Result of dimensionality reduction'',mappedX,labels);'}; else mpodt={'plot12n(''Result of dimensionality reduction'',mappedX);'}; end mpod=vertcat(mpod,mpodt); fprintf(fid,'%s\r\n',' '); for mc=1:length(mpod) fprintf(fid,'%s\r\n',mpod{mc}); end fprintf(fid,'%s\r\n',' '); end if length(handles.mstf)~=0 fprintf(fid,'%s\r\n',' '); % empty line - delimeter fprintf(fid,'%s\r\n',' '); % empty line - delimeter for mc=1:length(handles.mstf) fprintf(fid,'%s\r\n',handles.mstf{mc}); end end fclose(fid); end set(handles.sh,'enable','on'); drawnow;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
plot12n.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/plot12n.m
1,356
utf_8
8a16c46e9b838f4602a5af8fc8a857a8
% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology function plot12n(name,data) ld=length(data(1,:)); if ld==2 hf=figure; set(hf,'name',name,'NumberTitle','off'); % if handles.islb % scatter(data(:,1),data(:,2),5,handles.labels); % else plot(data(:,1),data(:,2),'.r'); % end title(name); else if ld==1 hf=figure; set(hf,'name',name,'NumberTitle','off'); %if handles.islb %scatter(data(:,1),zeros(length(data(:,1)),1),5,handles.labels); %else plot(data(:,1),zeros(length(data(:,1)),1),'.k'); %end title(name); else %if handles.islb % scattern('Result of dimensionality reduction',data,handles.labels); %else plotn(name,data); %end end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
not_loaded.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/not_loaded.m
7,728
utf_8
a754380baacab27eac13658ea4cc21a3
function varargout = not_loaded(varargin) % NOT_LOADED M-file for not_loaded.fig % NOT_LOADED by itself, creates a new NOT_LOADED or raises the % existing singleton*. % % H = NOT_LOADED returns the handle to a new NOT_LOADED or the handle to % the existing singleton*. % % NOT_LOADED('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in NOT_LOADED.M with the given input arguments. % % NOT_LOADED('Property','Value',...) creates a new NOT_LOADED or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before not_loaded_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to not_loaded_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help not_loaded % Last Modified by GUIDE v2.5 24-Jul-2008 18:38:56 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @not_loaded_OpeningFcn, ... 'gui_OutputFcn', @not_loaded_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before not_loaded is made visible. function not_loaded_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to not_loaded (see VARARGIN) % Choose default command line output for not_loaded handles.output = 'Yes'; % Update handles structure guidata(hObject, handles); % Insert custom Title and Text if specified by the user % Hint: when choosing keywords, be sure they are not easily confused % with existing figure properties. See the output of set(figure) for % a list of figure properties. if(nargin > 3) for index = 1:2:(nargin-3), if nargin-3==index, break, end switch lower(varargin{index}) case 'title' set(hObject, 'Name', varargin{index+1}); case 'string' set(handles.text1, 'String', varargin{index+1}); end end end % Determine the position of the dialog - centered on the callback figure % if available, else, centered on the screen FigPos=get(0,'DefaultFigurePosition'); OldUnits = get(hObject, 'Units'); set(hObject, 'Units', 'pixels'); OldPos = get(hObject,'Position'); FigWidth = OldPos(3); FigHeight = OldPos(4); if isempty(gcbf) ScreenUnits=get(0,'Units'); set(0,'Units','pixels'); ScreenSize=get(0,'ScreenSize'); set(0,'Units',ScreenUnits); FigPos(1)=1/2*(ScreenSize(3)-FigWidth); FigPos(2)=2/3*(ScreenSize(4)-FigHeight); else GCBFOldUnits = get(gcbf,'Units'); set(gcbf,'Units','pixels'); GCBFPos = get(gcbf,'Position'); set(gcbf,'Units',GCBFOldUnits); FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ... (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2]; end FigPos(3:4)=[FigWidth FigHeight]; set(hObject, 'Position', FigPos); set(hObject, 'Units', OldUnits); % Show a question icon from dialogicons.mat - variables questIconData % and questIconMap load dialogicons.mat IconData=questIconData; questIconMap(256,:) = get(handles.figure1, 'Color'); IconCMap=questIconMap; Img=image(IconData, 'Parent', handles.axes1); set(handles.figure1, 'Colormap', IconCMap); set(handles.axes1, ... 'Visible', 'off', ... 'YDir' , 'reverse' , ... 'XLim' , get(Img,'XData'), ... 'YLim' , get(Img,'YData') ... ); % Make the GUI modal set(handles.figure1,'WindowStyle','modal') % UIWAIT makes not_loaded wait for user response (see UIRESUME) uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = not_loaded_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % The figure can be deleted now delete(handles.figure1); % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = get(hObject,'String'); % Update handles structure guidata(hObject, handles); % Use UIRESUME instead of delete because the OutputFcn needs % to get the updated handles structure. uiresume(handles.figure1); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isequal(get(handles.figure1, 'waitstatus'), 'waiting') % The GUI is still in UIWAIT, us UIRESUME uiresume(handles.figure1); else % The GUI is no longer waiting, just close it delete(handles.figure1); end % --- Executes on key press over figure1 with no controls selected. function figure1_KeyPressFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check for "enter" or "escape" if isequal(get(hObject,'CurrentKey'),'escape') % User said no by hitting escape handles.output = 'No'; % Update handles structure guidata(hObject, handles); uiresume(handles.figure1); end if isequal(get(hObject,'CurrentKey'),'return') uiresume(handles.figure1); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
load_data.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/drtoolbox/gui/load_data.m
6,534
utf_8
ade0538cbeeb79ed3c72aea5743a2424
function varargout = load_data(varargin) % LOAD_DATA M-file for load_data.fig % LOAD_DATA, by itself, creates a new LOAD_DATA or raises the existing % singleton*. % % H = LOAD_DATA returns the handle to a new LOAD_DATA or the handle to % the existing singleton*. % % LOAD_DATA('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOAD_DATA.M with the given input arguments. % % LOAD_DATA('Property','Value',...) creates a new LOAD_DATA or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before load_data_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to load_data_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b. % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 % You are free to use, change, or redistribute this code in any way you % want for non-commercial purposes. However, it is appreciated if you % maintain the name of the original author. % % (C) Laurens van der Maaten, 2010 % University California, San Diego / Delft University of Technology % Edit the above text to modify the response to help load_data % Last Modified by GUIDE v2.5 23-Jul-2008 16:01:33 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @load_data_OpeningFcn, ... 'gui_OutputFcn', @load_data_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before load_data is made visible. function load_data_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to load_data (see VARARGIN) % Choose default command line output for load_data handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes load_data wait for user response (see UIRESUME) uiwait(handles.figure1); % uiwait; % --- Outputs from this function are returned to the command line. function varargout = load_data_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function ndp_Callback(hObject, eventdata, handles) % hObject handle to ndp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ndp as text % str2double(get(hObject,'String')) returns contents of ndp as a double % --- Executes during object creation, after setting all properties. function ndp_CreateFcn(hObject, eventdata, handles) % hObject handle to ndp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nl_Callback(hObject, eventdata, handles) % hObject handle to nl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of nl as text % str2double(get(hObject,'String')) returns contents of nl as a double % --- Executes during object creation, after setting all properties. function nl_CreateFcn(hObject, eventdata, handles) % hObject handle to nl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) uiresume(handles.figure1); % -------------------------------------------------------------------- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if get(handles.file,'value') cl=[0.4 0.4 0.4]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','off'); set(handles.nl,'Enable','off'); set(handles.ok,'String','Start wizard'); else cl=[0 0 0]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','on'); set(handles.nl,'Enable','on'); set(handles.ok,'String','OK'); end if get(handles.xls,'value') cl=[0.4 0.4 0.4]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','off'); set(handles.nl,'Enable','off'); set(handles.ok,'String','Open XLS-file'); else if ~get(handles.file,'value') cl=[0 0 0]; set(handles.ndpt,'ForegroundColor',cl); set(handles.nlt,'ForegroundColor',cl); set(handles.ndp,'Enable','on'); set(handles.nl,'Enable','on'); set(handles.ok,'String','OK'); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
ann_compile_mex.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/ANN/ann_mwrapper/ann_compile_mex.m
1,880
utf_8
014163ea1a72871ab04e2f661fc26a66
function ann_compile_mex() %ANN_COMPILE_MEX Compiles the core-mex files of the ANN Lib % % [ Syntax ] % - ann_compile_mex % % [ Description ] % - ann_compile_mex re-compiles the mex files. % % [ History ] % - Created by Dahua Lin, on Jul 06, 2007 % %% configurations % When you intend to change the configuration, please modify the following % lines ann_lib_root = 'ann_1.1.1'; ann_src_dir = [ann_lib_root, '/src']; ann_inc_dir = [ann_lib_root, '/include']; options = {'-O', '-v'}; %% main main_file = 'private/ann_mex_bk.cpp'; output_dir = 'private'; src_files = { ... 'ANN.cpp', ... 'bd_fix_rad_search.cpp', ... 'bd_pr_search.cpp', ... 'bd_search.cpp', ... 'bd_tree.cpp', ... 'brute.cpp', ... 'kd_dump.cpp', ... 'kd_fix_rad_search.cpp', ... 'kd_pr_search.cpp', ... 'kd_search.cpp', ... 'kd_split.cpp', ... 'kd_tree.cpp', ... 'kd_util.cpp', ... 'perf.cpp' }; check_exist(main_file); src_paths = cell(size(src_files)); for i = 1 : length(src_files) src_paths{i} = [ann_src_dir '/' src_files{i}]; check_exist(src_paths{i}); end switch filesep case '\' % mex(options{:},'-f','C:\Documents and Settings\Administrator\Application Data\MathWorks\MATLAB\R2007a\mexopts.bat', ['-I', ann_inc_dir], '-outdir', output_dir, main_file, src_paths{:}); mex(options{:}, ['-I', ann_inc_dir], '-outdir', output_dir, main_file, src_paths{:}); case '/' mex(options{:},'-f','/home/kruegerb/checkout/tools_intern/efficiency/efficiency_linux64/mexopts.sh', ['-I', ann_inc_dir], '-outdir', output_dir, main_file, src_paths{:}); end function check_exist(path) if ~exist(path, 'file') error('ann_mwrapper:ann_compile_mex:filenotfound', ... 'The file %s is not found', path); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
require_opt.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/ANN/ann_mwrapper/require_opt.m
99
utf_8
e7185a8f660741c408ea165caafcd4e3
function require_opt(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidopt', msg); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
annquery_bk.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/ANN/ann_mwrapper/annquery_bk.m
14,109
utf_8
ecc177956de83f5571791d1a5c7e3255
function [nnidx, dists] = annquery_bk(call, Points, varargin) switch call case 1 % Build tree case 2 % Query tree case 3 % Delete tree otherwise error('Unknown call for annquery_bk!\n'); end %ANNQUERY Performs Approximate K-Nearest-Neighbor query for a set of points % % [ Syntax ] % - nnidx = annquery(Xr, Xq, k) % - nnidx = annquery(Xr, Xq, k, ...) % - [nnidx, dists] = annquery(...) % - annquery -doc % % [ Arguments ] % - Xr: the reference points to construct the kd-tree (d x n matrix) % - Xq: the query points (d x nq matrix) % - k: the number of neighbors for each query point % % - nnidx: the array of indices of nearest neighbors (k x n matrix) % - dists: the array of distances between the neighbors and the query % points (k x n matrix) % % [ Description ] % - nnidx = annquery(Xr, Xq, k) finds the nearest neighbors of the query % points with default options. % % Suppose we are dealing with d-dimensional points, and there are n % reference points, and nq query points. Then Xr and Xq should be % d x n and d x nq matrix respectively, with each column representing % a point. % % For each point in Xq (say the i-th point, that is Xq(:,i)), the % function finds k nearest points to it in Xr. The indices of these % k points in Xr are stored in the i-th column of nnidx. % % - nnidx = annquery(Xr, Xq, k, ...) performs the k-NN search with % user-specified options. The options can be specified by name-value % list. % % Here are the options that can be set % \{: % - use_bdtree: whether to use box-decomposition tree % (default = false). % % bd-tree is a variant kd-tree structure, which % is more effectively in dealing with the highly % clustered points by incorporating shrinking % operations. However, it is not necessary for % typical datasets. % % - bucket_size: the size of each bucket in the tree. % (default = 1). % % - split: the name of the splitting rule in kd-tree % construction. (default = 'suggest') % % Here is a list of available split rules: % \{: % - std: the standard kd-tree splitting % rule % - midpt: the mid-point splitting rule % - sl_midpt: the sliding mid-point splitting % rule % - fair: the fair splitting rule % - sl_fair: the sliding fair splitting rule % - suggest: the suggested rule, which % performs best for typical cases. % \:} % % - shrink: the name of the shrinking rule in bd-tree % construction. (default = 'suggest') % % Here is a list of available shrinking rules: % \{: % - none: no shrinking is performed. % Without shrinking, bd-tree is % equivalent to normal kd-tree. % - simple: simple shrinking. % - centroid: centroid shrinking. % - suggest: the suggested rule, which % performs best for typical % cases. % \:} % The shrink option only takes effect when % use_bdtree is set to true. % % - search_sch: the search scheme to use. (default = 'std') % % Here is a list of available search schemes: % \{: % - std: the standard k-NN search % - pri: the priority search % % By this scheme, the cell that % contains the query point is % located, and cells are visited % in increasing order of distance % from the query point. % % - fr: the fixed-radius search % % By this scheme, only the % reference points whose % distances to the query point % is less than a radius is found. % \:} % % - eps: the upper bound on the search error. % % For 1 <= i <= k, the ratio between the distance % to the i-th reported point and that to the true % i-th nearest neighbor is at most 1 + eps. % % Typically, eps controls the trade-off between % efficiency and accuracy. When eps is set % larger, the approximation is less accurate, and % the search completes faster. % % - radius: the maximum distance between the neighbors and % the query point. This option only takes effects % when search_sch is set to 'fr'. In other words, % it only applies to fixed-radius search. % \:} % % Generally, the default options can work well for typical cases. In % special cases, you can change some options with others left in default % value by only specifying the options you would like to change. % % - [nnidx, dists] = annquery(...) also returns the corresponding distance values. % % In the output, dists is a k x nq double matrix. dists(i, j) is the distance of % the j's query point's distance to its i-th neighbor. % % Since that nnidx(i, j) is the index of j's query point's i-th neighbor, % nnidx and dists are corresponding. % % - annquery -doc or annquery('-doc') shows the HTML help in the MATLAB % embeded browser. % % [ Remarks ] % - The function is based on a mex-wrapper (ann_mex.m in private folder) % of the Approximate Nearest Neighbors Library version 1.1.1. % % - It is strongly recommended to gather all queries together and conduct % the queries in batch. Since for each time this function is invoked, % it constructs the kd-tree from the reference points. Hence, it may % lead to considerable overhead if the queries are done one by one. % % - The found nearest points for each query point are sorted in ascending % order of distance. It means that the first result refers to the point % nearest to the query, while the second one refers to the second % nearest, and so on. % % - If fixed-radius scheme is used (set search_sch option to 'fr'), it % is probable that for some query points, there are less than k % neighbors within the specified range. % % For example, if k = 5, and there are only 2 neighbors in the % specified range for the i-th query, then nnidx(:, i) would be a % column, in which the first 2 entries are the indices of the two % nearest neighbors, while the last 3 entries are all zeros. % Correspondingly, the last 3 entries in dists(:, i) are all inf. % % To summarize, the function uses 0 to indicate that a neighbor is not % found, and uses inf to give the corresponding distance. This only % applies to fixed-radius scheme. (For other schemes, it is impossible % that the neighbors are not sufficient). % % - If fixed-radius search is used, it is required that a positive radius % be explicitly set. % % [ Examples ] % - For each of 100 points of 5 dimensions, find its 3 nearesr neighbors in % a reference set of 200 points, using default options. % \{ % Xq = rand(5, 100); % Xr = rand(5, 200); % % inds = annquery(Xr, Xq, 3); % \} % If you would like to get the corresponding Euclidean distances as % well, you can use the following command % \{ % [inds, dists] = annquery(Xr, Xq, 3); % \} % % - Use user-specified options. % \{ % % use priority search scheme with a sliding fair rule % inds = annquery(Xr, Xq, k, 'search_sch', 'pri', 'split', 'sl_fair'); % % % set positive error bound to allow some errors % % in order to increase efficiency % inds = annquery(Xr, Xq, k, 'eps', 0.1); % % % use fixed-radius search with all neighbors confined within % % a range of radius 0.08 % inds = annquery(Xr, Xq, k, 'search_sch', 'fr', 'radius', 0.08); % % % use bd-tree construction % inds = annquery(Xr, Xq, k, 'use_bdtree', true); % % % use bd-tree construction with centroid shrinking rule % inds = annquery(Xr, Xq, k, 'use_bdtree', true, 'shrink', 'centroid'); % \} % % - If you want to find neighbors for each point within the same point % set with the query point itself excluded from neighbor set. % \{ % [inds, dists] = annquery(X, X, k+1, ...); % % inds = inds(2:end, :); % dists = dists(2:end, :); % \} % % This simple way is based on the rationale that the query point itself % is the most nearest point to the query when searching in the same % set. It works in most cases. % % However, if there are two points reside in EXACTLY the same position, % then it is probable that another point in the same position is % removed while the query point remains. However, such circumstances % rarely happen in real data. % % [ History ] % - Created by Dahua Lin, on Jul 06, 2007 % %% For help % if nargin == 1 && ischar(Xr) && strcmpi(Xr, '-doc') % showdoc(mfilename('fullpath')); % return; % end %% parse and verify input arguments error(nargchk(3, inf, nargin)); % some predicates is_normal_matrix = @(x) isnumeric(x) && ndims(x) == 2 && isreal(x) && ~issparse(x); is_posint_scalar = @(x) isnumeric(x) && isscalar(x) && x == fix(x) && x > 0; is_switch = @(x) islogical(x) && isscalar(x); is_float_scalar = @(x) isfloat(x) && isscalar(x); % Xr and Xq require_arg(is_normal_matrix(Xr), 'Xr should be a full numeric real matrix'); require_arg(is_normal_matrix(Xq), 'Xq should be a full numeric real matrix'); [d, n] = size(Xr); % require_arg(size(Xq, 1) == d, 'The point dimensions in Xr and Xq are inconsistent.') % k % require_arg(is_posint_scalar(k), 'k should be a positive integer scalar'); % require_arg(k <= n, 'The value k exceeds the number of reference points'); % options opts = struct( ... 'use_bdtree', false, ... 'bucket_size', 1, ... 'split', 'suggest', ... 'shrink', 'suggest', ... 'search_sch', 'std', ... 'eps', 0, ... 'radius', 0); if ~isempty(varargin) opts = setopts(opts, varargin{:}); end require_opt(is_switch(opts.use_bdtree), 'The option use_bdtree should be a logical scalar.'); require_opt(is_posint_scalar(opts.bucket_size), 'The option bucket_size should be a positive integer.'); split_c = get_name_code('splitting rule', opts.split, ... {'std', 'midpt', 'sl_midpt', 'fair', 'sl_fair', 'suggest'}); if opts.use_bdtree shrink_c = get_name_code('shrinking rule', opts.shrink, ... {'none', 'simple', 'centroid', 'suggest'}); else shrink_c = int32(0); end ssch_c = get_name_code('search scheme', opts.search_sch, ... {'std', 'pri', 'fr'}); require_opt(is_float_scalar(opts.eps) && opts.eps >= 0, ... 'The option eps should be a non-negative float scalar.'); use_fix_rad = strcmp(opts.search_sch, 'fr'); if use_fix_rad require_opt(is_float_scalar(opts.radius) && opts.radius > 0, ... 'The option radius should be a positive float scalar in fixed-radius search'); rad2 = opts.radius * opts.radius; else rad2 = 0; end %% main (invoking ann_mex) internal_opts = struct( ... 'use_bdtree', opts.use_bdtree, ... 'bucket_size', int32(opts.bucket_size), ... 'split', split_c, ... 'shrink', shrink_c, ... 'search_sch', ssch_c, ... 'knn', int32(k), ... 'err_bound', opts.eps, ... 'search_radius', rad2); [nnidx, dists] = ann_mex_bk(Xr, Xq, internal_opts); nnidx = nnidx + 1; % from zero-based to one-based if nargout >= 2 dists = sqrt(dists); % from squared distance to euclidean if use_fix_rad dists(nnidx == 0) = inf; end end %% Auxiliary function function c = get_name_code(optname, name, names) require_opt(ischar(name), ['The option ' optname ' should be a string indicating a name.']); cidx = find(strcmp(name, names)); require_opt(~isempty(cidx), ['The option ' optname ' cannot be assigned to be ' name]); c = int32(cidx - 1); function require_arg(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidarg', msg); end function require_opt(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidopt', msg); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
annquery.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/ANN/ann_mwrapper/annquery.m
13,857
utf_8
8cd85e7edbcfa78dccb8ddec6dbf4c39
function [nnidx, dists] = annquery(Xr, Xq, k, varargin) %ANNQUERY Performs Approximate K-Nearest-Neighbor query for a set of points % % [ Syntax ] % - nnidx = annquery(Xr, Xq, k) % - nnidx = annquery(Xr, Xq, k, ...) % - [nnidx, dists] = annquery(...) % - annquery -doc % % [ Arguments ] % - Xr: the reference points to construct the kd-tree (d x n matrix) % - Xq: the query points (d x nq matrix) % - k: the number of neighbors for each query point % % - nnidx: the array of indices of nearest neighbors (k x n matrix) % - dists: the array of distances between the neighbors and the query % points (k x n matrix) % % [ Description ] % - nnidx = annquery(Xr, Xq, k) finds the nearest neighbors of the query % points with default options. % % Suppose we are dealing with d-dimensional points, and there are n % reference points, and nq query points. Then Xr and Xq should be % d x n and d x nq matrix respectively, with each column representing % a point. % % For each point in Xq (say the i-th point, that is Xq(:,i)), the % function finds k nearest points to it in Xr. The indices of these % k points in Xr are stored in the i-th column of nnidx. % % - nnidx = annquery(Xr, Xq, k, ...) performs the k-NN search with % user-specified options. The options can be specified by name-value % list. % % Here are the options that can be set % \{: % - use_bdtree: whether to use box-decomposition tree % (default = false). % % bd-tree is a variant kd-tree structure, which % is more effectively in dealing with the highly % clustered points by incorporating shrinking % operations. However, it is not necessary for % typical datasets. % % - bucket_size: the size of each bucket in the tree. % (default = 1). % % - split: the name of the splitting rule in kd-tree % construction. (default = 'suggest') % % Here is a list of available split rules: % \{: % - std: the standard kd-tree splitting % rule % - midpt: the mid-point splitting rule % - sl_midpt: the sliding mid-point splitting % rule % - fair: the fair splitting rule % - sl_fair: the sliding fair splitting rule % - suggest: the suggested rule, which % performs best for typical cases. % \:} % % - shrink: the name of the shrinking rule in bd-tree % construction. (default = 'suggest') % % Here is a list of available shrinking rules: % \{: % - none: no shrinking is performed. % Without shrinking, bd-tree is % equivalent to normal kd-tree. % - simple: simple shrinking. % - centroid: centroid shrinking. % - suggest: the suggested rule, which % performs best for typical % cases. % \:} % The shrink option only takes effect when % use_bdtree is set to true. % % - search_sch: the search scheme to use. (default = 'std') % % Here is a list of available search schemes: % \{: % - std: the standard k-NN search % - pri: the priority search % % By this scheme, the cell that % contains the query point is % located, and cells are visited % in increasing order of distance % from the query point. % % - fr: the fixed-radius search % % By this scheme, only the % reference points whose % distances to the query point % is less than a radius is found. % \:} % % - eps: the upper bound on the search error. % % For 1 <= i <= k, the ratio between the distance % to the i-th reported point and that to the true % i-th nearest neighbor is at most 1 + eps. % % Typically, eps controls the trade-off between % efficiency and accuracy. When eps is set % larger, the approximation is less accurate, and % the search completes faster. % % - radius: the maximum distance between the neighbors and % the query point. This option only takes effects % when search_sch is set to 'fr'. In other words, % it only applies to fixed-radius search. % \:} % % Generally, the default options can work well for typical cases. In % special cases, you can change some options with others left in default % value by only specifying the options you would like to change. % % - [nnidx, dists] = annquery(...) also returns the corresponding distance values. % % In the output, dists is a k x nq double matrix. dists(i, j) is the distance of % the j's query point's distance to its i-th neighbor. % % Since that nnidx(i, j) is the index of j's query point's i-th neighbor, % nnidx and dists are corresponding. % % - annquery -doc or annquery('-doc') shows the HTML help in the MATLAB % embeded browser. % % [ Remarks ] % - The function is based on a mex-wrapper (ann_mex.m in private folder) % of the Approximate Nearest Neighbors Library version 1.1.1. % % - It is strongly recommended to gather all queries together and conduct % the queries in batch. Since for each time this function is invoked, % it constructs the kd-tree from the reference points. Hence, it may % lead to considerable overhead if the queries are done one by one. % % - The found nearest points for each query point are sorted in ascending % order of distance. It means that the first result refers to the point % nearest to the query, while the second one refers to the second % nearest, and so on. % % - If fixed-radius scheme is used (set search_sch option to 'fr'), it % is probable that for some query points, there are less than k % neighbors within the specified range. % % For example, if k = 5, and there are only 2 neighbors in the % specified range for the i-th query, then nnidx(:, i) would be a % column, in which the first 2 entries are the indices of the two % nearest neighbors, while the last 3 entries are all zeros. % Correspondingly, the last 3 entries in dists(:, i) are all inf. % % To summarize, the function uses 0 to indicate that a neighbor is not % found, and uses inf to give the corresponding distance. This only % applies to fixed-radius scheme. (For other schemes, it is impossible % that the neighbors are not sufficient). % % - If fixed-radius search is used, it is required that a positive radius % be explicitly set. % % [ Examples ] % - For each of 100 points of 5 dimensions, find its 3 nearesr neighbors in % a reference set of 200 points, using default options. % \{ % Xq = rand(5, 100); % Xr = rand(5, 200); % % inds = annquery(Xr, Xq, 3); % \} % If you would like to get the corresponding Euclidean distances as % well, you can use the following command % \{ % [inds, dists] = annquery(Xr, Xq, 3); % \} % % - Use user-specified options. % \{ % % use priority search scheme with a sliding fair rule % inds = annquery(Xr, Xq, k, 'search_sch', 'pri', 'split', 'sl_fair'); % % % set positive error bound to allow some errors % % in order to increase efficiency % inds = annquery(Xr, Xq, k, 'eps', 0.1); % % % use fixed-radius search with all neighbors confined within % % a range of radius 0.08 % inds = annquery(Xr, Xq, k, 'search_sch', 'fr', 'radius', 0.08); % % % use bd-tree construction % inds = annquery(Xr, Xq, k, 'use_bdtree', true); % % % use bd-tree construction with centroid shrinking rule % inds = annquery(Xr, Xq, k, 'use_bdtree', true, 'shrink', 'centroid'); % \} % % - If you want to find neighbors for each point within the same point % set with the query point itself excluded from neighbor set. % \{ % [inds, dists] = annquery(X, X, k+1, ...); % % inds = inds(2:end, :); % dists = dists(2:end, :); % \} % % This simple way is based on the rationale that the query point itself % is the most nearest point to the query when searching in the same % set. It works in most cases. % % However, if there are two points reside in EXACTLY the same position, % then it is probable that another point in the same position is % removed while the query point remains. However, such circumstances % rarely happen in real data. % % [ History ] % - Created by Dahua Lin, on Jul 06, 2007 % %% For help if nargin == 1 && ischar(Xr) && strcmpi(Xr, '-doc') showdoc(mfilename('fullpath')); return; end %% parse and verify input arguments error(nargchk(3, inf, nargin)); % some predicates is_normal_matrix = @(x) isnumeric(x) && ndims(x) == 2 && isreal(x) && ~issparse(x); is_posint_scalar = @(x) isnumeric(x) && isscalar(x) && x == fix(x) && x > 0; is_switch = @(x) islogical(x) && isscalar(x); is_float_scalar = @(x) isfloat(x) && isscalar(x); % Xr and Xq require_arg(is_normal_matrix(Xr), 'Xr should be a full numeric real matrix'); require_arg(is_normal_matrix(Xq), 'Xq should be a full numeric real matrix'); [d, n] = size(Xr); % require_arg(size(Xq, 1) == d, 'The point dimensions in Xr and Xq are inconsistent.') % k require_arg(is_posint_scalar(k), 'k should be a positive integer scalar'); % require_arg(k <= n, 'The value k exceeds the number of reference points'); % options opts = struct( ... 'use_bdtree', false, ... 'bucket_size', 1, ... 'split', 'suggest', ... 'shrink', 'suggest', ... 'search_sch', 'std', ... 'eps', 0, ... 'radius', 0); if ~isempty(varargin) opts = setopts(opts, varargin{:}); end require_opt(is_switch(opts.use_bdtree), 'The option use_bdtree should be a logical scalar.'); require_opt(is_posint_scalar(opts.bucket_size), 'The option bucket_size should be a positive integer.'); split_c = get_name_code('splitting rule', opts.split, ... {'std', 'midpt', 'sl_midpt', 'fair', 'sl_fair', 'suggest'}); if opts.use_bdtree shrink_c = get_name_code('shrinking rule', opts.shrink, ... {'none', 'simple', 'centroid', 'suggest'}); else shrink_c = int32(0); end ssch_c = get_name_code('search scheme', opts.search_sch, ... {'std', 'pri', 'fr'}); require_opt(is_float_scalar(opts.eps) && opts.eps >= 0, ... 'The option eps should be a non-negative float scalar.'); use_fix_rad = strcmp(opts.search_sch, 'fr'); if use_fix_rad require_opt(is_float_scalar(opts.radius) && opts.radius > 0, ... 'The option radius should be a positive float scalar in fixed-radius search'); rad2 = opts.radius * opts.radius; else rad2 = 0; end %% main (invoking ann_mex) internal_opts = struct( ... 'use_bdtree', opts.use_bdtree, ... 'bucket_size', int32(opts.bucket_size), ... 'split', split_c, ... 'shrink', shrink_c, ... 'search_sch', ssch_c, ... 'knn', int32(k), ... 'err_bound', opts.eps, ... 'search_radius', rad2); [nnidx, dists] = ann_mex(Xr, Xq, internal_opts); nnidx = nnidx + 1; % from zero-based to one-based if nargout >= 2 dists = sqrt(dists); % from squared distance to euclidean if use_fix_rad dists(nnidx == 0) = inf; end end %% Auxiliary function function c = get_name_code(optname, name, names) require_opt(ischar(name), ['The option ' optname ' should be a string indicating a name.']); cidx = find(strcmp(name, names)); require_opt(~isempty(cidx), ['The option ' optname ' cannot be assigned to be ' name]); c = int32(cidx - 1); function require_arg(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidarg', msg); end function require_opt(cond, msg) if ~cond error('ann_mwrapper:annquery:invalidopt', msg); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
setopts.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/ANN/ann_mwrapper/private/setopts.m
6,161
utf_8
e1da88dc99b232199d5082bf6df84068
function opts = setopts(opts0, varargin) %SETOPTS Sets the options and makes the option-struct % % [ Syntax ] % - opts = setopts([], name1, value1, name2, value2, ...) % - opts = setopts([], {name1, value1, name2, value2, ...}) % - opts = setopts([], newopts) % - opts = setopts(opts0, ...) % % [ Arguments ] % - opts0: the original options % - namei: the i-th option name % - valuei: the value of the i-th option % - opts: the updated options % % [ Description ] % - opts = setopts([], name1, value1, name2, value2, ...) makes an % option structure using the name-value pairs. The names should be % all strings. % % The constructed structure will be like the following: % \{ % opts.name1 = value1 % opts.name2 = value2 % ... % \} % % - opts = setopts([], {name1, value1, name2, value2, ...}) makes an % option structure using the name-value pairs encapsulated in % a cell array. It is equivalent to the un-encapsulated form. % % - opts = setopts([], newopts) makes an option structure by copying % the fields in newopts. % % - opts = setopts(opts0, ...) updates the original structure opts0. % Suppose there is a name-value pair with name abc, then % - if opts0 has a field named abc, then opts.abc will be set to % the supplied value; % - if opts0 does not has a field named abc, then a new field will % be added to opts % - The remaining fields of opts0 that are not in the name-value % pairs will be copied to the opts using original values. % % [ Remarks ] % - The MATLAB builtin function struct can also make struct with name % value pairs. However, there are two significant differences: % # when the values are cell arrays, the function struct will build % a struct array and deal the values in the cell arrays to % multiple structs. While the function setopts will always make % a scalar struct, the value in cell form will be directly set % as the value of the corresponding field as a whole. % # The function setopts can make a new option structure by updating % an existing one. It is suitable to the cases that there is a set % of default options, and the user only wants to change some of % them without changing the other. The setopts function offers a % convenient way to tune a subset of options in the multi-option % applications. % % - In the name-value list, multiple items with the same name is allowed. % Under the circumstances, only the rightmost value takes effect. This % design facilitates the use of a chain of option-setters. Each setter % can simply make its changes by appending some name-value pairs, % thereby the last changes will finally take effect. % % [ Examples ] % - Construct default options and then update it % \{ % default_opts = setopts([], ... % 'timeout', 30, ... % 'method', 'auto', ... % 'acts', {'open', 'edit', 'close'} ); % % >> default_opts.timeout = 30 % default_opts.method = 'auto' % default_opts.acts = {'open', 'edit', 'close'} % % user_opts = setopts(default_opts, ... % 'timeout', 50, ... % 'acts', {'open', 'edit', 'submit', 'close'}, ... % 'info', 'something'); % % >> user_opts.timeout = 50 % user_opts.method = 'auto' % user_opts.acts = {'open', 'edit', 'submit', 'close'} % user_opts.info = 'something' % \} % % - Set options with a chain of name-value pairs % \{ % p1 = {'timeout', 30, 'method', 'auto'} % p2 = {'info', [1 2], 'timeout', 50} % p3 = {'keys', {'a', 'b'}, 'info', [10 20]} % % opts = setopts([], [p1, p2, p3]) % % >> opts.timeout = 50 % opts.method = 'auto' % opts.info = [10 20] % opts.keys = {'a', 'b'} % \} % % - Update a struct with another one % \{ % s0 = struct('handle', 1, 'width', 10, 'height', 20) % su = struct('width', 15, 'height', 25) % % s1 = setopts(s0, su) % % >> s1.handle = 1 % s1.width = 15 % s2.height = 25 % \} % % [ History ] % - Created by Dahua Lin, on Jun 28, 2007 % %% parse and verify input arguments if isempty(opts0) opts = []; elseif isstruct(opts0) && isscalar(opts0) opts = opts0; else error('dmtoolbox:setopts:invalidarg', ... 'opts0 should be either a struct scalar or empty.'); end if nargin > 1 fparam = varargin{1}; if isstruct(fparam) if nargin > 2 error('dmtoolbox:setopts:invalidarg', ... 'No input arguments are allowed to follow the struct parameter'); end params = fparam; elseif iscell(fparam) if nargin > 2 error('dmtoolbox:setopts:invalidarg', ... 'No input arguments are allowed to follow the cell parameter'); end params = fparam; elseif ischar(fparam) params = varargin; else error('dmtoolbox:setopts:invalidarg', 'The input argument list is illegal.'); end else return; end %% main delegate if iscell(params) opts = setopts_with_cell(opts, params); else opts = setopts_with_struct(opts, params); end %% core functions function opts = setopts_with_cell(opts, params) names = params(1:2:end); values = params(2:2:end); n = length(names); if length(values) ~= n error('dmtoolbox:setopts:invalidarg', 'The names and values should form pairs'); end for i = 1 : n opts.(names{i}) = values{i}; end function opts = setopts_with_struct(opts, params) fns = fieldnames(params); n = length(fns); for i = 1 : n fn = fns{i}; opts.(fn) = params.(fn); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
graphViz4MatlabNode.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/graphViz4Matlab/util/graphViz4MatlabNode.m
11,839
utf_8
4a774ab6d3af22480ff6713e3c681d91
classdef graphViz4MatlabNode < dynamicprops & hgsetget % This class represents a drawable node in an arbitrary graph. % % Public properties can be set using the standard Matlab set method as in % set(node,'curvature',[0,0],'linesytle','--','linecolor','g'). Call % node.redraw to redraw it after changing properties. % % Nodes are not really designed to live on their own, they should be % aggregated into a graph object responsible for layout. % % Matthew Dunham % University of British Columbia % http://www.cs.ubc.ca/~mdunham/ properties label; % displayed name for the node splitLabel; % label split in the middle useFullLabel = false; % if true, the full non-split label is used regardles of how long it is. description = ''; % text displayed when you click on the node curvature = [1 1]; % curvature of the node, [1,1] = circle lineStyle = '-'; % line style for the node lineWidth = 2; % line wdth for the node inedges = []; % indices of edges in outedges = []; % indices of edges out fontSize = 12; % The font size for the node showFullLabel = false; % If true, node labels are not split onto multiple lines regardelss of how long end properties % Color properties lineColor = 'k'; % line color for the node selectedColor = [1 1 0.7]; % face color when selected with mouse faceColor = [1 1 0.8]; % face color when not shaded shadedColor = 'r'; % color when shaded, call shade() to shade textColor = 'k'; % label's text color containingGraph = []; % containing graph object end properties(GetAccess = 'public', SetAccess = 'protected') % Read only properties xpos = 0; % x-coordinate of node center relative to parent axes ypos = 0; % y-coordinate of node center relative to parent axes isvisible = false; % true iff the node is being displayed isshaded = false; % is the node shaded or not? width = 1; % width in data units height = 1; % height in data units end properties(GetAccess = 'public', SetAccess = 'protected') % Handles to underlying Matlab graphics objects rechandle = []; % handle to the underlying rectangle object labelhandle = []; % handle to the underlying text object parent = []; % handle to the parent axes object isselected = false; % true iff, the node has been selected end methods function obj = graphViz4MatlabNode(label) % Node Constructor obj.label = label; obj.setSplitLabel(label); end function draw(obj,parent) % Draw the node on the specified parent axes. If no parent is % specified, the current axis is used. if(obj.isvisible) warning('GRAPHNODE:draw',['Node ',obj.label,' is already drawn, call redraw().']); return; end if(nargin < 2) if(isempty(obj.parent) || ~ishandle(obj.parent)) obj.parent = gca; end else obj.parent = parent; end obj.drawNode(); obj.setText(); obj.isvisible = true; end function redraw(obj) % Redraw the node, (must be called after node properties are % changed). if(obj.isvisible), obj.erase;end obj.draw(); end function erase(obj) % Erase the node but do not delete it if(~obj.isvisible) warning('GRAPHNODE:erase',['Node ',obj.label,' is already erased']); return; end delete(obj.rechandle); delete(obj.labelhandle); obj.rechandle = []; end function shade(obj,color) % Shade the node the specified color. The default color is used if % none given. obj.isshaded = true; if(nargin == 2) obj.shadedColor = color; end if(obj.isvisible) set(obj.rechandle,'FaceColor',obj.shadedColor); end end function unshade(obj) % Unshade the node obj.isshaded = false; if(obj.isvisible) set(obj.rechandle,'FaceColor',obj.faceColor); end end function resize(obj,width,height) % Resize the node by the specified proportion if(nargin < 3) if(~isempty(obj.containingGraph)) height = width; end end obj.width = width; obj.height = height; if(obj.isvisible), obj.redraw; end end function move(obj,x,y) % Move the node's center to the new x,y coordinates, (relative to % the parent axes.) obj.xpos = x; obj.ypos = y; if(obj.isvisible),obj.redraw;end end function select(obj) % Call this function to set the node in a selected state. obj.isselected = true; if(obj.isvisible) set(obj.rechandle,'faceColor',obj.selectedColor); end end function deselect(obj) % Call this function to deselect the node. obj.isselected = false; if(obj.isvisible) obj.redraw; end end end % end of public methods methods(Access = 'protected') function nodePressed(obj,varargin) % This function is called whenever the node is pressed. if(~isempty(obj.containingGraph)) obj.containingGraph.nodeSelected(obj); end end function nodeDeleted(obj) % This function is called whenver the node is deleted, (perhaps % because the figure window was closed for instance). obj.isvisible = false; obj.parent = []; end function drawNode(obj) % Draw the actual node recxpos = obj.xpos - obj.width/2; recypos = obj.ypos - obj.height/2; lineColor = obj.lineColor; lineWidth = obj.lineWidth; if(obj.isselected) color = obj.selectedColor; lineColor = 'r'; lineWidth = 1.5*lineWidth; elseif(obj.isshaded) color = obj.shadedColor; else color = obj.faceColor; end obj.rechandle = rectangle(... 'Parent' ,obj.parent ,... 'Position' ,[recxpos,recypos,obj.width,obj.height] ,... 'Curvature' ,obj.curvature ,... 'LineWidth' , lineWidth ,... 'LineStyle' ,obj.lineStyle ,... 'EdgeColor' ,lineColor ,... 'faceColor' ,color ,... 'DisplayName' ,obj.label ,... 'Tag' ,obj.label ,... 'ButtonDownFcn',@obj.nodePressed ,... 'UserData' ,obj ,... 'DeleteFcn' ,@(varargin)obj.nodeDeleted() ); end function setText(obj) % Draw the node's label if((length(obj.label) < 10) || obj.useFullLabel || obj.showFullLabel) label = obj.label; else label = obj.splitLabel; end obj.labelhandle = text(obj.xpos,obj.ypos,label ,... 'FontUnits' , 'points' ,... 'HitTest' , 'off' ,... 'FontWeight' , 'demi' ,... 'Margin' , 0.01 ,... 'HorizontalAlignment' , 'center' ,... 'BackGroundColor' , 'none' ,... 'Selected' , 'off' ,... 'VerticalAlignment' , 'middle' ,... 'LineStyle' , 'none' ,... 'FontSize' , obj.fontSize ,... 'Color' , obj.textColor ); if(obj.useFullLabel) set(obj.labelhandle,'BackgroundColor',obj.selectedColor,'Margin',6,'EdgeColor','k','LineStyle','-'); end end function resizeText(obj) % Resize the text to fill the node (too slow for large graphs) fontsize = obj.maxFontSize; set(obj.labelhandle,'FontSize',fontsize); extent = get(obj.labelhandle,'Extent'); while((extent(1) < (obj.xpos - obj.width/2)) || (extent(2)+(extent(4)) > (obj.ypos + obj.height/2))) fontsize = 0.95*fontsize; set(obj.labelhandle,'FontSize',fontsize); extent = get(obj.labelhandle,'Extent'); end end function setSplitLabel(obj,label) obj.splitLabel = splitString(label,8,10); end end % end of protected methods end % end of graphnode class %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function S = splitString(varargin) % Split a string into multiple lines based on camel case. % % Inputs % % '-S' the string to split % '-minSize' does not split at all if length(S) < minSize % '-maxSize' splits no matter what, (even if no camel case change) if length(S) > maxSize % '-center' if true, [default], the string is center justified % '-cellMode' if true, a cell array of strings is returned, instead of a char array. [S,minSize,maxSize,cellMode,center] = processArgs(varargin,'*+-S','','-minSize',8,'-maxSize',10,'-cellMode',false,'-center',true); S = splitInTwo(S); if center S = strjust(S,'center'); end if cellMode S = cellstr(S); end function str = splitInTwo(str) % recursively split a string into two based on camel case isupper = isstrprop(str(2:end),'upper'); if(size(str,2) >= minSize && any(isupper)) first = find(isupper); first = first(1); top = str(1:first); bottom = str(first+1:end); str = strvcat(splitInTwo(top),splitInTwo(bottom)); %#ok elseif(size(str,2) > maxSize) top = [str(1:floor(length(str)/2)),'-']; bottom = str(floor(length(str)/2)+1:end); str = strvcat(splitInTwo(top),splitInTwo(bottom)); %#ok end end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
processArgs.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/graphViz4Matlab/util/processArgs.m
15,869
utf_8
0a862d38f194e4158c4b65d3f6642328
function varargout = processArgs(userArgs, varargin) % Process function arguments, allowing args to be passed by % the user either as name/value pairs, or positionally, or both. % % This function also provides optional enforcement of required inputs, and % optional type checking. Argument names must start with the '-' % character and not precede any positional arguments. % % Matthew Dunham % University of British Columbia % Last updated January 14th, 2010 % %% USAGE: % % [out1,out2,...,outN] = processArgs(userArgs ,... % '-name1' , default1 ,... % '-name2' , default2 ,... % '-nameN' , defaultN ); % % The 'userArgs' input is a cell array and in normal usage is simply the % varargin cell array from the calling function. It contains 0 to N values % or 0 to N name/value pairs. It may also contain a combination of % positional and named arguments as long as no named argument precedes a % positional one. % % Note, this function is CASE INSENSITIVE. % %% ENFORCING REQUIRED ARGUMENTS % % To ensure that certain arguments are passed in, (and error if not), add a % '*' character to the corresponding name as in % % [out1,...] = processArgs(userArgs,'*-name1',default1,... % % % Providing empty values, (e.g. {},[],'') for required arguments also % errors unless these were explicitly passed as named arguments. %% TYPE CHECKING % % To enforce that the input type, (class) is the same type as the default % value, add a '+' character to the corresponding name as in % % [out1,...] = processArgs(userArgs,'+-name1',default1,... % % '+' and '*' can be combined as in % % [out1,...] = processArgs(userArgs,'*+-name1',default1,... % % or equivalently % % [out1,...] = processArgs(userArgs,'+*-name1',default1,... %% OTHER CONSIDERATIONS % % If the user passes in arguments in positional mode, and uses [], {}, or % '' as place holders, the default values are used in their place. When the % user passes in values via name/value pairs, this behavior does not % occur; the explicit value the user specified, (even if [], {}, '') is % always used. % %% ADVANCED % The programmer must specify the same number of output arguments as % possible input arguments, OR exactly one output. If exactly one output % is used, the outputs are all bundled into a single cell array and % returned with each arg value preceded by its name. This can be useful for % relaying some or all of the arguments to subsequent functions as is done % with the extractArgs function. % %% DEPENDENCIES % % None % %% EXAMPLES % These are all valid usages. Note that here the first and second arguments % are required and the types of the second and fourth arguments are % checked. % % outerFunction(obj,... % '-first' , 1 ,... % '-second' , MvnDist() ,... % '-third' , 22 ,... % '-fourth' , 10 ); % % outerFunction(obj,'-fourth',3,'-second',MvnDist(),'-first',12); % outerFunction(obj,1,MvnDist(),3); % outerFunction(obj,1,MvnDist(),3,[]); % outerFunction(obj,'-first',1,'-second',DiscreteDist(),'-third',[]); % outerFunction(obj,1,MvnDist(),'-fourth',10); % % % function [a,b,c,d] = outerFunction(obj,varargin) % [a,b,c,d] = processArgs(varargin ,... % '*-first' , [] ,... % '*+-second' , MvnDist() ,... % '-third' , 18 ,... % '+-fourth' , 23 ); % end %% CONSTANTS PREFIX = '-'; % prefix that must precede the names of arguments. REQ = '*'; % require the argument TYPE = '+'; % check the type of the arg against the default type % set to true for more exhaustive error checking or false for faster % execution. FULL_ERROR_CHECK = true; %% PROCESS VARARGIN - PASSED BY PROGRAMMER %% Check Initial Inputs if ~iscell(userArgs) ,throwAsCaller(MException('PROCESSARGS:noUserArgs','PROGRAMMER ERROR - you must pass in the user''s arguments in a cell array as in processArgs(varargin,''-name'',val,...)'));end if isempty(varargin) ,throwAsCaller(MException('PROCESSARGS:emptyVarargin','PROGRAMMER ERROR - you have not passed in any name/default pairs to processArgs')); end %% Extract Programmer Argument Names and Markers progArgNames = varargin(1:2:end); maxNargs = numel(progArgNames); required = cellfun(@(c)any(REQ==c(1:min(3,end))),progArgNames); typecheck = cellfun(@(c)any(TYPE==c(1:min(3,end))),progArgNames); if ~iscellstr(progArgNames) ,throwAsCaller(MException('PROCESSARGS:notCellStr ',sprintf('PROGRAMMER ERROR - you must pass to processArgs name/default pairs'))); end %% Remove * and + Markers try progArgNames(required | typecheck) = ... cellfuncell(@(c)c(c~=REQ & c~=TYPE) ,... progArgNames(required | typecheck)); catch ME if strcmp(ME.identifier,'MATLAB:UndefinedFunction') err = MException('PROCESSARGS:missingExternalFunctions','ProcessArgs requires the following external functions available in PMTK2: catString, cellfuncell, interweave, isprefix. Please add these to your MATLAB path.'); throw(addCause(err,ME)); else rethrow(ME); end end %% Set Default Values defaults = varargin(2:2:end); varargout = defaults; %% Check Programmer Supplied Arguments if mod(numel(varargin),2) ,throwAsCaller(MException('PROCESSARGS:oddNumArgs',sprintf('PROGRAMMER ERROR - you have passed in an odd number of arguments to processArgs, which requires name/default pairs'))); end if any(cellfun(@isempty,progArgNames)) ,throwAsCaller(MException('PROCESSARGS:emptyStrName ',sprintf('PROGRAMMER ERROR - empty-string names are not allowed')));end if nargout ~= 1 && nargout ~= maxNargs ,throwAsCaller(MException('PROCESSARGS:wrongNumOutputs',sprintf('PROGRAMMER ERROR - processArgs requires the same number of output arguments as named/default input pairs'))); end if ~isempty(PREFIX) && ... ~all(cellfun(@(c)~isempty(c) &&... c(1)==PREFIX,progArgNames)) throwAsCaller(MException('PROCESSARGS:missingPrefix',sprintf('PROGRAMMER ERROR - processArgs requires that each argument name begin with the prefix %s',PREFIX))); end if FULL_ERROR_CHECK && ... numel(unique(progArgNames)) ~= numel(progArgNames) ,throwAsCaller(MException('PROCESSARGS:duplicateName',sprintf('PROGRAMMER ERROR - you can not use the same argument name twice')));end %% PROCESS USERARGS %% Error Check User Args if numel(userArgs) == 0 && nargout > 1 if any(required) ,throwAsCaller(MException('PROCESSARGS:missingReqArgs',sprintf('The following required arguments were not specified:\n%s',catString(progArgNames(required))))); else return; end end if FULL_ERROR_CHECK % slow, but helpful in transition from process_options to processArgs % checks for missing '-' if ~isempty(PREFIX) userstrings = lower(... userArgs(cellfun(@(c)ischar(c) && size(c,1)==1,userArgs))); problem = ismember(... userstrings,cellfuncell(@(c)c(2:end),progArgNames)); if any(problem) if sum(problem) == 1, warning('processArgs:missingPrefix','The specified value ''%s'', matches an argument name, except for a missing prefix %s. It will be interpreted as a value, not a name.',userstrings{problem},PREFIX) else warning('processArgs:missingPrefix','The following values match an argument name, except for missing prefixes %s:\n\n%s\n\nThey will be interpreted as values, not names.',PREFIX,catString(userstrings(problem))); end end end end %% Find User Arg Names userArgNamesNDX = find(cellfun(@(c)ischar(c) &&... ~isempty(c) &&... c(1)==PREFIX,userArgs)); %% Check User Arg Names if ~isempty(userArgNamesNDX) && ... ~isequal(userArgNamesNDX,userArgNamesNDX(1):2:numel(userArgs)-1) if isempty(PREFIX), throwAsCaller(MException('PROCESSARGS:missingVal',sprintf('\n(1) every named argument must be followed by its value\n(2) no positional argument may be used after the first named argument\n'))); else throwAsCaller(MException('PROCESSARGS:posArgAfterNamedArg',sprintf('\n(1) every named argument must be followed by its value\n(2) no positional argument may be used after the first named argument\n(3) every argument name must begin with the ''%s'' character\n(4) values cannot be strings beginning with the %s character\n',PREFIX,PREFIX))); end end if FULL_ERROR_CHECK && ... ~isempty(userArgNamesNDX) && ... numel(unique(userArgs(userArgNamesNDX))) ~= numel(userArgNamesNDX) throwAsCaller(MException('PROCESSARGS:duplicateUserArg',sprintf('You have specified the same argument name twice'))); end %% Extract Positional Args argsProvided = false(1,maxNargs); if isempty(userArgNamesNDX) positionalArgs = userArgs; elseif userArgNamesNDX(1) == 1 positionalArgs = {}; else positionalArgs = userArgs(1:userArgNamesNDX(1)-1); end %% Check For Too Many Inputs if numel(positionalArgs) + numel(userArgNamesNDX) > maxNargs ,throwAsCaller(MException('PROCESSARGS:tooManyInputs',sprintf('You have specified %d too many arguments to the function',numel(positionalArgs)+numel(userArgNamesNDX)- maxNargs)));end %% Process Positional Args for i=1:numel(positionalArgs) % don't overwrite default value if positional arg is % empty, i.e. '',{},[] if ~isempty(userArgs{i}) argsProvided(i) = true; if typecheck(i) && ~isa(userArgs{i},class(defaults{i})) ,throwAsCaller(MException('PROCESSARGS:argWrongType',sprintf('Argument %d must be of type %s',i,class(defaults{i})))); end varargout{i} = userArgs{i}; end end %% Process Named Args userArgNames = userArgs(userArgNamesNDX); userProgMap = zeros(1,numel(userArgNames)); usedProgArgNames = false(1,numel(progArgNames)); for i=1:numel(userArgNames) for j=1:numel(progArgNames) if ~usedProgArgNames(j) && strcmpi(userArgNames{i},progArgNames{j}) userProgMap(i) = j; usedProgArgNames(j) = true; break; end end end %% Error Check User Args if any(~userProgMap) ,throwAsCaller(MException('PROCESSARGS:invalidArgNames',sprintf('The following argument names are invalid: %s',catString(userArgNames(userProgMap == 0),' , ')))); end if any(userProgMap <= numel(positionalArgs)) ,throwAsCaller(MException('PROCESSARGS:bothPosAndName' ,sprintf('You cannot specify an argument positionally, and by name in the same function call.')));end %% Extract User Values userValues = userArgs(userArgNamesNDX + 1); %% Type Check User Args if any(typecheck) for i=1:numel(userArgNamesNDX) if typecheck(userProgMap(i)) && ... ~isa(userArgs{userArgNamesNDX(i)+1},... class(defaults{userProgMap(i)})) throwAsCaller(MException('PROCESSARGS:wrongType',sprintf('Argument %s must be of type %s',userArgs{userArgNamesNDX(i)},class(defaults{userProgMap(i)})))); end end end varargout(userProgMap) = userValues; %% Check Required Args argsProvided(userProgMap) = true; if any(~argsProvided & required) ,throwAsCaller(MException('PROCESSARGS:emptyVals',sprintf('The following required arguments were either not specified, or were given empty values:\n%s',catString(progArgNames(~argsProvided & required))))); end %% Relay Mode if nargout == 1 && (numel(varargin) > 2 || (numel(varargin) == 1 && isprefix('-',varargin{1}))) varargout = {interweave(progArgNames,varargout)}; end end function s = catString(c,delim) % Converts a cell array of strings to a single string, (i.e. single-row % character array). The specified delimiter, delim, is added between each % entry. Include any spaces you want in delim. If delim is not specified, % ', ' is used instead. If c is already a string, it is just returned. If c % is empty, s = ''. % % EXAMPLE: % % s = catString({'touch /tmp/foo';'touch /tmp foo2';'mkdir /tmp/test'},' && ') % s = % touch /tmp/foo && touch /tmp foo2 && mkdir /tmp/test if nargin == 0; s = ''; return; end if ischar(c), s=c; if strcmp(s,','),s = '';end return; end if isempty(c),s=''; return;end if nargin < 2, delim = ', '; end s = ''; for i=1:numel(c) s = [s, rowvec(c{i}),rowvec(delim)]; %#ok end s(end-numel(delim)+1:end) = []; if strcmp(s,','),s = '';end end function out = cellfuncell(fun, C, varargin) out = cellfun(fun, C, varargin{:},'UniformOutput',false); end function C = interweave(A,B) % If A, B are two cell arrays of length N1, N2, C is a cell array of length % N1 + N2 where where C(1) = A(1), C(2) = B(1), C(3) = A(2), C(4) = B(2), ... etc % Note, C is always a row vector. If one cell array is longer than the % other the remaining elements of the longer cell array are added to the % end of C. A and B are first converted to column vectors. A = A(:); B = B(:); C = cell(length(A)+length(B),1); counter = 1; while true if ~isempty(A) C(counter) = A(1); A(1) = []; counter = counter + 1; end if ~isempty(B) C(counter) = B(1); B(1) = []; counter = counter + 1; end if isempty(A) && isempty(B) break; end end C = C'; end function p = isprefix(short,long) % ISPREFIX Tests if the first arg is a prefix of the second. % The second arg may also be a cell array of strings, in which case, each % is tested. CASE SENSITIVE! % % If the second argument is not a string, p = false, it does not error. % % EXAMPLES: % % isprefix('foo','foobar') % ans = % 1 % %isprefix('test_',{'test_MvnDist','test_DiscreteDist','UnitTest'}) %ans = % 1 1 0 error(nargchk(2,2,nargin)); if ischar(long) p = strncmp(long,short,length(short)); elseif iscell(long) p = cellfun(@(c)isprefix(short,c),long); else p = false; end end function x = rowvec(x) x = x(:)'; end function x = colvec(x) x = x(:); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
glob.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/lightspeed/glob.m
3,690
utf_8
67bb3d6d7fb4a23bc9281238514c1562
function [names,isdirs] = glob(pattern,prefix) %GLOB Filename expansion via wildcards. % GLOB(PATTERN) returns a cell array of file/directory names which match the % PATTERN. % [NAMES,ISDIRS] = GLOB(PATTERN) also returns a logical vector indicating % which are directories. % % Two types of wildcards are supported: % * matches zero or more characters, besides / % ** matches zero or more characters, including /, ending with a / % *** is interpreted as ** followed by *, which means it matches zero or % more characters, including / % % For example, 'a*b' matches 'ab','acb','acdb', but not 'a/b'. % 'a**b' matches 'ab','a/b','ac/b','ac/d/b', but not 'acb' or 'a/cb'. % 'a***b' matches all of the above plus 'a/cb','ac/d/cb',etc. % % 'a//b' is not considered a valid filename, so 'a/*/b' will not return % 'a//b' or 'a/b'. % % Examples: % % if 'work' is a subdirectory, this returns only 'work', not its contents: % glob('work') % % returns 'work/fun.m' (not 'fun.m'): % glob('work/fun.m') % % all m-files in 'work', prefixed with 'work/': % glob('work/*.m') % % all files named 'fun.m' in 'work' or any subdirectory of 'work': % glob('work/**fun.m') % % all m-files in 'work' or any subdirectory of 'work': % glob('work/***.m') % % all files named 'fun.m' any subdirectory of 'work' (but not 'work'): % glob('work/**/fun.m') % % all files named 'fun.m' in any subdirectory of '.': % glob('**fun.m') % % all files in all subdirectories: % glob('***') % % See also globstrings. % Written by Tom Minka, 28-Apr-2004 (revised 2007) % (c) Microsoft Corporation. All rights reserved. if nargin < 2 prefix = ''; end names = {}; isdirs = []; if isempty(pattern) return end % break the pattern into path components [first,rest] = strtok(pattern,'/'); % when recursing, remove the leading / from rest if ~isempty(rest) rest = rest(2:end); end % special case for absolute paths if pattern(1) == '/' prefix = '/'; end % absolute path tests: % glob('/*.sys') % glob('/sho/**/*.sln') % glob('/sho***.sln') i = strfind(first,'**'); if ~isempty(i) % double-star pattern i = i(1); % process first occurrence rest = fullfile(first((i+2):end),rest); first = first(1:(i-1)); new_pattern = [first rest]; % if the pattern was 'a**b/c', new_pattern is 'ab/c' [names,isdirs] = glob(new_pattern,prefix); first = [first '*']; rest = ['**' rest]; % if the pattern was 'a**b/c', it is now 'a*/**b/c' end % expand the first component fullfirst = fullfile(prefix,first); if ~iswild(fullfirst) & isdir(fullfirst) first_files = struct('name',first,'isdir',1); else first_files = stripdots(dir(fullfirst)); end % for each match, add it to the results or recurse on the rest of the pattern for i = 1:length(first_files) new_prefix = fullfile(prefix,first_files(i).name); if isempty(rest) names{end+1} = new_prefix; isdirs(end+1) = first_files(i).isdir; elseif first_files(i).isdir [new_names, new_isdirs] = glob(rest,new_prefix); names = cellcat(names, new_names); isdirs = [isdirs; new_isdirs]; end end names = names(:); isdirs = isdirs(:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function files = stripdots(files) % omit . and .. from the results of DIR names = {files.name}; ok = (~strcmp(names,'.') & ~strcmp(names,'..')); files = files(ok); function c = cellcat(c,c2) c = {c{:} c2{:}}; function tf = iswild(pattern) tf = ~isempty(strfind(pattern,'*')); function s = regexp_quote(s) regexprep(s,'[!#]^','#^'); regexprep(s,'[!#]$','#$');
github
umariqb/3D_Pose_Estimation_CVPR2016-master
flops_pow.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/lightspeed/flops_pow.m
1,432
utf_8
5843823015471636d6d1b205800ac1fb
function f = flops_pow(a) % FLOPS_POW Flops for raising to real power. % FLOPS_POW(A) returns the number of flops for (X .^ A) where X is scalar. % Powers like 0, 1, 2, and 1/2 are handled specially. flops_div = 8; flops_sqrt = 8; if nargin < 1 a = 0.1; end f = 0; if a < 0 f = f + flops_div; a = -a; end if a == 0 || a == 1 return; end if fix(a) == a % number of multiplications to raise to integer power f = f + floor(log2(a)) + num_bits(a)-1; elseif a == 1/2 % sqrt is built-in function f = f + flops_sqrt; elseif fix(2*a) == 2*a % this handles flops_pow(1/2+1) f = f + flops_pow(2*a) - 1 + flops_sqrt; elseif a == 1/4 f = f + 2*flops_sqrt; elseif a == 3/4 f = f + 2*flops_sqrt+1; elseif fix(4*a) == 4*a % this handles flops_pow(1/4+1) f = f + flops_pow(2*a) - 1 + flops_sqrt; else f = Inf; end % The identities % exp(a) = e^a % a^b = exp(b*log(a)) % require that % flops_exp < flops_pow < flops_exp+flops_log+1. % But in practice, I find that the runtime exceeds this upper bound. f_upper = 61; % flops_exp+flops_log+1 if f > f_upper f = f_upper; end function b = num_bits(x) % Returns the number of 1 bits in the binary representation of x. % x must be a non-negative integer. % lookup table for 0-15 bits = [0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4]; b = 0; while(x > 0) b = b + bits(mod(x,16)+1); x = floor(x/16); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
duplicated.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/lightspeed/duplicated.m
1,440
utf_8
af1b5fe0787eb874aa6ca5df411128be
function d = duplicated(x) %DUPLICATED Find duplicated rows. % DUPLICATED(x) returns a vector d such that d(i) = 1 if x(i,:) is a % duplicate of an earlier row. % % Examples: % duplicated([2 7 8 7 1 2 8]') = [0 0 0 1 0 1 1]' % duplicated([0 0 1 1 0; 0 1 0 1 1]') = [0 0 0 0 1]' % duplicated(eye(100)) % duplicated(kron((1:3)',ones(3))) % % You can simulate unique(x) or unique(x,'rows') by x(~duplicated(x)). % The difference is that the latter form will not sort the contents of x, % as unique will. % % See also UNIQUE. % (c) Microsoft Corporation. All rights reserved. % This function is not well optimized. % In particular, it is slower than unique. [nr,nc] = size(x); if nc == 1 d = duplicated1(x); return; end if nr == 1 d = 0; return; end hash = x*rand(nc,1); [dummy,ord] = sort(hash); xo = x(ord,:); %d = [0 all(diff(xo)==0,2)']; d = [0 all(xo(1:end-1,:)==xo(2:end,:),2)']; dd = diff([d 0]); dstart = find(dd > 0); dend = find(dd < 0); % loop each run of duplicated columns for i = 1:length(dstart) % place the zero at the first element in the original order d(dstart(i)) = 1; d(dstart(i)-1 + argmin(ord(dstart(i):dend(i)))) = 0; end d(ord) = d; d = d'; %d = duplicated1(hash); function d = duplicated1(x) % special case where x is a column vector. [s,ord] = sort(x); d = zeros(size(x)); d(ord) = [0; s(1:end-1)==s(2:end)]; %d(ord) = [0; diff(s)==0];
github
umariqb/3D_Pose_Estimation_CVPR2016-master
subsasgn.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/lightspeed/@mutable/subsasgn.m
1,488
utf_8
44c7dae848f5b621b638053c1b231e87
function mut = subsasgn(mut,index,v) % Written by Tom Minka % (c) Microsoft Corporation. All rights reserved. subsasgnJava(mut.obj,index,v,mut.cl); function subsasgnJava(jv,index,v,cl) if nargin < 4 % class(jv) is expensive, so we do it only once cl = class(jv); end if strcmp(cl,'java.util.Hashtable') % don't bother checking the type %if strcmp(index(1).type,'.') f = index(1).subs; if length(index) > 1 jv = jv.get(f); if isempty(jv) error(sprintf('Reference to non-existent field ''%s''.',f)); end % recurse on remaining subscripts subsasgnJava(jv,index(2:end),v); else if ~jv.containsKey(f) % add a new field jv.get('_fields').addElement(f); end jv.put(f,toJava(v)); end return elseif strcmp(cl,'java.lang.Double[][]') | strcmp(cl,'java.lang.Object[][]') if length(index(1).subs) == 1 % convert single index to a full index i = index(1).subs{1}; if length(i) > 1 error('a single array of indices is not supported'); end s = sizeJava(jv); index(1).subs = num2cell(ind2subv(s,i),1); end if strcmp(cl,'java.lang.Object[][]') % cell array if strcmp(index(1).type,'{}') index(1).type = '()'; end end % fall through elseif strcmp(cl,'java.util.Vector') | strcmp(cl,'java.util.BitSet') % empty array error('Index exceeds matrix dimensions.'); end % use built-in subsasgn subsasgn(jv,index,toJava(v));
github
umariqb/3D_Pose_Estimation_CVPR2016-master
subsref.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/lightspeed/@mutable/subsref.m
1,686
utf_8
9b67e3386d0641a031d3e3d3761a81dc
function v = subsref(mut,index) % Written by Tom Minka % (c) Microsoft Corporation. All rights reserved. v = subsrefJava(mut.obj,index,mut.cl); function v = subsrefJava(jv,index,cl) if nargin < 3 % class(jv) is expensive, so we do it only once cl = class(jv); end wantcell = 0; if strcmp(cl,'java.util.Hashtable') % don't bother checking the type %if strcmp(index(1).type,'.') f = index(1).subs; v = jv.get(f); if isempty(v) error(sprintf('Reference to non-existent field ''%s''.',f)); end elseif strcmp(cl,'java.lang.Double[][]') | strcmp(cl,'java.lang.Object[][]') if length(index(1).subs) == 1 % convert single index to a full index i = index(1).subs{1}; if length(i) > 1 error('a single array of indices is not supported'); end s = sizeJava(jv); index(1).subs = num2cell(ind2subv(s,i),1); end if strcmp(cl,'java.lang.Object[][]') % cell array if strcmp(index(1).type,'{}') index(1).type = '()'; else % type is '()' for a cell array wantcell = 1; % if the subscript has more than one element, the result will already % be a cell array for i = index(1).subs if length(i{1}) > 1 wantcell = 0; break end end end end v = subsref(jv,index(1)); elseif strcmp(cl,'java.util.Vector') | strcmp(cl,'java.util.BitSet') % empty array error('Index exceeds matrix dimensions.'); else % use built-in subsref v = subsref(jv,index(1)); end if length(index) > 1 % recurse on remaining subscripts v = subsrefJava(v,index(2:end)); else v = fromJava(v); if wantcell v = {v}; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
test_sameobject.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/lightspeed/tests/test_sameobject.m
263
utf_8
8705f5d46d51edcdc06e7272b4504f75
function test_sameobject % Result should be 1 in both cases below. a = rand(4); b = a; if sameobject(a,b) ~= 1 error('failed'); end if helper(a,a) ~= 1 error('failed'); end disp('Test passed.') function x = helper(a,b) x = sameobject(a,b);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
gauher.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/gpml-matlab/gpml/gauher.m
2,235
utf_8
470f2e21a6e4f909868c550b5fe4637f
% compute abscissas and weight factors for Gaussian-Hermite quadrature % % CALL: [x,w]=gauher(N) % % x = base points (abscissas) % w = weight factors % N = number of base points (abscissas) (integrates a (2N-1)th order % polynomial exactly) % % p(x)=exp(-x^2/2)/sqrt(2*pi), a =-Inf, b = Inf % % The Gaussian Quadrature integrates a (2n-1)th order % polynomial exactly and the integral is of the form % b N % Int ( p(x)* F(x) ) dx = Sum ( w_j* F( x_j ) ) % a j=1 % % this procedure uses the coefficients a(j), b(j) of the % recurrence relation % % b p (x) = (x - a ) p (x) - b p (x) % j j j j-1 j-1 j-2 % % for the various classical (normalized) orthogonal polynomials, % and the zero-th moment % % 1 = integral w(x) dx % % of the given polynomial's weight function w(x). Since the % polynomials are orthonormalized, the tridiagonal matrix is % guaranteed to be symmetric. function [x,w]=gauher(N) if N==20 % return precalculated values x=[ -7.619048541679757;-6.510590157013656;-5.578738805893203; -4.734581334046057;-3.943967350657318;-3.18901481655339 ; -2.458663611172367;-1.745247320814127;-1.042945348802751; -0.346964157081356; 0.346964157081356; 1.042945348802751; 1.745247320814127; 2.458663611172367; 3.18901481655339 ; 3.943967350657316; 4.734581334046057; 5.578738805893202; 6.510590157013653; 7.619048541679757]; w=[ 0.000000000000126; 0.000000000248206; 0.000000061274903; 0.00000440212109 ; 0.000128826279962; 0.00183010313108 ; 0.013997837447101; 0.061506372063977; 0.161739333984 ; 0.260793063449555; 0.260793063449555; 0.161739333984 ; 0.061506372063977; 0.013997837447101; 0.00183010313108 ; 0.000128826279962; 0.00000440212109 ; 0.000000061274903; 0.000000000248206; 0.000000000000126 ]; else b = sqrt( (1:N-1)/2 )'; [V,D] = eig( diag(b,1) + diag(b,-1) ); w = V(1,:)'.^2; x = sqrt(2)*diag(D); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
approxEP.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/gpml-matlab/gpml/approxEP.m
5,097
utf_8
b787297e5f04f6d89e6fc5e602ee76a1
function [alpha, sW, L, nlZ, dnlZ] = approxEP(hyper, covfunc, lik, x, y) % Expectation Propagation approximation to the posterior Gaussian Process. % The function takes a specified covariance function (see covFunction.m) and % likelihood function (see likelihoods.m), and is designed to be used with % binaryGP.m. See also approximations.m. In the EP algorithm, the sites are % updated in random order, for better performance when cases are ordered % according to the targets. % % Copyright (c) 2006, 2007 Carl Edward Rasmussen and Hannes Nickisch 2007-07-24 persistent best_ttau best_tnu best_nlZ % keep tilde parameters between calls tol = 1e-3; max_sweep = 10; % tolerance for when to stop EP iterations n = size(x,1); K = feval(covfunc{:}, hyper, x); % evaluate the covariance matrix % A note on naming: variables are given short but descriptive names in % accordance with Rasmussen & Williams "GPs for Machine Learning" (2006): mu % and s2 are mean and variance, nu and tau are natural parameters. A leading t % means tilde, a subscript _ni means "not i" (for cavity parameters), or _n % for a vector of cavity parameters. if any(size(best_ttau) ~= [n 1]) % find starting point for tilde parameters ttau = zeros(n,1); % initialize to zero if we have no better guess tnu = zeros(n,1); Sigma = K; % initialize Sigma and mu, the parameters of .. mu = zeros(n, 1); % .. the Gaussian posterior approximation nlZ = n*log(2); best_nlZ = Inf; else ttau = best_ttau; % try the tilde values from previous call tnu = best_tnu; [Sigma, mu, nlZ, L] = epComputeParams(K, y, ttau, tnu, lik); if nlZ > n*log(2) % if zero is better .. ttau = zeros(n,1); % .. then initialize with zero instead tnu = zeros(n,1); Sigma = K; % initialize Sigma and mu, the parameters of .. mu = zeros(n, 1); % .. the Gaussian posterior approximation nlZ = n*log(2); end end nlZ_old = Inf; sweep = 0; % make sure while loop starts while nlZ < nlZ_old - tol && sweep < max_sweep % converged or max. sweeps? nlZ_old = nlZ; sweep = sweep+1; for i = randperm(n) % iterate EP updates (in random order) over examples tau_ni = 1/Sigma(i,i)-ttau(i); % first find the cavity distribution .. nu_ni = mu(i)/Sigma(i,i)-tnu(i); % .. parameters tau_ni and nu_ni % compute the desired raw moments m0, m1=hmu and m2; m0 is not used [m0, m1, m2] = feval(lik, y(i), nu_ni/tau_ni, 1/tau_ni); hmu = m1./m0; hs2 = m2./m0 - hmu^2; % compute second central moment ttau_old = ttau(i); % then find the new tilde parameters ttau(i) = 1/hs2 - tau_ni; tnu(i) = hmu/hs2 - nu_ni; ds2 = ttau(i) - ttau_old; % finally rank-1 update Sigma .. si = Sigma(:,i); Sigma = Sigma - ds2/(1+ds2*si(i))*si*si'; % takes 70% of total time mu = Sigma*tnu; % .. and recompute mu end [Sigma, mu, nlZ, L] = epComputeParams(K, y, ttau, tnu, lik); % recompute % Sigma & mu since repeated rank-one updates can destroy numerical precision end if sweep == max_sweep disp('Warning: maximum number of sweeps reached in function approxEP') end if nlZ < best_nlZ % if best so far .. best_ttau = ttau; best_tnu = tnu; best_nlZ = nlZ; % .. keep for next call end sW = sqrt(ttau); % compute output arguments, L and nlZ are done alpha = tnu-sW.*solve_chol(L,sW.*(K*tnu)); if nargout > 4 % do we want derivatives? dnlZ = zeros(size(hyper)); % allocate space for derivatives F = alpha*alpha'-repmat(sW,1,n).*solve_chol(L,diag(sW)); for j=1:length(hyper) dK = feval(covfunc{:}, hyper, x, j); dnlZ(j) = -sum(sum(F.*dK))/2; end end % function to compute the parameters of the Gaussian approximation, Sigma and % mu, and the negative log marginal likelihood, nlZ, from the current site % parameters, ttau and tnu. Also returns L (useful for predictions). function [Sigma, mu, nlZ, L] = epComputeParams(K, y, ttau, tnu, lik) n = length(y); % number of training cases ssi = sqrt(ttau); % compute Sigma and mu L = chol(eye(n)+ssi*ssi'.*K); % L'*L=B=eye(n)+sW*K*sW V = L'\(repmat(ssi,1,n).*K); Sigma = K - V'*V; mu = Sigma*tnu; tau_n = 1./diag(Sigma)-ttau; % compute the log marginal likelihood nu_n = mu./diag(Sigma)-tnu; % vectors of cavity parameters nlZ = sum(log(diag(L))) - sum(log(feval(lik, y, nu_n./tau_n, 1./tau_n))) ... -tnu'*Sigma*tnu/2 - nu_n'*((ttau./tau_n.*nu_n-2*tnu)./(ttau+tau_n))/2 ... +sum(tnu.^2./(tau_n+ttau))/2-sum(log(1+ttau./tau_n))/2;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
sq_dist.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/gpml-matlab/gpml/sq_dist.m
2,186
utf_8
3b01028d6b07c19a397a274229dd24ee
% sq_dist - a function to compute a matrix of all pairwise squared distances % between two sets of vectors, stored in the columns of the two matrices, a % (of size D by n) and b (of size D by m). If only a single argument is given % or the second matrix is empty, the missing matrix is taken to be identical % to the first. % % Special functionality: If an optional third matrix argument Q is given, it % must be of size n by m, and in this case a vector of the traces of the % product of Q' and the coordinatewise squared distances is returned. % % NOTE: The program code is written in the C language for efficiency and is % contained in the file sq_dist.c, and should be compiled using matlabs mex % facility. However, this file also contains a (less efficient) matlab % implementation, supplied only as a help to people unfamiliar with mex. If % the C code has been properly compiled and is avaiable, it automatically % takes precendence over the matlab code in this file. % % Usage: C = sq_dist(a, b) % or: C = sq_dist(a) or equiv.: C = sq_dist(a, []) % or: c = sq_dist(a, b, Q) % where the b matrix may be empty. % % where a is of size D by n, b is of size D by m (or empty), C and Q are of % size n by m and c is of size D by 1. % % Copyright (c) 2003, 2004, 2005 and 2006 Carl Edward Rasmussen. 2006-03-09. function C = sq_dist(a, b, Q); if nargin < 1 | nargin > 3 | nargout > 1 error('Wrong number of arguments.'); end if nargin == 1 | isempty(b) % input arguments are taken to be b = a; % identical if b is missing or empty end [D, n] = size(a); [d, m] = size(b); if d ~= D error('Error: column lengths must agree.'); end if nargin < 3 C = zeros(n,m); for d = 1:D C = C + (repmat(b(d,:), n, 1) - repmat(a(d,:)', 1, m)).^2; end % C = repmat(sum(a.*a)',1,m)+repmat(sum(b.*b),n,1)-2*a'*b could be used to % replace the 3 lines above; it would be faster, but numerically less stable. else if [n m] == size(Q) C = zeros(D,1); for d = 1:D C(d) = sum(sum((repmat(b(d,:), n, 1) - repmat(a(d,:)', 1, m)).^2.*Q)); end else error('Third argument has wrong size.'); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
logistic.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/gpml-matlab/gpml/logistic.m
4,453
utf_8
727c105366930b647b840ed749d3ae7a
function [out1, out2, out3, out4] = logistic(y, f, var) % logistic - logistic likelihood function. The expression for the likelihood is % logistic(t) = 1./(1+exp(-t)). % % Three modes are provided, for computing likelihoods, derivatives and moments % respectively, see likelihoods.m for the details. In general, care is taken % to avoid numerical issues when the arguments are extreme. The moments % \int f^k cumGauss(y,f) N(f|mu,var) df are calculated using an approximation % to the cumulative Gaussian based on a mixture of 5 cumulative Gaussian % functions (or alternatively using Gauss-Hermite quadrature, which may be less % accurate). % % Copyright (c) 2007 Carl Edward Rasmussen and Hannes Nickisch, 2007-07-25. if nargin>1, y=sign(y); end % allow only +/- 1 as values if nargin == 2 % (log) likelihood evaluation if numel(y)>0, yf = y.*f; else yf = f; end % product of latents and labels out1 = 1./(1+exp(-yf)); % likelihood if nargout>1 out2 = yf; ok = -35<yf; out2(ok) = -log(1+exp(-yf(ok))); % log of likelihood end elseif nargin == 3 if strcmp(var,'deriv') % derivatives of log likelihood if numel(y)==0, y=1; end yf = y.*f; % product of latents and labels s = -yf; ps = max(0,s); out1 = -sum(ps+log(exp(-ps)+exp(s-ps))); % lp = -sum(log(1+exp(s))) if nargout>1 % dlp - first derivatives s = min(0,f); p = exp(s)./(exp(s)+exp(s-f)); % p = 1./(1+exp(-f)) out2 = (y+1)/2-p; % dlp, derivative of log likelihood if nargout>2 % d2lp, 2nd derivative of log likelihood out3 = -exp(2*s-f)./(exp(s)+exp(s-f)).^2; if nargout>3 % d3lp, 3rd derivative of log likelihood out4 = 2*out3.*(0.5-p); end end end else % compute moments mu = f; % 2nd argument is the mean of a Gaussian if numel(y)==0, y=ones(size(mu)); end % if empty, assume y=1 % Two methods of integration are possible; the latter is more accurate % [out1,out2,out3] = gauherint(y, mu, var); [out1,out2,out3] = erfint(y, mu, var); end else error('No valid input provided.') end % The gauherint function approximates "\int t^k logistic(y t) N(t|mu,var)dt" by % means of Gaussian Hermite Quadrature. A call to gauher.m is made. function [m0,m1,m2] = gauherint(y, mu, var) N = 20; [f,w] = gauher(N); % 20 yields precalculated weights sz = size(mu); f0 = sqrt(var(:))*f'+repmat(mu(:),[1,N]); % center values of f sig = logistic( repmat(y(:),[1,N]), f0 ); % calculate the likelihood values m0 = reshape(sig*w, sz); % zeroth moment if nargout>1 % first moment m1 = reshape(f0.*sig*w, sz); if nargout>2, m2 = reshape(f0.*f0.*sig*w, sz); end % second moment end % The erfint function approximates "\int t^k logistic(y t) N(t|mu,s2) dt" by % setting: % logistic(t) \approx 1/2 + \sum_{i=1}^5 (c_i/2) erf(lambda_i t) % The integrals \int t^k erf(t) N(t|mu,s2) dt can be done analytically. % % The inputs y, mu and var have to be column vectors of equal lengths. function [m0,m1,m2] = erfint(y, mu, s2) l = [0.44 0.41 0.40 0.39 0.36]; % approximation coefficients lambda_i c = [1.146480988574439e+02; -1.508871030070582e+03; 2.676085036831241e+03; -1.356294962039222e+03; 7.543285642111850e+01 ]; S2 = 2*s2.*(y.^2)*(l.^2) + 1; % zeroth moment S = sqrt( S2 ); Z = mu.*y*l./S; M0 = erf(Z); m0 = ( 1 + M0*c )/2; if nargout>1 % first moment NormZ = exp(-Z.^2)/sqrt(2*pi); M0mu = M0.*repmat(mu,[1,5]); M1 = (2*sqrt(2)*y.*s2)*l.*NormZ./S + M0mu; m1 = ( mu + M1*c )/2; if nargout>2 % second moment M2 = repmat(2*mu,[1,5]).*(1+s2.*y.^2*(l.^2)).*(M1-M0mu)./S2 ... + repmat(s2+mu.^2,[1,5]).*M0; m2 = ( mu.^2 + s2 + M2*c )/2; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
solve_chol.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/gpml-matlab/gpml/solve_chol.m
991
utf_8
906bce3c6bfbaf11908ec2e326cffd7e
% solve_chol - solve linear equations from the Cholesky factorization. % Solve A*X = B for X, where A is square, symmetric, positive definite. The % input to the function is R the Cholesky decomposition of A and the matrix B. % Example: X = solve_chol(chol(A),B); % % NOTE: The program code is written in the C language for efficiency and is % contained in the file solve_chol.c, and should be compiled using matlabs mex % facility. However, this file also contains a (less efficient) matlab % implementation, supplied only as a help to people unfamiliar with mex. If % the C code has been properly compiled and is avaiable, it automatically % takes precendence over the matlab code in this file. % % Copyright (c) 2004, 2005, 2006 by Carl Edward Rasmussen. 2006-02-08. function x = solve_chol(A, B); if nargin ~= 2 | nargout > 1 error('Wrong number of arguments.'); end if size(A,1) ~= size(A,2) | size(A,1) ~= size(B,1) error('Wrong sizes of matrix arguments.'); end x = A\(A'\B);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
renumber.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/tensor_toolbox/@sptensor/private/renumber.m
1,096
utf_8
cc4e5b1cdd5104d68906c16fb00223f8
function [newsubs, newsz] = renumber(subs, sz, range) %RENUMBER indices for sptensor subsref % % [NEWSUBS,NEWSZ] = RENUMBER(SUBS,SZ,RANGE) takes a set of % original subscripts SUBS with entries from a tensor of size % SZ. All the entries in SUBS are assumed to be within the % specified RANGE. These subscripts are then renumbered so that, % in dimension i, the numbers range from 1:numel(RANGE(i)). % % See also SPTENSOR/SUBSREF newsz = sz; newsubs = subs; for i = 1 : size(sz,2) if ~(ischar(range{i}) && range{i} == ':') if (isempty(subs)) newsz(i) = numel(range{i}); else [newsubs(:,i), newsz(i)] = ... renumberdim(subs(:,i), sz(i), range{i}); end end end %------------------------------------------------------ function [newidx, newsz] = renumberdim(idx, sz, range) %RENUMBERDIM helper function for RENUMBER % See also SPTENSOR/PRIVATE/RENUMBER % Determine the size of the new range newsz = numel(range); % Create a map from the old range to the new range map = zeros(1, sz); for i = 1 : newsz map(range(i)) = i; end % Do the mapping newidx = map(idx);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
parafac_als.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/tensor_toolbox/algorithms/parafac_als.m
4,787
utf_8
b4f981cdfc968e7cd37f3d4a01938b74
function [P,Uinit] = parafac_als(X,R,opts) %PARAFAC_ALS Compute a PARAFAC decomposition of any type of tensor. % % P = PARAFAC_ALS(X,R) computes an estimate of the best rank-R % PARAFAC model of a tensor X using an alternating least-squares % algorithm. The input X can be a tensor, sptensor, ktensor, or % ttensor. The result P is a ktensor. % % P = PARAFAC_ALS(X,R,OPTS) specify options: % OPTS.tol: Tolerance on difference in fit {1.0e-4} % OPTS.maxiters: Maximum number of iterations {50} % OPTS.dimorder: Order to loop through dimensions {1:ndims(A)} % OPTS.init: Initial guess [{'random'}|'nvecs'|cell array] % % [P,U0] = PARAFAC_ALS(...) also returns the initial guess. % % Examples: % X = sptenrand([5 4 3], 10); % P = parafac_als(X,2); % P = parafac_als(X,2,struct('dimorder',[3 2 1])); % P = parafac_als(X,2,struct('dimorder',[3 2 1],'init','nvecs')); % U0 = {rand(5,2),rand(4,2),[]}; %<-- Initial guess for factors of P % P = parafac_als(X,2,struct('dimorder',[3 2 1],'init',{U0})); % % See also KTENSOR, TENSOR, SPTENSOR, TTENSOR. % %MATLAB Tensor Toolbox. %Copyright 2007, Sandia Corporation. % This is the MATLAB Tensor Toolbox by Brett Bader and Tamara Kolda. % http://csmr.ca.sandia.gov/~tgkolda/TensorToolbox. % Copyright (2007) Sandia Corporation. Under the terms of Contract % DE-AC04-94AL85000, there is a non-exclusive license for use of this % work by or on behalf of the U.S. Government. Export of this data may % require a license from the United States Government. % The full license terms can be found in tensor_toolbox/LICENSE.txt % $Id: parafac_als.m,v 1.12 2007/01/10 01:27:31 bwbader Exp $ %% Fill in optional variable if ~exist('opts','var') opts = struct; end %% Extract number of dimensions and norm of X. N = ndims(X); normX = norm(X); %% Set algorithm parameters from input or by using defaults fitchangetol = setparam(opts,'tol',1e-4); maxiters = setparam(opts,'maxiters',50); dimorder = setparam(opts,'dimorder',1:N); init = setparam(opts,'init','random'); %% Error checking % Error checking on maxiters if maxiters < 0 error('OPTS.maxiters must be positive'); end % Error checking on dimorder if ~isequal(1:N,sort(dimorder)) error('OPTS.dimorder must include all elements from 1 to ndims(X)'); end %% Set up and error checking on initial guess for U. if iscell(init) Uinit = init; if numel(Uinit) ~= N error('OPTS.init does not have %d cells',N); end for n = dimorder(2:end); if ~isequal(size(Uinit{n}),[size(X,n) R]) error('OPTS.init{%d} is the wrong size',n); end end else % Observe that we don't need to calculate an initial guess for the % first index in dimorder because that will be solved for in the first % inner iteration. if strcmp(init,'random') Uinit = cell(N,1); for n = dimorder(2:end) Uinit{n} = rand(size(X,n),R); end elseif strcmp(init,'nvecs') || strcmp(init,'eigs') Uinit = cell(N,1); for n = dimorder(2:end) fprintf(' Computing %d leading e-vectors for factor %d.\n',R,n); Uinit{n} = nvecs(X,n,R); end else error('The selected initialization method is not supported'); end end %% Set up for iterations - initializing U and the fit. U = Uinit; fit = 0; fprintf('\nAlternating Least-Squares:\n'); %% Main Loop: Iterate until convergence for iter = 1:maxiters fitold = fit; % Iterate over all N modes of the tensor for n = dimorder(1:end) % Calculate Unew = X_(n) * khatrirao(all U except n, 'r'). Unew = mttkrp(X,U,n); % Compute the matrix of coefficients for linear system Y = ones(R,R); for i = [1:n-1,n+1:N] Y = Y .* (U{i}'*U{i}); end Unew = (Y \ Unew')'; % Normalize each vector to prevent singularities in coefmatrix if iter == 1 lambda = sqrt(sum(Unew.^2,1))'; %2-norm else lambda = max( max(Unew,[],1), 1 )'; %max-norm end Unew = Unew * spdiags(1./lambda,0,R,R); U{n} = Unew; end P = ktensor(lambda,U); normresidual = sqrt( normX^2 + norm(P)^2 - 2 * innerprod(X,P) ); fit = 1 - (normresidual / normX); %fraction explained by model fitchange = abs(fitold - fit); fprintf(' Iter %2d: fit = %e fitdelta = %7.1e\n', iter, fit, fitchange); % Check for convergence if (iter > 1) && (fitchange < fitchangetol) break; end end %% Clean up final result % Arrange the final tensor so that the columns are normalized. P = arrange(P); % Fix the signs P = fixsigns(P); end %% function x = setparam(opts,name,default) if isfield(opts,name); x = opts.(name); else x = default; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
tucker_als.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/tensor_toolbox/algorithms/tucker_als.m
4,753
utf_8
76e12b4d240918bb85c83cae7e2510c7
function [T,Uinit] = tucker_als(X,R,opts) %TUCKER_ALS Higher-order orthogonal iteration. % % T = TUCKER_ALS(X,R) computes the best rank(R1,R2,..,Rn) % approximation of tensor X, according to the specified dimensions % in vector R. The input X can be a tensor, sptensor, ktensor, or % ttensor. The result returned in T is a ttensor. % % T = TUCKER_ALS(X,R,OPTS) specify options: % OPTS.tol: Tolerance on difference in fit {1.0e-4} % OPTS.maxiters: Maximum number of iterations {50} % OPTS.dimorder: Order to loop through dimensions {1:ndims(A)} % OPTS.init: Initial guess [{'random'}|'eigs'|cell array] % % [T,U0] = TUCKER_ALS(...) also returns the initial guess. % % Examples: % X = sptenrand([5 4 3], 10); % T = tucker_als(X,2); %<-- best rank(2,2,2) approximation % T = tucker_als(X,[2 2 1]); %<-- best rank(2,2,1) approximation % T = tucker_als(X,2,struct('dimorder',[3 2 1])); % T = tucker_als(X,2,struct('dimorder',[3 2 1],'init','eigs')); % U0 = {rand(5,2),rand(4,2),[]}; %<-- Initial guess for factors of T % T = tucker_als(X,2,struct('dimorder',[3 2 1],'init',{U0})); % % See also TTENSOR, TENSOR, SPTENSOR, KTENSOR. % %MATLAB Tensor Toolbox. %Copyright 2007, Sandia Corporation. % This is the MATLAB Tensor Toolbox by Brett Bader and Tamara Kolda. % http://csmr.ca.sandia.gov/~tgkolda/TensorToolbox. % Copyright (2007) Sandia Corporation. Under the terms of Contract % DE-AC04-94AL85000, there is a non-exclusive license for use of this % work by or on behalf of the U.S. Government. Export of this data may % require a license from the United States Government. % The full license terms can be found in tensor_toolbox/LICENSE.txt % $Id: tucker_als.m,v 1.4 2007/01/10 01:27:31 bwbader Exp $ % Fill in optional variable if ~exist('opts','var') opts = struct; end % Extract number of dimensions and norm of X. N = ndims(X); normX = norm(X); % Set algorithm parameters from input or by using defaults fitchangetol = setparam(opts,'tol',1e-4); maxiters = setparam(opts,'maxiters',50); dimorder = setparam(opts,'dimorder',1:N); init = setparam(opts,'init','random'); if numel(R) == 1 R = R * ones(N,1); end U = cell(N,1); %% Error checking % Error checking on maxiters if maxiters < 0 error('OPTS.maxiters must be positive'); end % Error checking on dimorder if ~isequal(1:N,sort(dimorder)) error('OPTS.dimorder must include all elements from 1 to ndims(X)'); end %% Set up and error checking on initial guess for U. if iscell(init) Uinit = init; if numel(Uinit) ~= N error('OPTS.init does not have %d cells',N); end for n = dimorder(2:end); if ~isequal(size(Uinit{n}),[size(X,n) R(n)]) error('OPTS.init{%d} is the wrong size',n); end end else % Observe that we don't need to calculate an initial guess for the % first index in dimorder because that will be solved for in the first % inner iteration. if strcmp(init,'random') Uinit = cell(N,1); for n = dimorder(2:end) Uinit{n} = rand(size(X,n),R(n)); end elseif strcmp(init,'nvecs') || strcmp(init,'eigs') % Compute an orthonormal basis for the dominant % Rn-dimensional left singular subspace of % X_(n) (1 <= n <= N). Uinit = cell(N,1); for n = dimorder(2:end) fprintf(' Computing %d leading e-vectors for factor %d.\n', ... R(n),n); Uinit{n} = nvecs(X,n,R(n)); end else error('The selected initialization method is not supported'); end end %% Set up for iterations - initializing U and the fit. U = Uinit; fit = 0; fprintf('\nAlternating Least-Squares:\n'); %% Main Loop: Iterate until convergence for iter = 1:maxiters fitold = fit; % Iterate over all N modes of the tensor for n = dimorder(1:end) Utilde = ttm(X, U, -n, 't'); % Maximize norm(Utilde x_n W') wrt W and % keeping orthonormality of W U{n} = nvecs(Utilde,n,R(n)); end % Assemble the current approximation core = ttm(Utilde, U, n, 't'); T = ttensor(core, U); % Compute fit normresidual = sqrt( normX^2 + norm(T)^2 - 2 * innerprod(X,T) ); fit = 1 - (normresidual / normX); %fraction explained by model fitchange = abs(fitold - fit); fprintf(' Iter %2d: fit = %e fitdelta = %7.1e\n', iter, fit, fitchange); % Check for convergence if (iter > 1) && (fitchange < fitchangetol) break; end end %% Compute the final result % Create the core array core = ttm(X, U, 't'); % Assemble the resulting tensor T = ttensor(core, U); end %% function x = setparam(opts,name,default) if isfield(opts,name); x = opts.(name); else x = default; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
datadisp.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/tensor_toolbox/@ktensor/datadisp.m
3,230
utf_8
617d86e8a39f5745c326f1f3c330a63f
function datadisp(T, dimlabels, opts) %DATADISP Special display of a ktensor. % % DATADISP(T,LABELS) displays the largest positive entries of each rank-1 % factor of T using the corresponding labels. LABELS is a cell array of % size ndims(T) such that LABELS{n} is a string cell array of length % size(T,n). % % DATADISP(T,LABELS,OPTS) specify options: % OPTS.dimorder: Order to display the dimensions of T {1:ndims(T)} % OPTS.maxentries: Number of entries to show for each factor {10} % OPTS.printneg: Boolean to print the most negative entries {false} % OPTS.threshold: Threshold of smallest magnitude score to show {1e-4} % % See also KTENSOR. % %MATLAB Tensor Toolbox. %Copyright 2007, Sandia Corporation. % This is the MATLAB Tensor Toolbox by Brett Bader and Tamara Kolda. % http://csmr.ca.sandia.gov/~tgkolda/TensorToolbox. % Copyright (2007) Sandia Corporation. Under the terms of Contract % DE-AC04-94AL85000, there is a non-exclusive license for use of this % work by or on behalf of the U.S. Government. Export of this data may % require a license from the United States Government. % The full license terms can be found in tensor_toolbox/LICENSE.txt % $Id: datadisp.m,v 1.12 2007/01/10 01:27:30 bwbader Exp $ %% Fill in optional variable if ~exist('opts','var') opts = struct; end %% Set options from input or use defaults dimorder = setparam(opts,'dimorder',1:ndims(T)); maxentries = setparam(opts,'maxentries',10); printneg = setparam(opts,'printneg',false); threshold = setparam(opts,'threshold',1e-6); %% Main loop R = size(T.lambda,1); % Rank r = 1; while (r <= R) fprintf(1, '\n======== Group %d ========\n', r); fprintf('\nWeight = %f\n', T.lambda(r)); for i = dimorder(1:end) print_sublist(T.u{i}(:,r), dimlabels{i}, 'positive', maxentries, threshold); if printneg print_sublist(T.u{i}(:,r), dimlabels{i}, 'negative', maxentries, threshold); end end if r == R, break, end; foo = input('\nReturn to continue, jump to rank, or ''0'' (zero) to quit: '); if foo == 0 return; elseif isempty(foo) r = r+1; else r = foo; end end return; %% function print_sublist(score, labels, type, maxentries, threshold) if isequal(type,'positive') [sortedScore, sortedIdx] = sort(score, 'descend'); elseif isequal(type, 'negative') [sortedScore, sortedIdx] = sort(score, 'ascend'); else error('Invalid type'); end sortedRefs = labels(sortedIdx); entries = min([maxentries, length(score)]); if isequal(type,'positive') range = 1:entries; else range = entries:-1:1; end fprintf('%-10s %-4s %s\n','Score','Id','Name'); for k = range if abs(sortedScore(k)) < threshold continue; end if isequal(type,'negative') && sortedScore(k) >= 0 continue; end if (abs(sortedScore(k)) < 1e-4) fprintf(1, '%10.3e %4d %s\n', sortedScore(k), sortedIdx(k), ... sortedRefs{k}); else fprintf(1, '%10.7f %4d %s\n', sortedScore(k), sortedIdx(k), ... sortedRefs{k}); end end %% function x = setparam(opts,name,default) if isfield(opts,name); x = opts.(name); else x = default; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
PCAWX.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/PCAW/PCAWX.m
8,913
utf_8
38089d70cf1668856332925d2c9d3ce3
function [T,P,xmean,expl,SS] = pcawx(Xmn,W,r,xmean,convg,maxniter,plotopt,saveopt) % [T,P,xmean,expl,SS] = pcawx(Xmn,W,r,xmean,convg,maxniter,plotopt,saveopt); % % Purpose: % The next quantity is minimized: % min|| W * ( X - 1.xmean' - T.P')|| % over m (mean center) % over T (scores) % over P (loadings) % % Input: % Xmn - (n x m) matrix % Mean Centered Input data. % % W - (n x m) matrix % Contains 1/STD for each entry in X % % r - scalar % Number of principal components. % % xmean - Optional (1 x m) vector. % Mean center of data. % Default: zeros(1,m) % % convg - (optional) scalar % Convergence criterium. % Default: 1e-5 % % maxniter- (optional) scalar % Maximum number of iterations. % Default: 2000 % % plotopt - (optional) scalar % Plot intermediate results. % Default: 0 % % saveopt - (optional) scalar % Save intermediate results. % Default: 0 % % Output: % T - (n x r) matrix % Orthogonal scores on columns % % P - (m x r) matrix % Orthonormal loadings on columns % % xmean - (1 x m) vector % Updated mean center of data (Estimated Offset) % % expl - Explained variation of Xmn [percent]. % % SS - (nniter x 1) vector % Weighted sum of squares: ||(Xmn-TP')*W|| % for each niteration. % % Based on an algorithm and computer program developed by Henk Kiers % Psychometrika 62(2) 251-266 % % ========================================================================== % Copyright 2005 Biosystems Data Analysis Group ; Universiteit van Amsterdam % ========================================================================== global StopPCAW; persistent Isave figNr1 figNr2 % Check arguments [n,m] = size(Xmn); if ( nargin < 4 ) xmean = zeros(1,m); end if ( isempty(xmean) ) xmean = zeros(1,m); end if ( nargin < 5 ) convg = 1e-5; end if ( isempty(convg) ) convg = 1e-5; end if ( nargin < 6 ) maxniter = 2000; end if ( isempty(maxniter) ) maxniter = 2000; end if ( nargin < 7 ) plotopt = 0; end if ( isempty(plotopt) ) plotopt = 0; end if ( nargin < 8 ) saveopt = 0; end % Start Code StopPCAW = 0; % Start with PCA and keep r eigenvectors. if ( any(isnan( Xmn(:) ) ) ) % Replace missing values in X with zeros % in order to get a initial estimate of % loadings and scores matrix. ind = find(isnan(Xmn) ); Xmn(ind) = zeros(size(ind)); W(ind) = zeros(size(ind)); end % initial estimate of scores and loadings. % A unweighted PCA is done on mean centered data. % % % [T,P] = pca(Xmn,0,[],r); [P,T] = princomp2(Xmn); T = T(:,1:r); P = P(:,1:r); Tpca = T; % wmax = MAXIMUM weight and thus MINIMUM error variance. wmax = max(W(:).^2); % Open temporary file used to stored intermediate results. if ( saveopt ) if ( isempty(Isave) ) Isave = 1; else Isave = Isave + 1; end fid = fopen(['PCAWXtemp',sprintf('%07d',Isave),'.dat'],'w'); fwrite(fid,n,'uint32'); fwrite(fid,m,'uint32'); fwrite(fid,r,'uint32'); end % ========= Initialize the majorization loop ============ niter = 1; % SS is current weighted sum of squares. SS(niter) = ssq( (Xmn-T*P') .* W ); % SSold is previous weighted sum of squares, make it always % larger than SS to start with. SSold = SS(niter) + 2; normMAT = norm(T * P'); if ( saveopt ) fwrite(fid,niter,'uint32'); fwrite(fid,SS(niter),'double'); fwrite(fid,T(:),'double'); fwrite(fid,P(:),'double'); fwrite(fid,xmean(:),'double'); end if ( plotopt & isempty(figNr1) ) figNr1 = figure('name' ,'Convergence',... 'units' ,'normalized',... 'position',[0.005,0.2,0.49,0.6]); figNr2 = figure('name' ,'Scores',... 'units' ,'normalized',... 'position',[0.5,0.2,0.49,0.6]); set(figNr1,'keypressfcn','global StopPCAW;StopPCAW=1;'); set(figNr2,'keypressfcn','global StopPCAW;StopPCAW=1;'); Tprev = Tpca; end % ================================================================= % Loop while next condition are all satisfied: % 1. relative change in SS is larger than convergence crniterium. % 2 SS is larger convg * norm of reconstructed X matrix. % 3. number of niterations does not exceed maxniter % 4. User did not signal to stop niterations. % ================================================================ VecOfOnes = ones(n,1); Xor = Xmn + VecOfOnes * xmean; while ( abs(SSold - SS(niter))/SSold > convg && ... SS(niter) > convg * normMAT && ... niter <=maxniter && ... ~StopPCAW ); RelErr = abs(SSold - SS(niter))/SSold; SSold = SS(niter); % Majorization step F = (W.^2) .* (Xmn - T * P' ) /wmax + T * P'; % % % [T,P] = pca(F,0,[],r); [P,T] = princomp2(F); T = T(:,1:r); P = P(:,1:r); Xup = Xor - T * P'; % Find better estimate of mean. if ( rem(niter,2) == 0 ) F = (W.^2) .* (Xup - VecOfOnes * xmean ) /wmax + VecOfOnes * xmean; xmean = 1/length(VecOfOnes)* VecOfOnes' * F; Xmn = Xor - VecOfOnes * xmean; end % Now new T,P and m are found, update crniterion niter = niter + 1; SS(niter) = ssq( (Xmn - T * P') .* W ); normMAT = norm(T * P'); % Save results in a temporary file every 5 niterations. if ( saveopt ) fwrite(fid,niter,'uint32'); fwrite(fid,SS(niter),'double'); fwrite(fid,T(:),'double'); fwrite(fid,P(:),'double'); fwrite(fid,xmean(:),'double'); end if ( plotopt) figure(figNr1) if ( niter > 30 ) range = niter-29:niter; semilogy(range(1:end-1),abs(diff(SS(range)))./SS(niter-29:niter-1),'r.-') axis([niter-29,niter,1e-6,1]) else semilogy(abs(diff(SS))./SS(1:niter-1),'r.-') axis([1,niter,convg/10,1]) end hold on hline(convg,'b-'); title('Convergence crniterion') figure(figNr2) Tcur = T; if ( mod(niter,30) ) hold off end % PCAW-scores are made similer to original PCA-scores % by means of Procrustes Rotation. Tcurr = compscores(Tcur,Tpca); plot(Tcurr(:,1),Tcurr(:,2),'bo') text(Tcurr(:,1),Tcurr(:,2),num2str([1:size(Tcurr,1)]')); hold on plot(Tpca(:,1),Tpca(:,2),'r.') scln_1 = [Tcurr(:,1),Tpca(:,1),NaN*ones(size(Tcurr,1),1)]'; scln_2 = [Tcurr(:,2),Tpca(:,2),NaN*ones(size(Tcurr,1),1)]'; plot(scln_1(:),scln_2(:),'g-') Tprev = Tcur; drawnow end end if ( saveopt ) fclose(fid); end TELLER = (norm(((Xmn-T*P').*W),'fro')).^2; NOEMER = (norm((Xmn .* W),'fro')).^2; expl = (1-(TELLER/NOEMER))*100; return %---------------------------------------------------------------------- % Additional Functions function t = ssq(a) %SSQ SSQ(A) is the sum of squares of the elements of matrix A. t = sum(sum(a.^2)); return function [sc1,sc2,Rot] = compscores(scores1,scores2) % [sc1,sc2,Rot] = compscores(scores1,scores2); % % Purpose: % Compares scores of two (PCA) models. % % Input % scores1 - (Nobject * Nload1) matrix % Scores on first model. % Nobject = number of objects. % Nload1 = number of loading vectors % in the model % These scores are rotated. % % scores2 - (Nobject * Nload2) matrix % Nobject = number of objects. % Nload2 = number of loading vectors % in the model. % Description: % Massart part B, page 313 if ( size(scores1,1) ~= size(scores2,1) ) error('Number of objects should be the same'); end [u,s,v] = svd(scores2'*scores1); Rot = v * u'; sc1 = scores1 * Rot; sc2 = scores2; return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
PCAWXC.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/PCAW/PCAWXC.m
8,982
utf_8
421d20f1186cd48cf0cb14f8b8707fd9
function [T,P,xmean,expl,SS] = pcawxc(Xmn,W,r,xmean,convg,maxniter,plotopt,saveopt) % [T,P,xmean,expl,SS] = pcawxc(Xmn,W,r,xmean,convg,maxniter,plotopt,saveopt) % % Purpose: % The next quantity is minimized: % min|| W * ( X - D.xmean' - T.P')|| % over m (mean center) % over T (scores) % over P (loadings) % % Input: % Xmn - (n x m) matrix % Mean Centered Input data. % % W - (n x m) matrix % Contains 1/STD for each entry in X % % r - scalar % Number of principal components. % % xmean - Optional (i x m) matrix. % Mean center of data. % Default: zeros(1,m) (where i is the number of individuals % in the data) % % convg - (optional) scalar % Convergence criterium. % Default: 1e-5 % % maxniter- (optional) scalar % Maximum number of iterations. % Default: 2000 % % plotopt - (optional) scalar % Plot intermediate results. % Default: 0 % % saveopt - (optional) scalar % Save intermediate results. % Default: 0 % % Output: % T - (n x r) matrix % Orthogonal scores on columns % % P - (m x r) matrix % Orthogonal loadings on columns % % xmean - (1 x m) vector % Updated mean center of data % % expl - Explained variance of Xmn [percent]. % % SS - (nniter x 1) vector % Weighted sum of squares: ||(Xmn-TP')*W|| % for each niteration. % % Based on an algorithm and computer program developed by Henk Kiers % Psychometrika 62(2) 251-266 % % ========================================================================== % Copyright 2005 Biosystems Data Analysis Group ; Universiteit van Amsterdam % ========================================================================== global StopPCAW persistent Isave figNr1 figNr2 % Check arguments [n,m] = size(Xmn); if ( nargin < 4 ) xmean = zeros(10,m); end if ( isempty(xmean) ) xmean = zeros(10,m); end if ( nargin < 5 ) convg = 1e-5; end if ( isempty(convg) ) convg = 1e-5; end if ( nargin < 6 ) maxniter = 2000; end if ( isempty(maxniter) ) maxniter = 2000; end if ( nargin < 7 ) plotopt = 0; end if ( isempty(plotopt) ) plotopt = 0; end if ( nargin < 8 ) saveopt = 0; end % Start Code StopPCAW = 0; % Start with PCA and keep r eigenvectors. if ( any(isnan( Xmn(:) ) ) ) % Replace missing values in X with zeros % in order to get a initial estimate of % loadings and scores matrix. ind = find(isnan(Xmn) ); Xmn(ind) = zeros(size(ind)); W(ind) = zeros(size(ind)); end % initial estimate of scores and loadings. % A unweighted PCA is done on mean centered data. [T,P] = pca(Xmn,0,[],r); Tpca = T; % wmax = MAXIMUM weight and thus MINIMUM error variance. wmax = max(W(:).^2); % Open temporary file used to stored intermediate results. if ( saveopt ) if ( isempty(Isave) ) Isave = 1; else Isave = Isave + 1; end fid = fopen(['PCAWXtemp',sprintf('%07d',Isave),'.dat'],'w'); fwrite(fid,n,'uint32'); fwrite(fid,m,'uint32'); fwrite(fid,r,'uint32'); end % ========= Initialize the majorization loop ============ niter = 1; % SS is current weighted sum of squares. SS(niter) = ssq( (Xmn-T*P') .* W ); % SSold is previous weighted sum of squares, make it always % larger than SS to start with. SSold = SS(niter) + 2; normMAT = norm(T * P'); if ( saveopt ) fwrite(fid,niter,'uint32'); fwrite(fid,SS(niter),'double'); fwrite(fid,T(:),'double'); fwrite(fid,P(:),'double'); fwrite(fid,xmean(:),'double'); end if ( plotopt & isempty(figNr1) ) figNr1 = figure('name' ,'Convergence',... 'units' ,'normalized',... 'position',[0.005,0.2,0.49,0.6]); figNr2 = figure('name' ,'Scores',... 'units' ,'normalized',... 'position',[0.5,0.2,0.49,0.6]); set(figNr1,'keypressfcn','global StopPCAW;StopPCAW=1'); set(figNr2,'keypressfcn','global StopPCAW;StopPCAW=1'); Tprev = Tpca; end % ================================================================= % Loop while next condition are all satisfied: % 1. relative change in SS is larger than convergence crniterium. % 2 SS is larger convg * norm of reconstructed X matrix. % 3. number of niterations does not exceed maxniter % 4. User did not signal to stop niterations. % ================================================================ Temp = zeros(29,10); TempOne = ones(29,1); DesignMat = []; for ( i = 1:10 ) Temp1 = Temp; Temp1(:,i) = TempOne; DesignMat = [DesignMat;Temp1]; end Xor = Xmn + DesignMat * xmean; while ( abs(SSold - SS(niter))/SSold > convg & ... SS(niter) > convg * normMAT & ... niter <=maxniter & ... ~StopPCAW ) RelErr = abs(SSold - SS(niter))/SSold; SSold = SS(niter); % Majorization step F = (W.^2) .* (Xmn - T * P' ) /wmax + T * P'; [T,P] = pca(F,0,[],r); Xup = Xor - T * P'; % Find better estimate of mean. if ( rem(niter,2) == 0 ) F = (W.^2) .* (Xup - DesignMat * xmean ) /wmax + DesignMat * xmean; xmean = inv(DesignMat' * DesignMat) * DesignMat' * F; Xmn = Xor - DesignMat * xmean; end % Now new T,P and m are found, update crniterion niter = niter + 1; SS(niter) = ssq( (Xmn - T * P') .* W ); normMAT = norm(T * P'); % Save results in a temporary file every 5 niterations. if ( saveopt ) fwrite(fid,niter,'uint32'); fwrite(fid,SS(niter),'double'); fwrite(fid,T(:),'double'); fwrite(fid,P(:),'double'); fwrite(fid,xmean(:),'double'); end if ( plotopt) figure(figNr1) if ( niter > 30 ) range = niter-29:niter; semilogy(range(1:end-1),abs(diff(SS(range)))./SS(niter-29:niter-1),'r.-') axis([niter-29,niter,1e-6,1]) else semilogy(abs(diff(SS))./SS(1:niter-1),'r.-') axis([1,niter,convg/10,1]) end hold on hline(convg,'b-'); title('Convergence crniterion') figure(figNr2) Tcur = T; if ( mod(niter,30) ) hold off end % PCAW-scores are made similer to original PCA-scores % by means of Procrustes Rotation. Tcurr = compscores(Tcur,Tpca); plot(Tcurr(:,1),Tcurr(:,2),'bo') text(Tcurr(:,1),Tcurr(:,2),num2str([1:size(Tcurr,1)]')); hold on plot(Tpca(:,1),Tpca(:,2),'r.') scln_1 = [Tcurr(:,1),Tpca(:,1),NaN*ones(size(Tcurr,1),1)]'; scln_2 = [Tcurr(:,2),Tpca(:,2),NaN*ones(size(Tcurr,1),1)]'; plot(scln_1(:),scln_2(:),'g-') Tprev = Tcur; drawnow end end if ( saveopt ) fclose(fid); end TELLER = (norm(((Xmn-T*P').*W),'fro')).^2; NOEMER = (norm((Xmn .* W),'fro')).^2; expl = (1-(TELLER/NOEMER))*100; return %---------------------------------------------------------------------- % Additional Functions function t = ssq(a) %SSQ SSQ(A) is the sum of squares of the elements of matrix A. t = sum(sum(a.^2)); return function [sc1,sc2,Rot] = compscores(scores1,scores2) % [sc1,sc2,Rot] = compscores(scores1,scores2); % % Purpose: % Compares scores of two (PCA) models. % % Input % scores1 - (Nobject * Nload1) matrix % Scores on first model. % Nobject = number of objects. % Nload1 = number of loading vectors % in the model % These scores are rotated. % % scores2 - (Nobject * Nload2) matrix % Nobject = number of objects. % Nload2 = number of loading vectors % in the model. % Description: % Massart part B, page 313 if ( size(scores1,1) ~= size(scores2,1) ) error('Number of objects should be the same'); end [u,s,v] = svd(scores2'*scores1); Rot = v * u'; sc1 = scores1 * Rot; sc2 = scores2; return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
nfrpca.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/nfrpca/nfrpca.m
3,146
utf_8
0985da68fadb9f9c67839a1a80d01dc4
function [scores,loads]=nfrpca(x,LV,method) % Nonlinear fuzzy robust PCA algorithm from article: %P. Luukka, 'A New Nonlinear Fuzzy Robust PCA Algorithm and Similarity %classifier in classification of medical data sets', %International Journal of Fuzzy Systems, Vol. 13, No. 3, September 2011 %pp. 153-162. % %Function call: [scores,loads]=nfrpca(x,LV,method) % % %INPUTS: %1)x: your data matrix samples in rows and variables in columns %2)LV: How many variables to use from data, if not specified all variables are used. %3)method: which method to use % 'nfrpca1' means Nonlinear fuzzy robust PCA algorithm from article above. %In current version only this one is implemented and will be selected %automatically. % % %OUTPUTS: % %scores: The principal component scores; that is, the representation of X in the principal component space. % Rows of score correspond to observations, columns to components. %loads: principal component coefficients also known as loadings. x=x'; [m,n]=size(x); if nargin<3 method='nfrpca1' elseif nargin<2 LV=min(m,n); end scores=[]; loads=[]; a=10; % parameter value in function y=tanh(a*x) ALFA0=1; % learning coefficient (0,1] ETA=.1; % soft threshold, a small positive number EXPO=1.5; % fuzziness variable if strcmpi(method,'nfrpca1')==1 for lv=1:LV alfa0=ALFA0; % learning coefficient (0,1] eta=ETA; % soft threshold, a small positive number expo=EXPO; % fuzziness variable t=1; % iteration count T=100; % iteration bound [tt,s,pp] = svds(x',1); w=pp; % initialize loadings %w=rand(m,1); % initialize loadings wold=5*ones(size(w)); crit=sum((w-wold).^2); while t<T % do not add '=' sign alfat=alfa0*(1-t/T); sigma=0; i=1; wold=w; while i<=n y=w'*x(:,i); g=tanh(a*y); %Now implemented for function tanh(ax) gder=a/cosh(a*y)^2; %Derivative of the function e3x=(x(:,i)-g*w)'*(x(:,i)-g*w); beta=(1/(1+(e3x)/eta)^(1/(expo-1)))^expo; apu1=x(:,i)-w*g; F=gder; w=w+alfat*beta*(x(:,i)*apu1'*w*F+apu1*g); w=w/norm(w); sigma=sigma+e3x; i=i+1; end eta=sigma/n; t=t+1; crit=[crit,sum((w-wold).^2)/m]; if sum((w-wold).^2)/m<1e-8 break end end scores=[scores x'*w]; loads=[loads w]; x=x'; x=x-x*w*w'; x=x'; end end function Y=meanw(X,W) % MEANW : Weighted Mean % % Y=meanw(X,W) % % Y is the mean of X weighted by W. % if(size(X)~=size(W)), error('Must be 1:1 corrospondence between weights and samples'); end; Y = sum(W.*X)./sum(W); function Y=stdw(X,W) % STDW : Weighted Standard Deviation % % Y=stdw(X,W) % % Y is the standard deviation of X weighted by W. % if(size(X)~=size(W)), error('Must be 1:1 corrospondence between weights and samples'); end; Y = sqrt( (sum(W.*X.*X)./sum(W)) - (sum(W.*X)./sum(W)).^2);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
maxminLandmarks.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/JPlex/maxminLandmarks.m
8,218
utf_8
77c012bdc970c93c6407fef22f0b6f88
function L = maxminLandmarks(matrix, numLands, EorD) % INPUT: % matrix - see description for input EorD. % numLands - the number of landmark points to be chosen. % EorD - character EorD determines how input matrix is interpreted. If % EorD is 'e', then the N x n input matrix is interpreted as N points % in R^n, as in JPlex subclass EuclideanArrayData. If EorD is 'd', % then the N x N input matrix is interpreted as the distance matrix % for N points in an arbitrary metric space, as in JPlex subclass % DistanceData. % % OUTPUT: % L - a vertical vector of length numLands+1. Entry 1 is zero. Entries 2 % through numLands+1 are the indices of numLands landmark points, % chosen via sequential maxmin. L is ready to be used as input into % subclass WitnessStream or LazyWitnessStream of JPlex. % % NOTES: % The function maxminLandmarks.m uses function px_maxmin.m from the Plex % Metric Data Toolbox version 2.5, in the C++ version of Plex, by Vin de % Silva, Patrick Perry and contributors. if EorD == 'e' L = [0,px_maxmin(matrix','vector',numLands,'n')]'; elseif EorD == 'd' L = [0,px_maxmin(matrix','metric',numLands,'n')]'; else error('input EorD must be either character e or character d') end function [L, DL, R] = px_maxmin(varargin) %PX_MAXMIN -- select landmark points by greedy optimisation % % Given a set of N points, PX_MAXMIN selects a subset of n points called % 'landmark' points by an interative greedy optimisation. Specifically, % when j landmark points have been chosen, the (j+1)-st landmark point % maximises the function 'minimum distance to an existing landmark point'. % % The initial landmark point is arbitrary, and may be chosen randomly or % by decree. More generally, the process can be 'seeded' by up to k % landmark points chosen randomly or by decree. % % The input data can belong to one of the following types: % % 'vector': set of d-dimensional Euclidean points passed to the % function as d-by-N matrix % % 'metric': N-by-N matrix of distances % % 'rows': function handle with one vector argument I=[i1,i2,...,ip] % which returns a p-by-N matrix of distances between the p % specified points and the full data set. % % The output L is a list of indices for the landmark points, presented in % the order of discovery. User-specified seeds are listed first, followed % by randomly chosen seeds. % % A second output argument, DL, returns the n-by-N matrix of distances % between landmark points and all data points. % % A third output argument, R, returns the covering number of the landmark % set. R is the smallest number such that every data point lies within % distance R of a landmark point. % % Syntax: % % L = PX_MAXMIN(data1, type1, data2, type2, ...); % [L, DL] = PX_MAXMIN(data1, type1, data2, type2, ...); % [L, DL, R] = PX_MAXMIN(data1, type1, data2, type2, ...); % % Each pair (data, type) is one of the following: % % (X, 'vector'), (D, 'metric'), (fD,'rows') % % (n, 'n') -- number of landmarks % % (S, 'seeds') -- list of seeds specified by the user; no repeats are % allowed. % % (k, 'rand') -- number of randomly chosen seeds % % The pairs may be listed in any order. The type strings are sensitive to % case. Exactly one of {X, D, fD} must be specified, and n must always be % specified. % % Both of {k, S} are optional arguments. If S is specified, and is not % the empty list, then k=0 is the default. Otherwise, the defaults are % k=1, S=[]. % % The function PX_LANDMARKD is a C++ version of PX_MAXMIN and may be used % instead. The syntax and functionality are slightly different. % %Plex Metric Data Toolbox version 2.5 by Vin de Silva, Patrick Perry and %contributors. See PX_PLEXINFO for credits and licensing information. %Released with Plex version 2.5. [2006-Jul-14] % [2004-May-06] Modifications: % -replacing @local_euclid with @local_euclid2 % -returning R as an output argument % % [2004-May-24] -speed up 'min' step using incremental updates. % -R now returns the *next* value of MaxMin. % % [2004-Apr-28] Vin de Silva, Department of Mathematics, Stanford. %---------------------------------------------------------------- % collate the input variables %---------------------------------------------------------------- types = {'vector', 'metric', 'rows', 'n', 'seeds', 'rand'}; if any(~ismember(varargin(2:2:end), types)) error('Invalid data type specified.') end if (nargin ~= (2 * length(unique(varargin(2:2:end))))) error('Repeated or missing data types.') end [isused, input_ix] = ismember(types, varargin(2: 2: end)); if (sum(isused(1:3)) ~= 1) error('Points must be specified in exactly one of the given formats.') end if ~isused(4) error('Number of landmarks must be specifed.') end %---------------------------------------------------------------- % standardize the input %---------------------------------------------------------------- %------------------------------------------------ % By the end of this section, feval(Dfun,list) % will return D(list,:), whichever the input % format of the data %------------------------------------------------ dataformat = find(isused(1:3)); % which format have the data been % entered in? switch dataformat case 1 % 'vector' X = varargin{2*input_ix(1)-1}; [d,N] = size(X); %Dfun = @local_euclid; L2sq = sum(X.^2,1); % these values are repeatedly used: Dfun = @local_euclid2; % optimised to take advantage of this case 2 % 'metric' D = varargin{2*input_ix(2)-1}; N = length(D); Dfun =@local_submatrix; case 3 % 'rows' Dfun = varargin{2*input_ix(3)-1}; N = size(feval(Dfun,1), 2); end %------------------------------------------------ % collect n %------------------------------------------------ n = varargin{2*input_ix(4)-1}; %------------------------------------------------ % determine seeding %------------------------------------------------ if isused(5) S = varargin{2*input_ix(5)-1}; if (length(S) ~= length(unique(S))) error('S must not contain repeated elements.') end else S = []; end if isused(6) k = varargin{2*input_ix(6)-1}; elseif isempty(S) k = 1; else k = 0; end %---------------------------------------------------------------- % main loop %---------------------------------------------------------------- s = length(S); if (n < s + k) error('Too many seeds!') end % read in seed points from S L = zeros(1,n); L(1: s) = S; unused = setdiff((1:N), S); if (length(unused) ~= (N-s)) error('Seeds specified incorrectly.') end % generate random seed points foo = randperm(N-s); randseeds = unused(foo(1:k)); clear foo L(s+1: s+k) = randseeds; % generate remaining landmarks by maxmin DD = zeros(n, N); DD((1: s+k), :) = feval(Dfun, L(1: s+k)); DDmin = min(DD((1:s+k),:), [], 1); for a = (s+k+1: n) [r, newL] = max(DDmin, [], 2); L(a) = newL; DD(a,:) = feval(Dfun, newL); DDmin = min(DDmin, DD(a,:)); end r = max(DDmin); %---------------------------------------------------------------- % finish! %---------------------------------------------------------------- if (nargout >= 2) DL = DD; end if (nargout >= 3) R = r; end return %---------------------------------------------------------------- % local functions %---------------------------------------------------------------- function DD = local_euclid(list); X = evalin('caller', 'X'); [d,N] = size(X); DD = sqrt(max(0, repmat(sum(X(:,list).^2, 1)', [1 N]) ... + repmat(sum(X.^2, 1), [length(list) 1]) ... - 2 * X(:, list)' * X)); %---------------------------------------------------------------- function DD = local_euclid2(list); X = evalin('caller', 'X'); [d,N] = size(X); L2sq = evalin('caller','L2sq'); DD = sqrt(max(0, repmat(L2sq(list)', [1 N]) ... + repmat(L2sq, [length(list) 1]) ... - 2 * X(:, list)' * X)); %---------------------------------------------------------------- function DD = local_submatrix(list); D = evalin('caller', 'D'); DD = D(list, :); %----------------------------------------------------------------
github
umariqb/3D_Pose_Estimation_CVPR2016-master
kDensitySlow.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/JPlex/kDensitySlow.m
14,268
utf_8
05805720e2157587c9ae55434b4fe184
function densities = kDensitySlow(points, k) % INPUT: % points - N x n matrix of N points in R^n % k - positive integer less than N. This integer is a parameter for our % density estimate. % % OUTPUT: % densities - vertical vector of length N whose i-th entry is the % estimated density of the i-th point. The estimated density at a % point is the reciprocal of the distance from that point to its % k-th closest neighbor. % % NOTES: % The function kDensitySlow.m uses the function slmetric_pw.m, written by % Dahua Lin, to compute distance matrices. Please see % http://www.mathworks.com/matlabcentral/fileexchange/15935-computing-pairwise-distances-and-metrics % for more information about the function slmetric_pw.m. % % File kdDensitySlow.m is slow for large datasets (thus the name). If you % are interested in a faster version, please email Henry at % [email protected]. The faster version relies on a MATLAB kd-tree % package available here: % http://www.mathworks.com/matlabcentral/fileexchange/21512-kd-tree-for-matlab % % [email protected] % CONSTANTS: blockSize = 500; % If blockSize too small, the function will be slower than % it would be otherwise. If blockSize is too large, there will not be % enough memory for the computation. My default is blockSize = 500. maxMatrixSize = 25000000; % This m-file will not create a matrix bigger than % maxMatrixSize. Constant blocksize will be lowered so that % N*blockSize<=maxMatrixSize. N = size(points,1); % N is the number of points if N*blockSize > maxMatrixSize blockSize = floor(maxMatrixSize/N); disp('Constant blockSize has been lowered. Expect a very long computation time. Please open m-file kDensitySlow.m for details.') end densities = zeros(N,1); for i = 1:floor(N/blockSize) distances = slmetric_pw(points', points(blockSize*(i-1)+1:blockSize*i,:)', 'eucdist'); sortedDistances = sort(distances); densities(blockSize*(i-1)+1:blockSize*i) = 1./sortedDistances(k+1,:)'; end %remaining points nextPoint = floor(N/blockSize)*blockSize+1; if nextPoint <= N distances = slmetric_pw(points', points(nextPoint:N,:)', 'eucdist'); sortedDistances = sort(distances); densities(nextPoint:N) = 1./sortedDistances(k+1,:)'; end function M = slmetric_pw(X1, X2, mtype, varargin) %SLMETRIC_PW Compute the metric between column vectors pairwisely % % [ Syntax ] % - M = slmetric_pw(X1, X2, mtype); % - M = slmetric_pw(X1, X2, mtype, ...); % % [ Arguments ] % - X1, X2: the sample matrices % - mtype: the string indicating the type of metric % - M: the resulting metric matrix % % [ Description ] % - M = slmetric_pw(X1, X2, mtype) Computes the metrics between % column vectors of X1 and X2 pairwisely, using the metric % specified by mtype. % % Both X1 and X2 are matrices with each column representing a % sample. X1 and X2 should have the same number of rows. Suppose % the size of X1 is d x n1, and the size of X2 is d x n2. Then % the output metric matrix M will be of size n1 x n2, in which % M(i, j) is the metric value between X1(:,i) and X2(:,j). % % - M = slmetric_pw(X1, X2, mtype, ...) Some metric types requires % extra parameters, which should be specified in params. % % The supported metrics of this function are listed as follows: % \{: % - eucdist: Euclidean distance: % $ ||x - y|| $ % % - sqdist: Square of Euclidean distance: % $ ||x - y||^2 $ % % - dotprod: Canonical dot product: % $ <x,y> = x^T * y $ % % - nrmcorr: Normalized correlation (cosine angle): % $ (x^T * y ) / (||x|| * ||y||) $ % % - corrdist: Normalized Correlation distance % $ 1 - nrmcorr(x, y) $ % % - angle: Angle between two vectors (in radian) % $ arccos (nrmcorr(x, y)) $ % - quadfrm: Quadratic form: % $ x^T * Q * y $ % Q is specified in the 1st extra parameter % % - quaddiff: Quadratic form of difference: % $ (x - y)^T * Q * (x - y) $ % Q is specified in the 1st extra parameter % % - cityblk: City block distance (abssum of difference) % $ sum_i |x_i - y_i| $ % % - maxdiff: Maximum absolute difference % $ max_i |x_i - y_i| $ % % - mindiff: Minimum absolute difference % $ min_i |x_i - y_i| $ % % - minkowski: Minkowski distance % $ (\sum_i |x_i - y_i|^p)^(1/p) $ % The order p is specified in the 1st extra parameter % % - wsqdist: Weighted square of Euclidean distance % $ \sum_i w_i (x_i - y_i)^2 $ % the weights w is specified in 1st extra parameter % as a d x 1 column vector % % - hamming: Hamming distance with threshold t % \{ % ht1 = x > t % ht2 = y > t % d = sum(ht1 ~= ht2) % \} % use threshold t as the first extra param. % (by default, t is set to zero). % % - hamming_nrm: Normalized hamming distance, which equals the % ratio of the elements that differ. % \{ % ht1 = x > t % ht2 = y > t % d = sum(ht1 ~= ht2) / length(ht1) % \} % use threshold t as the first extra param. % (by default, t is set to zero). % % - intersect: Histogram Intersection % $ d = sum min(x, y) / min(sum(x), sum(y))$ % % - intersectdis: Histogram intersection distance % $ d = 1 - sum min(x, y) / min(sum(x), sum(y)) $ % % - chisq: Chi-Square Distance % $ d = sum (x(i) - y(i))^2/(2 * (x(i)+y(i))) $ % % - kldiv: Kull-back Leibler divergence % $ d = sum x(i) log (x(i) / y(i)) $ % % - jeffrey: Jeffrey divergence % $ d = KL(h1, (h1+h2)/2) + KL(h2, (h1+h2)/2) $ % \:} % % [ Remarks ] % - Both X1 and X2 should be a matrix of numeric values, except % for case when metric type is 'hamming' or 'hamming_nrm'. % For hamming or hamming_nrm metric, the input matrix can be logical. % % [ Examples ] % - Compute different types of metrics in pairwise manner % \{ % % prepare sample matrix % X1 = rand(10, 100); % X2 = rand(10, 150); % % % compute the euclidean distances (L2) % % between the samples in X1 and X2 % M = slmetric_pw(X1, X2, 'eucdist'); % % % compute the eucidean distances between the samples % % in X1 in a pairwise manner % M = slmetric_pw(X1, X1, 'eucdist'); % % % compute the city block distances (L1) % M = slmetric_pw(X1, X2, 'cityblk'); % % % compute the normalize correlations % M = slmetric_pw(X1, X2, 'nrmcorr'); % % % compute hamming distances % M = slmetric_pw(X1, X2, 'hamming', 0.5); % M2 = slmetric_pw((X1 > 0.5), (X2 > 0.5), 'hamming'); % assert(isequal(M, M2)); % \} % % - Compute the parameterized metrics % \{ % % compute weighted squared distances with user-supplied weights % weights = rand(10, 1); % M = slmetric_pw(X1, X2, 'wsqdist', weights); % % % compute quadratic distances (x-y)^T * Q (x-y) % Q = rand(10, 10); % M = slmetric_pw(X1, X2, 'quaddiff', Q); % % % compute Minkowski distance of order 3 % M = slmetric_pw(X1, X2, 'minkowski', 3); % \} % % [ History ] % - Created by Dahua Lin on Dec 06th, 2005 % - Modified by Dahua Lin on Apr 21st, 2005 % - regularize the error reporting % - Modified by Dahua Lin on Sep 11st, 2005 % - completely rewrite the core codes based on new mex computation % cores, and the runtime efficiency in both time and space is % significantly increased. % - Modified by Dahua Lin on Jul 02, 2007 % - rewrite the core computation based on the bsxfun introduced in % MATLAB R2007a % - rewrite the core-mex for cityblk, maxdiff, mindiff % - introduce new metrics: corrdist, minkowski % - Modified by Dahua Lin on Jul 30, 2007 % - Add the metric types for histograms, which are originally % implemented in slhistmetric_pw in sltoolbox v1. % - Modified by Dahua Lin on Aug 16, 2007 % - revise some of the help contents % %% parse and verify input arguments error(nargchk(3, inf, nargin)); assert(ischar(mtype), 'sltoolbox:slmetric_pw:invalidarg', ... 'The metric type should be a string.'); if strcmp(mtype, 'hamming') || strcmp(mtype, 'hamming_nrm') assert((isnumeric(X1) || islogical(X1)) && ndims(X1) == 2 && ... (isnumeric(X2) || islogical(X2)) && ndims(X2) == 2, ... 'sltoolbox:slmetric_pw:invalidarg', 'X1 and X2 should be numeric or logical matrices.'); else assert(isnumeric(X1) && ndims(X1) == 2 && isnumeric(X2) && ndims(X2) == 2, ... 'sltoolbox:slmetric_pw:invalidarg', 'X1 and X2 should be numeric matrices.'); end assert(isa(X2, class(X1)), ... 'sltoolbox:slmetric_pw:invalidarg', 'X1 and X2 should be of the same class.'); if isempty(X1) || isempty(X2) M = []; return; end %% compute switch mtype case {'eucdist', 'sqdist'} checkdim(X1, X2); M = bsxfun(@plus, sum(X1 .* X1, 1)', (-2) * X1' * X2); M = bsxfun(@plus, sum(X2 .* X2, 1), M); M(M < 0) = 0; if strcmp(mtype, 'eucdist') M = sqrt(M); end case 'dotprod' checkdim(X1, X2); M = X1' * X2; case {'nrmcorr', 'corrdist', 'angle'} checkdim(X1, X2); ns1 = sqrt(sum(X1 .* X1, 1)); ns2 = sqrt(sum(X2 .* X2, 1)); ns1(ns1 == 0) = 1; ns2(ns2 == 0) = 1; M = bsxfun(@times, X1' * X2, 1 ./ ns1'); M = bsxfun(@times, M, 1 ./ ns2); switch mtype case 'corrdist' M = 1 - M; case 'angle' M = real(acos(M)); end case 'quadfrm' Q = varargin{1}; M = X1' * Q * X2; case 'quaddiff' checkdim(X1, X2); Q = varargin{1}; M = X1' * (-(Q + Q')) * X2; M = bsxfun(@plus, M, sum(X1 .* (Q * X1), 1)'); M = bsxfun(@plus, M, sum(X2 .* (Q * X2), 1)); case 'cityblk' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(1)); case 'maxdiff' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(3)); case 'mindiff' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(2)); case 'minkowski' checkdim(X1, X2); pord = varargin{1}; if ~isscalar(pord) error('sltoolbox:slmetric_pw:invalidparam', ... 'the mikowski order should be a scalar'); end pord = cast(pord, class(X1)); M = pwmetrics_cimp(X1, X2, int32(4), pord); case 'wsqdist' d = checkdim(X1, X2); w = varargin{1}; if ~isequal(size(w), [d, 1]) error('sltoolbox:slmetric_pw:invalidparam', ... 'the weights should be given as a d x 1 vector.'); end wX2 = bsxfun(@times, X2, w); M = bsxfun(@plus, (-2) * X1' * wX2, sum(wX2 .* X2, 1)); clear wX2; wX1 = bsxfun(@times, X1, w); M = bsxfun(@plus, M, sum(wX1 .* X1, 1)'); case {'hamming', 'hamming_nrm'} checkdim(X1, X2); if islogical(X1) && islogical(X2) H1 = X1; H2 = X2; else if isempty(varargin) t = 0; else t = varargin{1}; assert(isnumeric(t) && isscalar(t), ... 'sltoolbox:slmetric_pw:invalidparam', 't should be a numeric scalar.'); end H1 = X1 > t; H2 = X2 > t; end M = pwhamming_cimp(H1, H2); if strcmp(mtype, 'hamming_nrm') M = M / size(H1, 1); end case 'intersect' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(5)); case 'intersectdis' checkdim(X1, X2); M = 1 - pwmetrics_cimp(X1, X2, int32(5)); case 'chisq' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(6)); case 'kldiv' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(7)); case 'jeffrey' checkdim(X1, X2); M = pwmetrics_cimp(X1, X2, int32(8)); otherwise error('sltoolbox:slmetric_pw:unknowntype', 'Unknown metric type %s', mtype); end %% Auxiliary function function d = checkdim(X1, X2) d = size(X1, 1); if d ~= size(X2, 1) error('sltoolbox:slmetric_pw:sizmismatch', ... 'X1 and X2 have different sample dimensions'); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
astar_search.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/matlab_bgl_new/astar_search.m
3,582
utf_8
528ff641877279dc012bed23ea2d9d21
function [d pred f]=astar_search(A,s,h,varargin) % ASTAR_SEARCH Perform a heuristically guided (A*) search on the graph. % % [d pred rank]=astar_search(A,s,h,optionsu) returns the distance map, % search tree and f-value of each node in an astar_search. % The search begins at vertex s. The heuristic h guides the search, % h(v) should be small close to a goal and large far from a goal. The % heuristic h can either be a vector with an entry for each vertex in the % graph or a function which maps vertices to values. % % This method works on non-negatively weighted directed graphs. % The runtime is O((E+V)log(V)). % % ... = astar_search(A,u,...) takes a set of % key-value pairs or an options structure. See set_matlab_bgl_options % for the standard options. % options.visitor: a visitor to use with the A* search (see Note) % options.inf: the value to use for unreachable vertices % [double > 0 | {Inf}] % options.target: a special vertex that will stop the search when hit % [{'none'} | any vertex number besides the u]; this is ignored if % a visitor is set. % options.edge_weight: a double array over the edges with an edge % weight for each node, see EDGE_INDEX and EXAMPLES/REWEIGHTED_GRAPHS % for information on how to use this option correctly % [{'matrix'} | length(nnz(A)) double vector] % % Note: You can specify a visitor for this algorithm. The visitor has the % following optional functions. % vis.initialize_vertex(u) % vis.discover_vertex(u) % vis.examine_vertex(u) % vis.examine_edge(ei,u,v) % vis.edge_relaxed(ei,u,v) % vis.edge_not_relaxed(ei,u,v) % vis.black_target(ei,u,v) % vis.finish_vertex(u) % Each visitor parameter should be a function pointer, which returns 0 % if the search should stop. (If the function does not return anything, % the algorithm continues.) % % Example: % load graphs/bgl_cities.mat % goal = 11; % Binghamton % start = 9; % Buffalo % % Use the euclidean distance to the goal as the heuristic % h = @(u) norm(xy(u,:) - xy(goal,:)); % % Setup a routine to stop when we find the goal % ev = @(u) (u ~= goal); % [d pred f] = astar_search(A, start, h, ... % struct('visitor', struct('examine_vertex', ev))); % David Gleich % Copyright, Stanford University, 2006-2008 %% History % 2007-04-20: Added edge weight option % 2007-07-12: Fixed edge_weight documentation. % 2008-10-07: Changed options parsing %% [trans check full2sparse] = get_matlab_bgl_options(varargin{:}); if full2sparse && ~issparse(A), A = sparse(A); end options = struct('inf', Inf, 'edge_weight', 'matrix', 'target', 'none'); options = merge_options(options,varargin{:}); edge_weight_opt = 'matrix'; if strcmp(options.edge_weight, 'matrix') % do nothing if we are using the matrix weights else edge_weight_opt = options.edge_weight; end if strcmp(options.target,'none') target = 0; % a flag used to denote "no target" to the mex elseif isa(options.target, 'double') target = options.target; else error('matlab_bgl:invalidParameter', ... 'options.target is not ''none'' or a vertex number.'); end if check, check_matlab_bgl(A,struct()); end if trans, A = A'; end function hi=vec2func(u) hi = h(u); end if isa(h,'function_handle') hfunc = h; else hfunc = @vec2func; end if isfield(options,'visitor') [d pred f] = astar_search_mex(A,s,target,hfunc,options.inf,edge_weight_opt,options.visitor); else [d pred f] = astar_search_mex(A,s,target,h,options.inf,edge_weight_opt); end % end the main function end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
grid_graph.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/matlab_bgl_new/grid_graph.m
2,553
utf_8
4c43dba3494901741531114e9307da9f
function [A coords] = grid_graph(varargin) % GRID_GRAPH Generate a grid graph or hypergrid graph % % [A xy] = grid_graph(m,n) generates a grid graph with m vertices along the % x axis and n vertices along the y axis. The xy output gives the 2d % coordinates of each vertex. % [A xyz] = grid_graph(m,n,k) generates a grid graph with m vertices along % the x axis, n vertices along the y axis, and k vertices along the z axis. % The xyz output gives the 3d coordinates of each vertex. % [A X] = grid_graph(d1, d2, ..., dk) generates a hypergrid graph in k % dimensions with d1 vertices along dimension 1, d2 vertices along % dimension 2, ..., and dk vertices along the final dimension. The X % output gives the k dimensional coordinates of each vertex. % [A X] = grid_graph([d1, d2, ..., dk]) is an alternate input scheme. % % Example: % [A xy] = grid_graph(5,10); % gplot(A,xy); % A = grid_graph(2*ones(1,10)); % compute 10d hypercube % David Gleich % Copyright, Stanford University, 2007-2008 %% History % 2007-07-13: Initial version %% k = length(varargin); if k==1 && numel(varargin{1}) > 1 varargin = num2cell(varargin{1}); k = length(varargin); else if any(cellfun('prodofsize',varargin)~=1) error('matlab_bgl:invalidArgument',... 'please specific the size of dimension in the arguments'); end end dims=cell(k,1); dim_size = cell2mat(varargin(end:-1:1)); A = sparse(1); for ii=1:length(dim_size) n2 = dim_size(ii); dims{ii} = linspace(0,1,n2); %A = kron(A,line_graph(n2)) + kron(line_graph(n2),speye(size(A,1))); A = kron(speye(size(A,1)), line_graph(n2)) + kron(A,speye(n2)); end % retarded, but it'll have to do... if (nargout > 1) if (k == 1) % this case is easy enough n = dim_size(1); coords = (0:n-1)'./(n-1); else % Matlab's ndgrid does something different for one dimension % we also have to reverse the output and get each component of the % output. coords_cell = cell(k,1); cmdstr = '['; for ii=1:k cmdstr = [cmdstr sprintf('coords_cell{%i} ',k-ii+1)]; %#ok end cmdstr = [cmdstr '] = ndgrid(dims{:});']; eval(cmdstr); coords = zeros(size(A,1),k); for ii=1:k coords(:,ii) = reshape(permute(coords_cell{ii},k:-1:1),size(A,1),1); end end end function [Al] = line_graph(n) e = ones(n,1); Al = spdiags([e e], [-1 1], n, n);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
path_histogram.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/matlab_bgl_new/custom/path_histogram.m
2,057
utf_8
8ba677da99d2a4a4e26d41487c0ea5db
function [l c] = path_histogram(G,varargin) % PATH_HISTOGRAM Compute a histogram of all shortest paths in graph G % % [l c] = path_histogram(G) computes all shortest paths in A one at a time % and forms the histogram of the shortest distances between all vertices. % % [l c] = path_histogram(G,struct('sample',N)) uses N random samples instead of an % exact solution. (N=0 uses exact solution) % % Options: % options.weighted: use Dijkstra algorithm for weighted paths [{0} | 1] % options.intcount: use integer histogram bins [0 | {1}] % options.nbins: number of bins when intcount=0 [{50} | positive integer] % options.sample: use N iid samples instead of all sources % [{0} | positive integer] % options.verbose: output status for long runs [{0} | 1] % % Example: % load('graphs/cs-stanford.mat'); % [l c] = path_histogram(A); % bar(l,c,[min(l),max(l)],'hist'); % % David Gleich % Copyright, Stanford University, 2008 % % History % 2008-03-14: Initial coding by David options=struct('weighted',0,'intcount',1,'nbins',50','sample',0,'istrans',0,... 'verbose',0); if ~isempty(varargin), options = merge_structs(varargin{1}, options); end if ~options.istrans, G = G'; end bfsoptions=struct('istrans',1); n=size(G,1); verb=options.verbose; N = options.sample; if N==0, vs=1:n; N = n; else vs=ceil(n*rand(options.sample,1)); end % sample from all vertices H=sparse(n,1); t0=clock; p=1; Np=min(N,100); for vi=1:N if verb && vi==(p*floor(N/Np) + max(mod(N,Np)-(Np-p),0)) dt=etime(clock,t0); p=p+1; fprintf(' %5.1f : %9i of %9i; etr=%7f sec\n', ... 100*(p-1)/Np, vi, N, N*dt/vi-dt); end di=bfs(G,vi,bfsoptions); di=di(di>0); % only use reachable points H=H+accumarray(di,1,[n 1],@sum,0,true); bfsoptions.nocheck=1; % don't repeat options check end l = find(H); c = nonzeros(H); end % internal copy of merge_structs function S=merge_structs(A,B) S = A; fn = fieldnames(B); for ii = 1:length(fn), if (~isfield(A, fn{ii})), S.(fn{ii}) = B.(fn{ii}); end, end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
bacon_numbers.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/matlab_bgl_new/examples/bacon_numbers.m
939
utf_8
6f7f6c07dfde59ec0fd693b43e29e93f
function bn = bacon_numbers(A,u) % BACON_NUMBERS Compute the Bacon numbers for a graph. % % bn = bacon_numbers(A,u) computes the Bacon numbers for all nodes in the % graph assuming that Kevin Bacon is node u. % allocate storage for the bacon numbers % the ipdouble call allocates storage that can be modified in place. bn_inplace = ipdouble(zeros(num_vertices(A),1)); % implement a nested function that can refer to variables we declare. In % this case, we refer to the bn_inplace variable. function tree_edge(ei,u,v) bn_inplace(v) = bn_inplace(u)+1; end % setup the bacon_recorder visitor bacon_recorder = struct(); bacon_recorder.tree_edge = @tree_edge; % call breadth_first_search breadth_first_search(A,u,bacon_recorder); % convert the inplace storage back to standard Matlab storage to return. bn = double(bn_inplace); % the end line is required with nested functions to terminate the file end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
rtest_1.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/matlab_bgl_new/test/rtest_1.m
1,767
utf_8
591edf7b20b839883d608054412f6829
function rval=rtest_1() n = 49; [A,b] = testmat(n,2); x0 = [1:n]'/(n+1); y0 = [1:n]'/(n+1); x = repmat(x0,1,n); y = repmat(y0',n,1); xy = [x(:),y(:)]; rval = 0; try T = mst(A); T = T + diag(diag(A)); rval = 1; catch lasterr end; try A(1,2)= -1; A(2,1)= -1; T = prim_mst(A); rval = 0; catch rval = 1; end; function [A,b] = testmat( n,stencil ) h = 1/(n+1); % initialization x = [1:n]'/(n+1); y = [1:n]'/(n+1); u = zeros(n,n); % exact solution u0 = repmat(x.^4,1,n) + repmat(12*y'.^2,n,1); % matices T0 = -ones(n); T0 = sparse( triu(tril(T0,-1),-1) + triu(tril(T0,1),1) ); I = speye(n); if stencil == 1 T = (-8*I - T0) / 3; B = (I - T0) / 3; else T = (-20*I - 4*T0) / 6; B = (4*I - T0) / 6; end A = kron(I,T) - kron(T0,B); % boundary b = zeros(n); if stencil == 1 b(1,:) = b(1,:) + 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2; b(n,:) = b(n,:) + 3 + 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2; b(:,1) = b(:,1) + x.^2 + (x-h).^2 + (x+h).^2; b(:,n) = b(:,n) + x.^2 + (x-h).^2 + (x+h).^2 + 12*3; else b(1,:) = b(1,:) + 4* 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2; b(n,:) = b(n,:) + 6 + 4* 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2; b(:,1) = b(:,1) + 4* x.^2 + (x-h).^2 + (x+h).^2; b(:,n) = b(:,n) + 4* x.^2 + (x-h).^2 + (x+h).^2 + 12*6; end % fix corners b(1,n) = b(1,n) - 12; b(n,1) = b(n,1) - 1; b(n,n) = b(n,n) - 13; % normalize if stencil == 1 b = - b / 3; else b = - b / 6; end % add source f = 12*x.^2 + 24; f = repmat(f,1,n); b = b + f * h^2; b = b(:); return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
rtest_6.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/matlab_bgl_new/test/rtest_6.m
609
utf_8
eb8fb5b91bb3daf03c595491cc14de96
function rval = rtest_6() rval = 0; try % create a line graph n = 10; A = sparse(1:n-1,2:n,1,n,n); A = A+A'; u = 1; v = 5; d = dist_uv(A,u,v); if any(d(v+1:end) > 0) error('breadth_first_search did not stop correctly'); end rval = 1; catch lasterr end end function dmap = dist_uv(A,u,v) vstar = v; dmap = ipdouble(zeros(size(A,1),1)); function stop=on_tree_edge(ei,u,v) dmap(v) = dmap(u)+1; stop = (v ~= vstar); end breadth_first_search(A,u,struct('tree_edge',@on_tree_edge)); dmap = double(dmap); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
stdrinv.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/MultivariateAnalysisToolbox/Statistics/stdrinv.m
2,424
utf_8
edac77861bbaf484b520a61afc312925
function x = stdrinv(p, v, r) %STDRINV Compute inverse c.d.f. for Studentized Range statistic % STDRINV(P,V,R) is the inverse cumulative distribution function for % the Studentized range statistic for R samples and V degrees of % freedom, evaluated at P. % Copyright 1993-2002 The MathWorks, Inc. % $Revision: 1.3 $ $Date: 2002/02/04 18:52:50 $ % Based on Fortran program from statlib, http://lib.stat.cmu.edu % Algorithm AS 190 Appl. Statist. (1983) Vol.32, No. 2 % Incorporates corrections from Appl. Statist. (1985) Vol.34 (1) if (length(p)>1 | length(v)>1 | length(r)>1), error('STDRINV requires scalar arguments.'); % for now end [err,p,v,r] = distchck(3,p,v,r); if (err > 0), error('Non-scalar arguments must match in size.'); end % Handle illegal or trivial values first. x = zeros(size(p)); if (length(x) == 0), return; end ok = (v>0) & (v==round(v)) & (r>1) & (r==round(r) & (p<1)); x(~ok) = NaN; ok = ok & (p>0); v = v(ok); p = p(ok); r = r(ok); if (length(v) == 0), return; end xx = zeros(size(v)); % Define constants jmax = 20; pcut = 0.00001; tiny = 0.000001; upper = (p > .99); if (upper) uppertail = 'u'; p0 = 1-p; else uppertail = 'l'; p0 = p; end % Obtain initial values q1 = qtrng0(p, v, r); p1 = stdrcdf(q1, v, r, uppertail); xx = q1; if (abs(p1-p0) >= pcut*p0) if (p1 > p0), p2 = max(.75*p0, p0-.75*(p1-p0)); end if (p1 < p0), p2 = p0 + (p0 - p1) .* (1 - p0) ./ (1 - p1) * 0.75; end if (upper) q2 = qtrng0(1-p2, v, r); else q2 = qtrng0(p2, v, r); end % Refine approximation for j=2:jmax p2 = stdrcdf(q2, v, r, uppertail); e1 = p1 - p0; e2 = p2 - p0; d = e2 - e1; xx = (q1 + q2) / 2; if (abs(d) > tiny*p0) xx = (e2 .* q1 - e1 .* q2) ./ d; end if (abs(e1) >= abs(e2)) q1 = q2; p1 = p2; end if (abs(p1 - p0) < pcut*p0), break; end q2 = xx; end end x(ok) = xx; % --------------------------------- function x = qtrng0(p, v, r) % Algorithm AS 190.2 Appl. Statist. (1983) Vol.32, No.2 % Calculates an initial quantile p for a studentized range % distribution having v degrees of freedom and r samples % for probability p, p.gt.0.80 .and. p.lt.0.995. t=norminv(0.5 + 0.5 .* p); if (v < 120), t = t + 0.25 * (t.^3 + t) ./ v; end q = 0.8843 - 0.2368 .* t; if (v < 120), q = q - (1.214./v) + (1.208.*t./v); end x = t .* (q .* log(r-1) + 1.4142);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
allstats.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/MultivariateAnalysisToolbox/Statistics/allstats.m
8,932
utf_8
ad81b07beeb64cd19b77ee49f11e54a6
function s = allstats(x,dim,flag,p) % ALLSTATS computes all common statistics. % ----------------------------- % s = allstats(x, dim, flag, p) % ----------------------------- % Description: computes, for a univariate data, a variety of statistical % properties, including mean, skewness, and kurtosis. % ALLSTATS All Common Statistics. % S = ALLSTATS(X,DIM,Flag) returns common statistics of the data in X along % the dimension DIM, with the variance type specified by Flag. % % X must be non-sparse, real, single or double, and 2D. NaNs contained in % X are consdered missing data and are ignored in computations. Note that % when X contains NaNs, this function will return different results than % those returned by the standard MATLAB functions MEAN, MEDIAN, and MODE, % STD and VAR because these function do not ignore NaNs. % % If DIM is [] or not given, DIM is the first non-singleton dimension of X. % % If Flag = 0 or [] or is not given, the variance is normalized by N-1. % If Flag = 1, the variance is normalized by N. % % S = ALLSTATS(X,DIM,Flag,P) in addition returns the additional percentiles % in vector P. P must contain numerical values between 0 and 100 exclusive. % % The output S is a structure containing the statistics with field names % describing the respective statistics: % % S.n = number of observations (excluding NaNs) % S.nan = number of NaNs % S.min = minimum % S.q1 = 25th percentile % S.median = median (50th percentile) % S.q3 = 75th percentile % S.max = maximum % S.mode = mode % S.mean = mean % S.std = standard deviation % S.var = variance % S.skew = skewness % S.kurt = kurtosis (= 3 for Gaussian or Normal Data) % S.p01 = first optional percentile % S.p02 = second optional percentile, etc. % % For vector data, outputs are scalars. % For matrix data, outputs are row vectors for DIM=1 % and column vectors for DIM=2. % % Reference: http://www.itl.nist.gov/div898/handbook/ % % Examples: % ALLSTATS(X) for vector X computes statistics along the vector, for matrix % X computes statistics for each column of X. % ALLSTATS(X,1) for matrix X computes statistics along the row dimension, % i.e., for each column of X. % ALLSTATS(X,2) for matrix X computes statistics along the column % dimension, i.e., for each row of X. % ALLSTATS(X,[],1) computes statistics along the first non-singleton % dimension of X, and normalizes the variance and standard deviation by N. % ALLSTATE(X,[],0,[2.5 10 90 97.5]) computes statistics along the first % non-singleton dimension and in addition returns 2.5%, 10%, 90% and 97.5% % percentiles. % % See also MAX, MIN, MEAN, MEDIAN, MODE, STD, VAR % Classification: Statistics % D.C. Hanselman, University of Maine, Orono, ME 04469 % [email protected] % Mastering MATLAB 7 % 2006-03-04, 2006-08-11 optional percentiles added % % The gracious assistance of John D'Errico and Urs Schwarz is hereby noted. if nargin<1 error('allstats:NotEnoughInputArguments',... 'At Least One Input Argument Required.') elseif ~isfloat(x) error('allstats:InvalidInput','Input X Must be Single or Double.') elseif ndims(x)>2 error('allstats:InvalidNumberofDimensions','X Must be 2D.') elseif issparse(x) error('allstats:NotFull','X Must Not be Sparse.') elseif ~isreal(x) error('allstats:NotReal','X Must be Real Valued.') end xsiz=size(x); if nargin<2 || isempty(dim) dim=find(xsiz>1,1); end if isempty(dim) || numel(dim)~=1 || fix(dim)~=dim || dim<1 || dim>ndims(x) error('allstats:DimOutofRange','DIM Invalid.') end if nargin<3 || (nargin==3 && isempty(flag)) flag=0; end if numel(flag)~=1 || (flag~=0 && flag~=1) error('allstate:InvalidInput','Flag Must be 0 or 1') end if nargin<4 % no optional P vector given p=[]; else % optional P vector exists if ~isnumeric(p) || any(p<=0) || any(p>=100) error('allstats:InvalidInput',... 'P must contain values between 0 and 100.') end p=p(:)/100; % convert percentiles to raw numbers pfn=reshape(sprintf('p%02d',1:length(p)),3,[])'; % field name char array end N=xsiz(dim); if N==1 % one observation along chosed DIM, return defaults sv=zeros(xsiz,class(x)); in=isnan(x); s=struct('n',double(~in),'nan',double(in),'min',x,'q1',x,'median',x,... 'q3',x,'max',x,'mode',x,'mean',x,'std',sv,'var',sv,... 'skew',sv,'kurt',sv); return else % create struct for output s=struct('n',[],'nan',[],'min',[],'q1',[],'median',[],'q3',[],'max',[],... 'mode',[],'mean',[],'std',[],'var',[],'skew',[],'kurt',[]); end tflag=false; if dim==2 % work along DIM=1, convert back later if needed x=x.'; tflag=true; % flag to note transpose taken end s.max=max(x); % built in max s.min=min(x); % built in min % To avoid redundant error checking and therefore maximize speed, implement % other statistical measures here rather than call their respective M-files. s.mean=nanmean(x,1); % mean xs=x-repmat(s.mean,N,1); % subtract mean from each column xss=xs.*xs; s.var=nanmean(xss,flag); % var s.std=sqrt(s.var); % std s.skew=nanmean(xss.*xs,flag)./s.var.^(1.5); % skew s.kurt=nanmean(xss.*xss,flag)./s.var.^2; % kurtosis xs=sort(x); % sort data down columns, this puts NaNs last inan=isnan(xs); % true for NaNs s.nan=sum(inan); % number of NaNs per column s.n=N-s.nan; % number of non-NaN observations per column ic=s.nan==0; % columns where there are no NaNs tmp=nan+zeros(size(s.mean),class(x)); % template s.q1=tmp; s.median=tmp; s.q3=tmp; if ~isempty(p) % place default output into optional percentiles for k=1:length(p) s.(pfn(k,:))=tmp; end end % process columns having no NaNs to find percentiles and median if any(ic) q=[0, (0.5:N -0.5)/N, 1]'; xx=[s.min(ic); xs(:,ic); s.max(ic)]; xq=interp1q(q,xx,[1;2;3]/4); % fast interp s.q1(ic)=xq(1,:); % q1 s.median(ic)=xq(2,:); % median s.q3(ic)=xq(3,:); % q3 if ~isempty(p) % handle optional percentiles xq=interp1q(q,xx,p); for k=1:length(p) s.(pfn(k,:))=xq(k,:); end end end % now process columns having NaNs for k=find(s.nan & s.n>3) % columns having fewer than 4 non-NaNs return NaN N=s.n(k); q=[0, (0.5:N -0.5)/N, 1]'; xx=[s.min(k); xs(1:N,k); s.max(k)]; xq=interp1q(q,xx,[1;2;3]/4); s.q1(k)=xq(1); % q1 s.median(k)=xq(2); % median s.q3(k)=xq(3); % q3 if ~isempty(p) % handle optional percentiles xq=interp1q(q,xx,p); for kk=1:length(p) s.(pfn(kk,:))(k)=xq(kk,:); end end end s.mode=tmp;% columns having fewer than 4 non-NaNs return NaN cols=1:size(xs,2); cols(s.n<4)=[]; for k=cols % get mode column by column N=s.n(k); y=[1;diff(xs(1:N,k))]~=0; % where distinct values begin m=diff([find(y);N+1]); % counts y=xs(y,k); % the unique values [idx,idx]=max(m); %#ok s.mode(k)=y(idx); % mode end if tflag && numel(s.min)~=1 % transpose data back for DIM = 2 s.n=s.n.'; s.nan=s.nan.'; s.min=s.min.'; s.q1=s.q1.'; s.median=s.median.'; s.q3=s.q3.'; s.max=s.max.'; s.mode=s.mode.'; s.mean=s.mean.'; s.var=s.var.'; s.std=s.std.'; s.skew=s.skew.'; s.kurt=s.kurt.'; if ~isempty(p) % handle optional percentiles for k=1:length(p) s.(pfn(k,:))=s.(pfn(k,:))'; end end end %-------------------------------------------------------------------------- function m=nanmean(x,flag) % mean along row dimension ignoring NaN elements % flag is zero to divide by N-1 % flag is one to divide by N bnan=isnan(x); % find NaNs in each column N=size(x,1)-sum(bnan); % number of non-NaNs in each column x(bnan)=0; % set NaN elements to zero m=nan+zeros(1,size(x,2),class(x)); % default NaN output idx=N>1; % columns that are not all NaNs m(idx)=sum(x(:,idx))./(N(idx)-1+flag); % results excluding NaNs
github
umariqb/3D_Pose_Estimation_CVPR2016-master
kalmanf.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/toolboxes/kalman/kalmanf.m
7,331
utf_8
24eadc4b403a096819f5de7899ee4a61
% KALMANF - updates a system state vector estimate based upon an % observation, using a discrete Kalman filter. % % Version 1.0, June 30, 2004 % % This tutorial function was written by Michael C. Kleder % % INTRODUCTION % % Many people have heard of Kalman filtering, but regard the topic % as mysterious. While it's true that deriving the Kalman filter and % proving mathematically that it is "optimal" under a variety of % circumstances can be rather intense, applying the filter to % a basic linear system is actually very easy. This Matlab file is % intended to demonstrate that. % % An excellent paper on Kalman filtering at the introductory level, % without detailing the mathematical underpinnings, is: % "An Introduction to the Kalman Filter" % Greg Welch and Gary Bishop, University of North Carolina % http://www.cs.unc.edu/~welch/kalman/kalmanIntro.html % % PURPOSE: % % The purpose of each iteration of a Kalman filter is to update % the estimate of the state vector of a system (and the covariance % of that vector) based upon the information in a new observation. % The version of the Kalman filter in this function assumes that % observations occur at fixed discrete time intervals. Also, this % function assumes a linear system, meaning that the time evolution % of the state vector can be calculated by means of a state transition % matrix. % % USAGE: % % s = kalmanf(s) % % "s" is a "system" struct containing various fields used as input % and output. The state estimate "x" and its covariance "P" are % updated by the function. The other fields describe the mechanics % of the system and are left unchanged. A calling routine may change % these other fields as needed if state dynamics are time-dependent; % otherwise, they should be left alone after initial values are set. % The exceptions are the observation vectro "z" and the input control % (or forcing function) "u." If there is an input function, then % "u" should be set to some nonzero value by the calling routine. % % SYSTEM DYNAMICS: % % The system evolves according to the following difference equations, % where quantities are further defined below: % % x = Ax + Bu + w meaning the state vector x evolves during one time % step by premultiplying by the "state transition % matrix" A. There is optionally (if nonzero) an input % vector u which affects the state linearly, and this % linear effect on the state is represented by % premultiplying by the "input matrix" B. There is also % gaussian process noise w. % z = Hx + v meaning the observation vector z is a linear function % of the state vector, and this linear relationship is % represented by premultiplication by "observation % matrix" H. There is also gaussian measurement % noise v. % where w ~ N(0,Q) meaning w is gaussian noise with covariance Q % v ~ N(0,R) meaning v is gaussian noise with covariance R % % VECTOR VARIABLES: % % s.x = state vector estimate. In the input struct, this is the % "a priori" state estimate (prior to the addition of the % information from the new observation). In the output struct, % this is the "a posteriori" state estimate (after the new % measurement information is included). % s.z = observation vector % s.u = input control vector, optional (defaults to zero). % % MATRIX VARIABLES: % % s.A = state transition matrix (defaults to identity). % s.P = covariance of the state vector estimate. In the input struct, % this is "a priori," and in the output it is "a posteriori." % (required unless autoinitializing as described below). % s.B = input matrix, optional (defaults to zero). % s.Q = process noise covariance (defaults to zero). % s.R = measurement noise covariance (required). % s.H = observation matrix (defaults to identity). % % NORMAL OPERATION: % % (1) define all state definition fields: A,B,H,Q,R % (2) define intial state estimate: x,P % (3) obtain observation and control vectors: z,u % (4) call the filter to obtain updated state estimate: x,P % (5) return to step (3) and repeat % % INITIALIZATION: % % If an initial state estimate is unavailable, it can be obtained % from the first observation as follows, provided that there are the % same number of observable variables as state variables. This "auto- % intitialization" is done automatically if s.x is absent or NaN. % % x = inv(H)*z % P = inv(H)*R*inv(H') % % This is mathematically equivalent to setting the initial state estimate % covariance to infinity. % % SCALAR EXAMPLE (Automobile Voltimeter): % % % Define the system as a constant of 12 volts: % clear s % s.x = 12; % s.A = 1; % % Define a process noise (stdev) of 2 volts as the car operates: % s.Q = 2^2; % variance, hence stdev^2 % % Define the voltimeter to measure the voltage itself: % s.H = 1; % % Define a measurement error (stdev) of 2 volts: % s.R = 2^2; % variance, hence stdev^2 % % Do not define any system input (control) functions: % s.B = 0; % s.u = 0; % % Do not specify an initial state: % s.x = nan; % s.P = nan; % % Generate random voltages and watch the filter operate. % tru=[]; % truth voltage % for t=1:20 % tru(end+1) = randn*2+12; % s(end).z = tru(end) + randn*2; % create a measurement % s(end+1)=kalmanf(s(end)); % perform a Kalman filter iteration % end % figure % hold on % grid on % % plot measurement data: % hz=plot([s(1:end-1).z],'r.'); % % plot a-posteriori state estimates: % hk=plot([s(2:end).x],'b-'); % ht=plot(tru,'g-'); % legend([hz hk ht],'observations','Kalman output','true voltage',0) % title('Automobile Voltimeter Example') % hold off function s = kalmanf(s) % set defaults for absent fields: if ~isfield(s,'x'); s.x=nan*z; end if ~isfield(s,'P'); s.P=nan; end if ~isfield(s,'z'); error('Observation vector missing'); end if ~isfield(s,'u'); s.u=0; end if ~isfield(s,'A'); s.A=eye(length(x)); end if ~isfield(s,'B'); s.B=0; end if ~isfield(s,'Q'); s.Q=zeros(length(x)); end if ~isfield(s,'R'); error('Observation covariance missing'); end if ~isfield(s,'H'); s.H=eye(length(x)); end if isnan(s.x) % initialize state estimate from first observation if diff(size(s.H)) error('Observation matrix must be square and invertible for state autointialization.'); end s.x = inv(s.H)*s.z; s.P = inv(s.H)*s.R*inv(s.H'); else % This is the code which implements the discrete Kalman filter: % Prediction for state vector and covariance: s.x = s.A*s.x + s.B*s.u; s.P = s.A * s.P * s.A' + s.Q; % Compute Kalman gain factor: K = s.P*s.H'*inv(s.H*s.P*s.H'+s.R); % Correction based on observation: s.x = s.x + K*(s.z-s.H*s.x); s.P = s.P - K*s.H*s.P; % Note that the desired result, which is an improved estimate % of the sytem state vector x and its covariance P, was obtained % in only five lines of code, once the system was defined. (That's % how simple the discrete Kalman filter is to use.) Later, % we'll discuss how to deal with nonlinear systems. end return
github
umariqb/3D_Pose_Estimation_CVPR2016-master
plotSnippetsAndCoeffs.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/plotTools/plotSnippetsAndCoeffs.m
4,412
utf_8
8c1b2f6c8b785c3298ecad7bd7bd78e4
function plotSnippetsAndCoeffs(hit) % tmp=hit.startFrames; % tmp(2,:)=hit.endFrames-(tmp(1,:)); % tmp=[tmp [0;hit.orgNumFrames]]; YLabels{1,1}='dummy'; for i=1:hit.numHits contains=strfind(YLabels,hit.hitProperties{i}.motionClass{1}); gra=0; for gr=1:size(contains,1) if ~isempty(contains{gr}) && ... (length(YLabels{gr})==length(hit.hitProperties{i}.motionClass{1})) gra=gra + 1; end end if gra==0 YLabels=[YLabels; hit.hitProperties{i}.motionClass{1}]; end end YLabels{1}='Complete Motion'; % map=[1 1 1; 0.5 0 0]; % colormap(map); figure; gca=subplot(2,1,[1]); % line([1 hit.orgNumFrames],[1 1],'linewidth',5); for hitInd=1:hit.numHits contains=strfind(YLabels,hit.hitProperties{hitInd}.motionClass{1}); pos=1; while isempty(contains{pos}) pos=pos+1; end hand=line([hit.hitProperties{hitInd}.startFrame ... hit.hitProperties{hitInd}.endFrame], ... [pos pos], ... 'linewidth',20, ... 'color',[0.2 0.2 1]) ; set(hand, 'buttondownFcn', {@motionPlayerCallback2, ... hit.hitProperties{hitInd}.res.skel, ... hit.hitProperties{hitInd}.res.origMotCut, ... hit.hitProperties{hitInd}.res.skel, ... hit.hitProperties{hitInd}.res.recMot}); end hold on; % for i=1:size(tmp,2)-1 % colormap(map); % barh(i,tmp(1,i)+tmp(2,i),'stack','FaceColor','flat', ... % 'BarWidth',0.7,'EdgeColor','flat', ... % 'ButtonDownFcn',{@playResultOnClick, ... % Tensor, ... % hit.hitProperties{i}} ... % ); % % end % colormap(map); % barh(tmp','stack','FaceColor','flat', ... % 'BarWidth',0.7,'EdgeColor','flat'); axis([0 hit.orgNumFrames 1.5 size(YLabels,1)+0.5]); set(gca,'YTick',2:size(YLabels,1)); set(gca,'YTickLabel',YLabels(2:end,:)); set(gca,'XTick',1:100:hit.orgNumFrames); set(gca,'XTickLabel',0:100:hit.orgNumFrames); grid on; set(gca,'Layer','top') % % x2 = axes('Position',get(x1,'Position'),... % 'XAxisLocation','top',... % 'YAxisLocation','right',... % 'Color','none',... % 'XColor','k','YColor','k'); % set (x2 ,'YTick',1:hit.numHits+1); % set (x2 ,'YTickLabel',YLabels2); xlabel('Frames'); handTitle=title(hit.amc,'Interpreter','None'); set(handTitle, 'buttondownFcn', {@motionPlayerCallback3, ... hit.asf, ... hit.amc}); hold off; h2=subplot(2,1,[2]); set(h2,'NextPlot','replacechildren') set(h2,'ColorOrder',[1 0 0;0 1 0;0 0 1;0.5 0 0.5;0 0.5 0.5; 0.5 0.5 0]); [numHits,coeffs,styleList]=countHitsPerFrameAndCoefs(hit); % testcolors=lines(size(styleList,2)); testcolors=jet(size(styleList,2)); % testcolors=hot(size(styleList,2)); % testcolors=rand(size(styleList,2),3); hold on; for styleInd=1:size(styleList,2) plot(coeffs.(styleList{styleInd})','color',testcolors(styleInd,:),'linewidth',5); styleY=0.63-mod(styleInd,15)*0.02; styleX=0.0+floor(styleInd/15)*0.1; textH=annotation('textbox',[ styleX styleY 0.1 0.025]); set(textH,'color',testcolors(styleInd,:)); set(textH,'string',styleList(styleInd)); set(textH,'EdgeColor','none'); end hold off; % countline=0; % for l1=1:hit.numHits % for l2=1:size(hit.hitProperties{l1}.styles,2) % colind=1; % while ~strcmp(styleList{colind},hit.hitProperties{l1}.styles{l2}) % colind=colind+1; % end % % countline=countline+1; % % % plot(coeffs(countline,:),'LineWidth',3,'color',testcolors(colind,:)); % end % end % legend on; % legend(styleList); % figure;surf(coeffs); axis([0 hit.orgNumFrames -0.2 1.2]); set(h2,'XTick',1:100:hit.orgNumFrames); set(h2,'XTickLabel',0:100:hit.orgNumFrames); grid on; % % h3=subplot(3,1,[3]); % % resE=plotRecErrors(hit); % % axis([0 hit.orgNumFrames 0 50]); % % set(h3,'XTick',1:100:hit.orgNumFrames); % % set(h3,'XTickLabel',0:100:hit.orgNumFrames); % % grid on; end function motionPlayerCallback2(src, eventdata, skel1, mot1, skel2, mot2) motionplayer('skel',{skel1 skel2}, 'mot', {mot1 mot2}); end function motionPlayerCallback3(src, eventdata, asf,amc) infos=fileparts(amc); [skel,mot]=readMocap(fullfile(infos,asf),amc); motionplayer('skel',{skel}, 'mot', {mot}); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
plotMultiLayerResult.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/plotTools/plotMultiLayerResult.m
6,061
utf_8
487664f58abd695aa4d63822205f034d
function plotMultiLayerResult(annotation,hits4File) global VARS_GLOBAL; motClasses = fieldnames(annotation); document=hits4File.amc; figure; set(gcf, 'renderer', 'painters') ; set(gcf, 'name', [document]); %% Collect Annotations for document. % hitData = classificationResult.(class)((classificationResult.(class)(:,1) == currentDocument), [2:3, 6]); h1=subplot(2,1,1); handle=title(document,'interpreter','none'); set(handle,'ButtonDownFcn',{@motionPlayerCallbackLoad, hits4File.amc,1,hits4File.orgNumFrames*4}); set(h1, 'ytick', [1.5:2:length(motClasses)*2]); set(h1, 'yticklabel', motClasses); set(h1, 'XTick',1:100:hits4File.orgNumFrames); set(h1, 'XTickLabel',0:100:hits4File.orgNumFrames); axis([0 hits4File.orgNumFrames 0.5 length(motClasses)*2+0.5]); for mClass=1:size(motClasses,1); line([1, hits4File.orgNumFrames], [2*mClass+0.5, 2*mClass+0.5]); hitData=zeros(1,2); count=1; if ~isempty(annotation.(motClasses{mClass})) for i=1:size(annotation.(motClasses{mClass}),1); if strcmp(strcat(VARS_GLOBAL.dir_root,annotation.(motClasses{mClass})(i,3)),document) hitData(count,:)=cell2mat(annotation.(motClasses{mClass})(i,1:2)); files{count}=annotation.(motClasses{mClass})(i,3); count=count+1; end end end for h=1:size(hitData, 1) hitStart = hitData(h, 1); hitEnd = hitData(h, 2); % remap from 30Hz to 120 Hz % animationStart = hitStart * 4 - 4 + 1; % animationEnd = hitEnd * 4 - 4 + 1; %draw rectangle color = [1 0 0]; %[0 127 14]/255; yPosition = mClass*2; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallbackLoad, fullfile(VARS_GLOBAL.dir_root,cell2mat(files{h})),hitData(h,1)*4,hitData(h,2)*4}); end % set(handle,'ButtonDownFcn',{@animateRectOnClick,... % docName,... % animationStart,... % animationEnd, ... % cost,... % hitStart,... % hitEnd,... % }); end end for hit=1:hits4File.numHits mClassStr = hits4File.hitProperties{1,hit}.motionClass; tmp=strfind(motClasses,cell2mat(mClassStr)); mClass=1; while isempty(cell2mat(tmp(mClass))) mClass=mClass+1; end hitStart=hits4File.startFrames(hit); hitEnd =hits4File.endFrames (hit); color = [0 0.7 0]; yPosition = 2*mClass-1; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallback1, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.orgMot}); end end %% Collect PartDTW Hits for Document! h2=subplot(2,1,2); %create styleList [numHits,coeffs,styleList]=countHitsPerFrameAndCoefs(hits4File); set(h2, 'ytick', 1:1:size(styleList,2)); set(h2, 'yticklabel', styleList); set(h2, 'XTick',1:100:hits4File.orgNumFrames); set(h2, 'XTickLabel',0:100:hits4File.orgNumFrames); for styInd=1:size(styleList,2) line([1, hits4File.orgNumFrames], [styInd+0.5, styInd+0.5]); end axis([0 hits4File.orgNumFrames 0.5 size(styleList,2)+0.5]); for hit=1:hits4File.numHits [maxval,maxPos]=max(hits4File.hitProperties{1,hit}.res.coeffsX{1}); subClass=hits4File.hitProperties{1,hit}.styles{maxPos}; tmp=strfind(styleList,subClass); mClass=1; while isempty(cell2mat(tmp(mClass))) mClass=mClass+1; end hitStart=hits4File.startFrames(hit); hitEnd =hits4File.endFrames (hit); if maxval>0.0 color=[0 0.7 0]; else color=[0 1 0]; end yPosition = mClass; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallback2, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.orgMot, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.recMotUnWarp}); end end end function motionPlayerCallback1(src, eventdata, skel1, mot1) motionplayer('skel',{skel1}, 'mot', {mot1}); end function motionPlayerCallback2(src, eventdata, skel1, mot1, skel2, mot2) motionplayer('skel',{skel1 skel2}, 'mot', {mot1 mot2}); end function motionPlayerCallbackLoad(src, eventdata, amc, startF, endF) infos=filename2info(amc); [skel,mot] =readMocap(fullfile(infos.amcpath,infos.asfname),amc); mot=cutMotion(mot,startF,endF); motionplayer('skel',{skel}, 'mot', {mot}); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
plotMultiLayerResult2Fig.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/plotTools/plotMultiLayerResult2Fig.m
7,834
utf_8
6d24c03809181e6d076bdf9aecbcbed6
function plotMultiLayerResult2Fig(annotation,hits4File, parameter) if nargin < 3 parameter = struct; end if isfield(parameter, 'printFigure') == 0 parameter.printFigure = 0; end if isfield(parameter, 'filenamePrefix') == 0 parameter.filenamePrefix = 'figures/tensorClassification_'; end if isfield(parameter, 'paperPositionClassification') == 0 parameter.paperPositionClassification = [1,1,6.3,2.5]; end if isfield(parameter, 'paperPositionPartDTW') == 0 parameter.paperPositionPartDTW = [1,1,6.3,2.5]; end if isfield(parameter, 'omitTitle') == 0 parameter.omitTitle = 0; end global VARS_GLOBAL; motClasses = flipud(fieldnames(annotation)); document=hits4File.amc; docLength = hits4File.orgNumFrames; figure(); set(gcf, 'renderer', 'painters') ; set(gcf, 'name', [document]); [temp, docShortName] = fileparts(document); set(gcf, 'position',[50 50 1000 440]); %% Collect Annotations for document. % hitData = classificationResult.(class)((classificationResult.(class)(:,1) == currentDocument), [2:3, 6]); % h1=subplot(2,1,1); if parameter.omitTitle == 0 handle=title(document,'interpreter','none'); set(handle,'ButtonDownFcn',{@motionPlayerCallbackLoad, hits4File.amc,1,hits4File.orgNumFrames*4}); end set(gca, 'ytick', [1.5:2:length(motClasses)*2]); set(gca, 'yticklabel', motClasses); % set(gca, 'XTick',1:100:hits4File.orgNumFrames); % set(gca, 'XTickLabel',0:100:hits4File.orgNumFrames); axis([0 hits4File.orgNumFrames 0.5 length(motClasses)*2+0.5]); for mClass=1:size(motClasses,1); line([1, hits4File.orgNumFrames], [2*mClass+0.5, 2*mClass+0.5]); hitData=zeros(1,2); count=1; if ~isempty(annotation.(motClasses{mClass})) for i=1:size(annotation.(motClasses{mClass}),1); if strcmp(strcat(VARS_GLOBAL.dir_root,annotation.(motClasses{mClass})(i,3)),document) hitData(count,:)=cell2mat(annotation.(motClasses{mClass})(i,1:2)); files{count}=annotation.(motClasses{mClass})(i,3); count=count+1; end end end for h=1:size(hitData, 1) hitStart = hitData(h, 1); hitEnd = hitData(h, 2); % remap from 30Hz to 120 Hz % animationStart = hitStart * 4 - 4 + 1; % animationEnd = hitEnd * 4 - 4 + 1; %draw rectangle color = [1 0 0]; %[0 127 14]/255; yPosition = mClass*2; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallbackLoad, fullfile(VARS_GLOBAL.dir_root,cell2mat(files{h})),hitData(h,1)*4,hitData(h,2)*4}); end % set(handle,'ButtonDownFcn',{@animateRectOnClick,... % docName,... % animationStart,... % animationEnd, ... % cost,... % hitStart,... % hitEnd,... % }); end end for hit=1:hits4File.numHits mClassStr = hits4File.hitProperties{1,hit}.motionClass; tmp=strfind(motClasses,cell2mat(mClassStr)); mClass=1; while isempty(cell2mat(tmp(mClass))) mClass=mClass+1; end hitStart=hits4File.startFrames(hit); hitEnd =hits4File.endFrames (hit); color = [0 0.7 0]; yPosition = 2*mClass-1; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallback1, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.orgMot}); end end line([docLength, docLength], [0.5, 2*length(motClasses)+0.5], 'Color', [0,0,0]); line([1, docLength], [2*length(motClasses)+0.5, 2*length(motClasses)+0.5], 'Color', [0,0,0]); if parameter.printFigure set(gcf, 'paperPosition', parameter.paperPositionPartDTW); filename = [parameter.filenamePrefix '_PartDTW_' docShortName '.eps']; print('-depsc2', filename); end %% Collect PartDTW Hits for Document! figure(); set(gcf, 'renderer', 'painters') ; set(gcf, 'name', [document]); set(gcf, 'position',[50 500 1000 440]); if parameter.omitTitle == 0 handle=title(document,'interpreter','none'); end %create styleList [numHits,coeffs,styleList]=countHitsPerFrameAndCoefs(hits4File); ylabels = renameSubclasses(styleList); set(gca, 'ytick', 1:1:size(styleList,2)); set(gca, 'yticklabel', ylabels); % set(gca, 'XTick',1:100:hits4File.orgNumFrames); % set(gca, 'XTickLabel',0:100:hits4File.orgNumFrames); for styInd=1:size(styleList,2) line([1, hits4File.orgNumFrames], [styInd+0.5, styInd+0.5]); end axis([0 hits4File.orgNumFrames 0.5 size(styleList,2)+0.5]); for hit=1:hits4File.numHits [maxval,maxPos]=max(hits4File.hitProperties{1,hit}.res.coeffsX{1}); subClass=hits4File.hitProperties{1,hit}.styles{maxPos}; tmp=strfind(styleList,subClass); mClass=1; while isempty(cell2mat(tmp(mClass))) mClass=mClass+1; end hitStart=hits4File.startFrames(hit); hitEnd =hits4File.endFrames (hit); if maxval>0.0 color=[0 0.7 0]; else color=[0 1 0]; end yPosition = mClass; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallback2, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.orgMot, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.recMotUnWarp}); end end line([docLength, docLength], [0.5, 2*length(motClasses)+0.5], 'Color', [0,0,0]); line([1, docLength], [length(styleList)+0.5, length(styleList)+0.5], 'Color', [0,0,0]); if parameter.printFigure set(gcf, 'paperPosition', parameter.paperPositionClassification); filename = [parameter.filenamePrefix '_Classification_' docShortName '.eps']; print('-depsc2', filename); end end function motionPlayerCallback1(src, eventdata, skel1, mot1) motionplayer('skel',{skel1}, 'mot', {mot1}); end function motionPlayerCallback2(src, eventdata, skel1, mot1, skel2, mot2) motionplayer('skel',{skel1 skel2}, 'mot', {mot1 mot2}); end function motionPlayerCallbackLoad(src, eventdata, amc, startF, endF) infos=filename2info(amc); [skel,mot] =readMocap(fullfile(infos.amcpath,infos.asfname),amc); mot=cutMotion(mot,startF,endF); motionplayer('skel',{skel}, 'mot', {mot}); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
C_forwardKinematicsWrapper.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/efficiency/C_forwardKinematicsWrapper.m
1,939
utf_8
85e2913a5509cecf6714dac9d41ed2fb
function [jointTrajectories,skel] = C_forwardKinematicsWrapper(skel,rootTranslation,rotationQuat) if nargin == 1 if ~isfield(skel,'parents') skel.parents = computeParentsLocal(skel); end if ~isfield(skel,'bones') skel.bones = computeBonesLocal(skel); end jointTrajectories = 0; else nframes = size(rootTranslation,2); if ~isfield(skel,'parents') skel.parents = computeParentsLocal(skel); end if ~isfield(skel,'bones') skel.bones = computeBonesLocal(skel); end if iscell(rotationQuat) if ~isempty(skel.unanimated) if isempty(rotationQuat{skel.unanimated(1)}) rotationQuat(skel.unanimated) = {[ ones(1,nframes); ... zeros(3,nframes)]}; end end rotationQuat = cell2mat(rotationQuat); end if size(rotationQuat,1)<skel.njoints*4 rotationQuat = [rotationQuat(1:4,:); ... ones(1,nframes); ... zeros(3,nframes); ... rotationQuat(5:20,:);... ones(1,nframes); ... zeros(3,nframes); ... rotationQuat(21:end,:)]; end jointTrajectories = C_forwardKinematics(skel.parents,skel.bones,rootTranslation,rotationQuat); end end function bones = computeBonesLocal(skel) bones = zeros(3,skel.njoints); for i=1:skel.njoints bones(:,i) = skel.nodes(i,1).offset; end end function parents = computeParentsLocal(skel) parents = zeros(1,skel.njoints); for i=1:skel.njoints parents(:,i) = skel.nodes(i,1).parentID; end end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
cmaes.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/cmaes.m
116,994
utf_8
966f8e72ff09eb059beb3cf37d4e50a0
function [xmin, ... % minimum search point of last iteration fmin, ... % function value of xmin counteval, ... % number of function evaluations done stopflag, ... % stop criterion reached out, ... % struct with various histories and solutions bestever ... % struct containing overall best solution (for convenience) ] = cmaes( ... fitfun, ... % name of objective/fitness function xstart, ... % objective variables initial point, determines N insigma, ... % initial coordinate wise standard deviation(s) inopts, ... % options struct, see defopts below varargin ) % arguments passed to objective function % cmaes.m, Version 3.61.beta, last change: April, 2012 % CMAES implements an Evolution Strategy with Covariance Matrix % Adaptation (CMA-ES) for nonlinear function minimization. For % introductory comments and copyright (GPL) see end of file (type % 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and, % without data logging and plotting, it should run under Octave % (Linux, package octave-forge is needed). % % OPTS = CMAES returns default options. % OPTS = CMAES('defaults') returns default options quietly. % OPTS = CMAES('displayoptions') displays options. % OPTS = CMAES('defaults', OPTS) supplements options OPTS with default % options. % % XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates an approximate minimum % XMIN of function FUN starting from column vector X0 with the initial % coordinate wise search standard deviation SIGMA. % % Input arguments: % % FUN is a string function name like 'frosen'. FUN takes as argument % a column vector of size of X0 and returns a scalar. An easy way to % implement a hard non-linear constraint is to return NaN. Then, % this function evaluation is not counted and a newly sampled % point is tried immediately. % % X0 is a column vector, or a matrix, or a string. If X0 is a matrix, % mean(X0, 2) is taken as initial point. If X0 is a string like % '2*rand(10,1)-1', the string is evaluated first. % % SIGMA is a scalar, or a column vector of size(X0,1), or a string % that can be evaluated into one of these. SIGMA determines the % initial coordinate wise standard deviations for the search. % Setting SIGMA one third of the initial search region is % appropriate, e.g., the initial point in [0, 6]^10 and SIGMA=2 % means cmaes('myfun', 3*rand(10,1), 2). If SIGMA is missing and % size(X0,2) > 1, SIGMA is set to sqrt(var(X0')'). That is, X0 is % used as a sample for estimating initial mean and variance of the % search distribution. % % OPTS (an optional argument) is a struct holding additional input % options. Valid field names and a short documentation can be % discovered by looking at the default options (type 'cmaes' % without arguments, see above). Empty or missing fields in OPTS % invoke the default value, i.e. OPTS needs not to have all valid % field names. Capitalization does not matter and unambiguous % abbreviations can be used for the field names. If a string is % given where a numerical value is needed, the string is evaluated % by eval, where 'N' expands to the problem dimension % (==size(X0,1)) and 'popsize' to the population size. % % [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ... % CMAES(FITFUN, X0, SIGMA) % returns the best (minimal) point XMIN (found in the last % generation); function value FMIN of XMIN; the number of needed % function evaluations COUNTEVAL; a STOPFLAG value as cell array, % where possible entries are 'fitness', 'tolx', 'tolupx', 'tolfun', % 'maxfunevals', 'maxiter', 'stoptoresume', 'manual', % 'warnconditioncov', 'warnnoeffectcoord', 'warnnoeffectaxis', % 'warnequalfunvals', 'warnequalfunvalhist', 'bug' (use % e.g. any(strcmp(STOPFLAG, 'tolx')) or findstr(strcat(STOPFLAG, % 'tolx')) for further processing); a record struct OUT with some % more output, where the struct SOLUTIONS.BESTEVER contains the overall % best evaluated point X with function value F evaluated at evaluation % count EVALS. The last output argument BESTEVER equals % OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and % parameters is written to files according to the Log-options. % % A regular manual stop can be achieved via the file signals.par. The % program is terminated if the first two non-white sequences in any % line of this file are 'stop' and the value of the LogFilenamePrefix % option (by default 'outcmaes'). Also a run can be skipped. % Given, for example, 'skip outcmaes run 2', skips the second run % if option Restarts is at least 2, and another run will be started. % % To run the code completely silently set Disp, Save, and Log options % to 0. With OPTS.LogModulo > 0 (1 by default) the most important % data are written to ASCII files permitting to investigate the % results (e.g. plot with function plotcmaesdat) even while CMAES is % still running (which can be quite useful on expensive objective % functions). When OPTS.SaveVariables==1 (default) everything is saved % in file OPTS.SaveFilename (default 'variablescmaes.mat') allowing to % resume the search afterwards by using the resume option. % % To find the best ever evaluated point load the variables typing % "es=load('variablescmaes')" and investigate the variable % es.out.solutions.bestever. % % In case of a noisy objective function (uncertainties) set % OPTS.Noise.on = 1. This option interferes presumably with some % termination criteria, because the step-size sigma will presumably % not converge to zero anymore. If CMAES was provided with a % fifth argument (P1 in the below example, which is passed to the % objective function FUN), this argument is multiplied with the % factor given in option Noise.alphaevals, each time the detected % noise exceeds a threshold. This argument can be used within % FUN, for example, as averaging number to reduce the noise level. % % OPTS.DiagonalOnly > 1 defines the number of initial iterations, % where the covariance matrix remains diagonal and the algorithm has % internally linear time complexity. OPTS.DiagonalOnly = 1 means % keeping the covariance matrix always diagonal and this setting % also exhibits linear space complexity. This can be particularly % useful for dimension > 100. The default is OPTS.DiagonalOnly = 0. % % OPTS.CMA.active = 1 turns on "active CMA" with a negative update % of the covariance matrix and checks for positive definiteness. % OPTS.CMA.active = 2 does not check for pos. def. and is numerically % faster. Active CMA usually speeds up the adaptation and might % become a default in near future. % % The primary strategy parameter to play with is OPTS.PopSize, which % can be increased from its default value. Increasing the population % size (by default linked to increasing parent number OPTS.ParentNumber) % improves global search properties in exchange to speed. Speed % decreases, as a rule, at most linearely with increasing population % size. It is advisable to begin with the default small population % size. The options Restarts and IncPopSize can be used for an % automated multistart where the population size is increased by the % factor IncPopSize (two by default) before each restart. X0 (given as % string) is reevaluated for each restart. Stopping options % StopFunEvals, StopIter, MaxFunEvals, and Fitness terminate the % program, all others including MaxIter invoke another restart, where % the iteration counter is reset to zero. % % Examples: % % XMIN = cmaes('myfun', 5*ones(10,1), 1.5); % % starts the search at 10D-point 5 and initially searches mainly % between 5-3 and 5+3 (+- two standard deviations), but this is not % a strict bound. 'myfun' is a name of a function that returns a % scalar from a 10D column vector. % % opts.LBounds = 0; opts.UBounds = 10; % opts.Restarts = 3; % doubles the popsize for each restart % X = cmaes('myfun', 10*rand(10,1), 5, opts); % % searches within lower bound of 0 and upper bound of 10. Bounds can % also be given as column vectors. If the optimum is not located % on the boundary, use rather a penalty approach to handle bounds. % % opts=cmaes; % opts.StopFitness=1e-10; % X=cmaes('myfun', rand(5,1), 0.5, opts); % % stops the search, if the function value is smaller than 1e-10. % % [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2); % % passes two additional parameters to the function MYFUN2. % % See also FMINSEARCH, FMINUNC, FMINBND. % TODO: % write dispcmaesdat for Matlab (and Octave) % control savemodulo and plotmodulo via signals.par cmaVersion = '3.62.beta'; % ----------- Set Defaults for Input Parameters and Options ------------- % These defaults may be edited for convenience % Input Defaults (obsolete, these are obligatory now) definput.fitfun = 'felli'; % frosen; fcigar; see end of file for more definput.xstart = rand(10,1); % 0.50*ones(10,1); definput.sigma = 0.3; % Options defaults: Stopping criteria % (value of stop flag) defopts.StopFitness = '-Inf % stop if f(xmin) < stopfitness, minimization'; defopts.MaxFunEvals = 'Inf % maximal number of fevals'; defopts.MaxIter = '1e3*(N+5)^2/sqrt(popsize) % maximal number of iterations'; defopts.StopFunEvals = 'Inf % stop after resp. evaluation, possibly resume later'; defopts.StopIter = 'Inf % stop after resp. iteration, possibly resume later'; defopts.TolX = '1e-11*max(insigma) % stop if x-change smaller TolX'; defopts.TolUpX = '1e3*max(insigma) % stop if x-changes larger TolUpX'; defopts.TolFun = '1e-12 % stop if fun-changes smaller TolFun'; defopts.TolHistFun = '1e-13 % stop if back fun-changes smaller TolHistFun'; defopts.StopOnStagnation = 'on % stop when fitness stagnates for a long time'; % TODO: stagnation has four parameters for the period: min = 120, const = 30N/lam, rel = 0.2, max = 2e5 % defopts.StopOnStagnation = '[120 30*N/popsize 0.2 2e5] % [min const rel_iter max] measuring period'; defopts.StopOnWarnings = 'yes % ''no''==''off''==0, ''on''==''yes''==1 '; defopts.StopOnEqualFunctionValues = '2 + N/3 % number of iterations'; % Options defaults: Other defopts.DiffMaxChange = 'Inf % maximal variable change(s), can be Nx1-vector'; defopts.DiffMinChange = '0 % minimal variable change(s), can be Nx1-vector'; defopts.WarnOnEqualFunctionValues = ... 'yes % ''no''==''off''==0, ''on''==''yes''==1 '; defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector'; defopts.UBounds = 'Inf % upper bounds, scalar or Nx1-vector'; defopts.EvalParallel = 'no % objective function FUN accepts NxM matrix, with M>1?'; defopts.EvalInitialX = 'yes % evaluation of initial solution'; defopts.Restarts = '0 % number of restarts '; defopts.IncPopSize = '2 % multiplier for population size before each restart'; defopts.PopSize = '(4 + floor(3*log(N))) % population size, lambda'; defopts.ParentNumber = 'floor(popsize/2) % AKA mu, popsize equals lambda'; defopts.RecombinationWeights = 'superlinear decrease % or linear, or equal'; defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000) % C is diagonal for given iterations, 1==always'; defopts.Noise.on = '0 % uncertainty handling is off by default'; defopts.Noise.reevals = '1*ceil(0.05*lambda) % nb. of re-evaluated for uncertainty measurement'; defopts.Noise.theta = '0.5 % threshold to invoke uncertainty treatment'; % smaller: more likely to diverge defopts.Noise.cum = '0.3 % cumulation constant for uncertainty'; defopts.Noise.cutoff = '2*lambda/3 % rank change cutoff for summation'; defopts.Noise.alphasigma = '1+2/(N+10) % factor for increasing sigma'; % smaller: slower adaptation defopts.Noise.epsilon = '1e-7 % additional relative perturbation before reevaluation'; defopts.Noise.minmaxevals = '[1 inf] % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes'; defopts.Noise.alphaevals = '1+2/(N+10) % factor for increasing 2nd arg to fitfun'; defopts.Noise.callback = '[] % callback function when uncertainty threshold is exceeded'; % defopts.TPA = 0; defopts.CMA.cs = '(mueff+2)/(N+mueff+3) % cumulation constant for step-size'; %qqq defopts.CMA.cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version defopts.CMA.damps = '1 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; % defopts.CMA.ccum = '4/(N+4) % cumulation constant for covariance matrix'; defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc'; defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff) % learning rate for rank-one update'; defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update'; defopts.CMA.on = 'yes'; defopts.CMA.active = '0 % active CMA, 1: neg. updates with pos. def. check, 2: neg. updates'; flg_future_setting = 0; % testing for possible future variant(s) if flg_future_setting disp('in the future') % damps setting from Brockhoff et al 2010 % this damps diverges with popsize 400: % defopts.CMA.damps = '2*mueff/lambda + 0.3 + cs % damping for step-size'; % cmaeshtml('benchmarkszero', ones(20,1)*2, 5, o, 15); % how about: % defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; defopts.CMA.damps = '0.5 + 0.5*min(1, (0.27*lambda/mueff-1)^2) + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; if 11 < 3 defopts.CMA.damps = '0.5 + 0.5*min(1,(lam_mirr/(0.159*lambda)-1)^2) + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size'; defopts.mirrored_offspring = 'floor(0.5 + 0.159 * lambda)'; % TODO: this should also depend on diagonal option!? defopts.CMA.active = 'floor(int8(lam_mirr>0)) % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; end % ccum adjusted for large mueff, better on schefelmult? % TODO: this should also depend on diagonal option!? defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc'; defopts.CMA.active = '1 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates'; end defopts.Resume = 'no % resume former run from SaveFile'; defopts.Science = 'on % off==do some additional (minor) problem capturing, NOT IN USE'; defopts.ReadSignals = 'on % from file signals.par for termination, yet a stumb'; defopts.Seed = 'sum(100*clock) % evaluated if it is a string'; defopts.DispFinal = 'on % display messages like initial and final message'; defopts.DispModulo = '100 % [0:Inf], disp messages after every i-th iteration'; defopts.SaveVariables = 'on % [on|final|off][-v6] save variables to .mat file'; defopts.SaveFilename = 'variablescmaes.mat % save all variables, see SaveVariables'; defopts.LogModulo = '1 % [0:Inf] if >1 record data less frequently after gen=100'; defopts.LogTime = '25 % [0:100] max. percentage of time for recording data'; defopts.LogFilenamePrefix = 'outcmaes % files for output data'; defopts.LogPlot = 'off % plot while running using output data files'; %qqqkkk %defopts.varopt1 = ''; % 'for temporary and hacking purposes'; %defopts.varopt2 = ''; % 'for temporary and hacking purposes'; defopts.UserData = 'for saving data/comments associated with the run'; defopts.UserDat2 = ''; 'for saving data/comments associated with the run'; % ---------------------- Handling Input Parameters ---------------------- if nargin < 1 || isequal(fitfun, 'defaults') % pass default options if nargin < 1 disp('Default options returned (type "help cmaes" for help).'); end xmin = defopts; if nargin > 1 % supplement second argument with default options xmin = getoptions(xstart, defopts); end return; end if isequal(fitfun, 'displayoptions') names = fieldnames(defopts); for name = names' disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']); end return; end input.fitfun = fitfun; % record used input if isempty(fitfun) % fitfun = definput.fitfun; % warning(['Objective function not determined, ''' fitfun ''' used']); error(['Objective function not determined']); end if ~ischar(fitfun) error('first argument FUN must be a string'); end if nargin < 2 xstart = []; end input.xstart = xstart; if isempty(xstart) % xstart = definput.xstart; % objective variables initial point % warning('Initial search point, and problem dimension, not determined'); error('Initial search point, and problem dimension, not determined'); end if nargin < 3 insigma = []; end if isa(insigma, 'struct') error(['Third argument SIGMA must be (or eval to) a scalar '... 'or a column vector of size(X0,1)']); end input.sigma = insigma; if isempty(insigma) if all(size(myeval(xstart)) > 1) insigma = std(xstart, 0, 2); if any(insigma == 0) error(['Initial search volume is zero, choose SIGMA or X0 appropriate']); end else % will be captured later % error(['Initial step sizes (SIGMA) not determined']); end end % Compose options opts if nargin < 4 || isempty(inopts) % no input options available inopts = []; opts = defopts; else opts = getoptions(inopts, defopts); end i = strfind(opts.SaveFilename, '%'); % remove everything after comment if ~isempty(i) opts.SaveFilename = opts.SaveFilename(1:i(1)-1); end opts.SaveFilename = deblank(opts.SaveFilename); % remove trailing white spaces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% counteval = 0; countevalNaN = 0; irun = 0; while irun <= myeval(opts.Restarts) % for-loop does not work with resume irun = irun + 1; % ------------------------ Initialization ------------------------------- % Handle resuming of old run flgresume = myevalbool(opts.Resume); xmean = myeval(xstart); if all(size(xmean) > 1) xmean = mean(xmean, 2); % in case if xstart is a population elseif size(xmean, 2) > 1 xmean = xmean'; end if ~flgresume % not resuming a former run % Assign settings from input parameters and options for myeval... N = size(xmean, 1); numberofvariables = N; lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1)); % lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2)); popsize = lambda0; lambda = lambda0; insigma = myeval(insigma); if all(size(insigma) == [N 2]) insigma = 0.5 * (insigma(:,2) - insigma(:,1)); end else % flgresume is true, do resume former run tmp = whos('-file', opts.SaveFilename); for i = 1:length(tmp) if strcmp(tmp(i).name, 'localopts'); error('Saved variables include variable "localopts", please remove'); end end local.opts = opts; % keep stopping and display options local.varargin = varargin; load(opts.SaveFilename); varargin = local.varargin; flgresume = 1; % Overwrite old stopping and display options opts.StopFitness = local.opts.StopFitness; %%opts.MaxFunEvals = local.opts.MaxFunEvals; %%opts.MaxIter = local.opts.MaxIter; opts.StopFunEvals = local.opts.StopFunEvals; opts.StopIter = local.opts.StopIter; opts.TolX = local.opts.TolX; opts.TolUpX = local.opts.TolUpX; opts.TolFun = local.opts.TolFun; opts.TolHistFun = local.opts.TolHistFun; opts.StopOnStagnation = local.opts.StopOnStagnation; opts.StopOnWarnings = local.opts.StopOnWarnings; opts.ReadSignals = local.opts.ReadSignals; opts.DispFinal = local.opts.DispFinal; opts.LogPlot = local.opts.LogPlot; opts.DispModulo = local.opts.DispModulo; opts.SaveVariables = local.opts.SaveVariables; opts.LogModulo = local.opts.LogModulo; opts.LogTime = local.opts.LogTime; clear local; % otherwise local would be overwritten during load end %-------------------------------------------------------------- % Evaluate options stopFitness = myeval(opts.StopFitness); stopMaxFunEvals = myeval(opts.MaxFunEvals); stopMaxIter = myeval(opts.MaxIter); stopFunEvals = myeval(opts.StopFunEvals); stopIter = myeval(opts.StopIter); if flgresume stopIter = stopIter + countiter end stopTolX = myeval(opts.TolX); stopTolUpX = myeval(opts.TolUpX); stopTolFun = myeval(opts.TolFun); stopTolHistFun = myeval(opts.TolHistFun); stopOnStagnation = myevalbool(opts.StopOnStagnation); stopOnWarnings = myevalbool(opts.StopOnWarnings); flgreadsignals = myevalbool(opts.ReadSignals); flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues); flgEvalParallel = myevalbool(opts.EvalParallel); stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues); arrEqualFunvals = zeros(1, 10+N); flgDiagonalOnly = myeval(opts.DiagonalOnly); flgActiveCMA = myeval(opts.CMA.active); noiseHandling = myevalbool(opts.Noise.on); noiseMinMaxEvals = myeval(opts.Noise.minmaxevals); noiseAlphaEvals = myeval(opts.Noise.alphaevals); noiseCallback = myeval(opts.Noise.callback); flgdisplay = myevalbool(opts.DispFinal); flgplotting = myevalbool(opts.LogPlot); verbosemodulo = myeval(opts.DispModulo); flgscience = myevalbool(opts.Science); flgsaving = []; strsaving = []; if strfind(opts.SaveVariables, '-v6') i = strfind(opts.SaveVariables, '%'); if isempty(i) || i == 0 || strfind(opts.SaveVariables, '-v6') < i strsaving = '-v6'; flgsaving = 1; flgsavingfinal = 1; end end if strncmp('final', opts.SaveVariables, 5) flgsaving = 0; flgsavingfinal = 1; end if isempty(flgsaving) flgsaving = myevalbool(opts.SaveVariables); flgsavingfinal = flgsaving; end savemodulo = myeval(opts.LogModulo); savetime = myeval(opts.LogTime); i = strfind(opts.LogFilenamePrefix, ' '); % remove everything after white space if ~isempty(i) opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:i(1)-1); end % TODO here silent option? set disp, save and log options to 0 %-------------------------------------------------------------- if (isfinite(stopFunEvals) || isfinite(stopIter)) && ~flgsaving warning('To resume later the saving option needs to be set'); end % Do more checking and initialization if flgresume % resume is on time.t0 = clock; if flgdisplay disp([' resumed from ' opts.SaveFilename ]); end if counteval >= stopMaxFunEvals error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ... 'criterion before resume']); end if countiter >= stopMaxIter error(['MaxIter exceeded, use StopIter as stopping criterion ' ... 'before resume']); end else % flgresume % xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change mindx = myeval(opts.DiffMinChange); % minimal sensible variable change % can both also be defined as Nx1 vectors lbounds = myeval(opts.LBounds); ubounds = myeval(opts.UBounds); if length(lbounds) == 1 lbounds = repmat(lbounds, N, 1); end if length(ubounds) == 1 ubounds = repmat(ubounds, N, 1); end if isempty(insigma) % last chance to set insigma if all(lbounds > -Inf) && all(ubounds < Inf) if any(lbounds>=ubounds) error('upper bound must be greater than lower bound'); end insigma = 0.3*(ubounds-lbounds); stopTolX = myeval(opts.TolX); % reevaluate these stopTolUpX = myeval(opts.TolUpX); else error(['Initial step sizes (SIGMA) not determined']); end end % Check all vector sizes if size(xmean, 2) > 1 || size(xmean,1) ~= N error(['intial search point should be a column vector of size ' ... num2str(N)]); elseif ~(all(size(insigma) == [1 1]) || all(size(insigma) == [N 1])) error(['input parameter SIGMA should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); elseif size(stopTolX, 2) > 1 || ~ismember(size(stopTolX, 1), [1 N]) error(['option TolX should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); elseif size(stopTolUpX, 2) > 1 || ~ismember(size(stopTolUpX, 1), [1 N]) error(['option TolUpX should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); elseif size(maxdx, 2) > 1 || ~ismember(size(maxdx, 1), [1 N]) error(['option DiffMaxChange should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); elseif size(mindx, 2) > 1 || ~ismember(size(mindx, 1), [1 N]) error(['option DiffMinChange should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); elseif size(lbounds, 2) > 1 || ~ismember(size(lbounds, 1), [1 N]) error(['option lbounds should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); elseif size(ubounds, 2) > 1 || ~ismember(size(ubounds, 1), [1 N]) error(['option ubounds should be (or eval to) a scalar '... 'or a column vector of size ' num2str(N)] ); end % Initialize dynamic internal state parameters if any(insigma <= 0) error(['Initial search volume (SIGMA) must be greater than zero']); end if max(insigma)/min(insigma) > 1e6 error(['Initial search volume (SIGMA) badly conditioned']); end sigma = max(insigma); % overall standard deviation pc = zeros(N,1); ps = zeros(N,1); % evolution paths for C and sigma if length(insigma) == 1 insigma = insigma * ones(N,1) ; end diagD = insigma/max(insigma); % diagonal matrix D defines the scaling diagC = diagD.^2; if flgDiagonalOnly ~= 1 % use at some point full covariance matrix B = eye(N,N); % B defines the coordinate system BD = B.*repmat(diagD',N,1); % B*D for speed up only C = diag(diagC); % covariance matrix == BD*(BD)' end if flgDiagonalOnly B = 1; end fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values fitness.histsel=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values fitness.histbest=[]; % history of fitness values fitness.histmedian=[]; % history of fitness values % Initialize boundary handling bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf); if bnd.isactive if any(lbounds>ubounds) error('lower bound found to be greater than upper bound'); end [xmean ti] = xintobounds(xmean, lbounds, ubounds); % just in case if any(ti) warning('Initial point was out of bounds, corrected'); end bnd.weights = zeros(N,1); % weights for bound penalty % scaling is better in axis-parallel case, worse in rotated bnd.flgscale = 0; % scaling will be omitted if zero if bnd.flgscale ~= 0 bnd.scale = diagC/mean(diagC); else bnd.scale = ones(N,1); end idx = (lbounds > -Inf) | (ubounds < Inf); if length(idx) == 1 idx = idx * ones(N,1); end bnd.isbounded = zeros(N,1); bnd.isbounded(find(idx)) = 1; maxdx = min(maxdx, (ubounds - lbounds)/2); if any(sigma*sqrt(diagC) > maxdx) fac = min(maxdx ./ sqrt(diagC))/sigma; sigma = min(maxdx ./ sqrt(diagC)); warning(['Initial SIGMA multiplied by the factor ' num2str(fac) ... ', because it was larger than half' ... ' of one of the boundary intervals']); end idx = (lbounds > -Inf) & (ubounds < Inf); dd = diagC; if any(5*sigma*sqrt(dd(idx)) < ubounds(idx) - lbounds(idx)) warning(['Initial SIGMA is, in at least one coordinate, ' ... 'much smaller than the '... 'given boundary intervals. For reasonable ' ... 'global search performance SIGMA should be ' ... 'between 0.2 and 0.5 of the bounded interval in ' ... 'each coordinate. If all coordinates have ' ... 'lower and upper bounds SIGMA can be empty']); end bnd.dfithist = 1; % delta fit for setting weights bnd.aridxpoints = []; % remember complete outside points bnd.arfitness = []; % and their fitness bnd.validfitval = 0; bnd.iniphase = 1; end % ooo initial feval, for output only if irun == 1 out.solutions.bestever.x = xmean; out.solutions.bestever.f = Inf; % for simpler comparison below out.solutions.bestever.evals = counteval; bestever = out.solutions.bestever; end if myevalbool(opts.EvalInitialX) fitness.hist(1)=feval(fitfun, xmean, varargin{:}); fitness.histsel(1)=fitness.hist(1); counteval = counteval + 1; if fitness.hist(1) < out.solutions.bestever.f out.solutions.bestever.x = xmean; out.solutions.bestever.f = fitness.hist(1); out.solutions.bestever.evals = counteval; bestever = out.solutions.bestever; end else fitness.hist(1)=NaN; fitness.histsel(1)=NaN; end % initialize random number generator if ischar(opts.Seed) randn('state', eval(opts.Seed)); % random number generator state else randn('state', opts.Seed); end %qqq % load(opts.SaveFilename, 'startseed'); % randn('state', startseed); % disp(['SEED RELOADED FROM ' opts.SaveFilename]); startseed = randn('state'); % for retrieving in saved variables % Initialize further constants chiN=N^0.5*(1-1/(4*N)+1/(21*N^2)); % expectation of % ||N(0,I)|| == norm(randn(N,1)) countiter = 0; % Initialize records and output if irun == 1 time.t0 = clock; % TODO: keep also median solution? out.evals = counteval; % should be first entry out.stopflag = {}; outiter = 0; % Write headers to output data files filenameprefix = opts.LogFilenamePrefix; if savemodulo && savetime filenames = {}; filenames(end+1) = {'axlen'}; filenames(end+1) = {'fit'}; filenames(end+1) = {'stddev'}; filenames(end+1) = {'xmean'}; filenames(end+1) = {'xrecentbest'}; str = [' (startseed=' num2str(startseed(2)) ... ', ' num2str(clock, '%d/%02d/%d %d:%d:%2.2f') ')']; for namecell = filenames(:)' name = namecell{:}; [fid, err] = fopen(['./' filenameprefix name '.dat'], 'w'); if fid < 1 % err ~= 0 warning(['could not open ' filenameprefix name '.dat']); filenames(find(strcmp(filenames,name))) = []; else % fprintf(fid, '%s\n', ... % ['<CMAES-OUTPUT version="' cmaVersion '">']); % fprintf(fid, [' <NAME>' name '</NAME>\n']); % fprintf(fid, [' <DATE>' date() '</DATE>\n']); % fprintf(fid, ' <PARAMETERS>\n'); % fprintf(fid, [' dimension=' num2str(N) '\n']); % fprintf(fid, ' </PARAMETERS>\n'); % different cases for DATA columns annotations here % fprintf(fid, ' <DATA'); if strcmp(name, 'axlen') fprintf(fid, ['%% columns="iteration, evaluation, sigma, ' ... 'max axis length, min axis length, ' ... 'all principal axes lengths (sorted square roots ' ... 'of eigenvalues of C)"' str]); elseif strcmp(name, 'fit') fprintf(fid, ['%% columns="iteration, evaluation, sigma, axis ratio, bestever,' ... ' best, median, worst fitness function value,' ... ' further objective values of best"' str]); elseif strcmp(name, 'stddev') fprintf(fid, ['%% columns=["iteration, evaluation, sigma, void, void, ' ... 'stds==sigma*sqrt(diag(C))"' str]); elseif strcmp(name, 'xmean') fprintf(fid, ['%% columns="iteration, evaluation, void, ' ... 'void, void, xmean"' str]); elseif strcmp(name, 'xrecentbest') fprintf(fid, ['%% columns="iteration, evaluation, fitness, ' ... 'void, void, xrecentbest"' str]); end fprintf(fid, '\n'); % DATA if strcmp(name, 'xmean') fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval); % fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); %qqq fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n'); fprintf(fid, '%e ', xmean); fprintf(fid, '\n'); end fclose(fid); clear fid; % preventing end end % for files end % savemodulo end % irun == 1 end % else flgresume % -------------------- Generation Loop -------------------------------- stopflag = {}; while isempty(stopflag) % set internal parameters if countiter == 0 || lambda ~= lambda_last if countiter > 0 && floor(log10(lambda)) ~= floor(log10(lambda_last)) ... && flgdisplay disp([' lambda = ' num2str(lambda)]); lambda_hist(:,end+1) = [countiter+1; lambda]; else lambda_hist = [countiter+1; lambda]; end lambda_last = lambda; % Strategy internal parameter setting: Selection mu = myeval(opts.ParentNumber); % number of parents/points for recombination if strncmp(lower(opts.RecombinationWeights), 'equal', 3) weights = ones(mu,1); % (mu_I,lambda)-CMA-ES elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3) weights = mu+0.5-(1:mu)'; elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3) % use (lambda+1)/2 as reference if mu < lambda/2 weights = log(max(mu, lambda/2) + 1/2)-log(1:mu)'; % muXone array for weighted recombination else error(['Recombination weights to be "' opts.RecombinationWeights ... '" is not implemented']); end mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu weights = weights/sum(weights); % normalize recombination weights array if mueff == lambda error(['Combination of values for PopSize, ParentNumber and ' ... ' and RecombinationWeights is not reasonable']); end % Strategy internal parameter setting: Adaptation cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix cs = myeval(opts.CMA.cs); % old way TODO: remove this at some point % mucov = mueff; % size of mu used for calculating learning rate ccov % ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix % + (1-1/mucov) * min(1,(2*mucov-1)/((N+2)^2+mucov)); % new way if myevalbool(opts.CMA.on) ccov1 = myeval(opts.CMA.ccov1); ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu)); else ccov1 = 0; ccovmu = 0; end % flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed % 0 : C will never be diagonal anymore % 1 : C will always be diagonal % >1: C is diagonal for first iterations, set to 0 afterwards if flgDiagonalOnly < 1 flgDiagonalOnly = 0; end if flgDiagonalOnly ccov1_sep = min(1, ccov1 * (N+1.5) / 3); ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3); elseif N > 98 && flgdisplay && countiter == 0 disp('consider option DiagonalOnly for high-dimensional problems'); end % ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness %damps = ... % damping for step size control, usually close to one % (1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase % * max(0.3, ... % reduce damps, if max. iteration number is small % 1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs; damps = myeval(opts.CMA.damps); if noiseHandling noiseReevals = min(myeval(opts.Noise.reevals), lambda); noiseAlpha = myeval(opts.Noise.alphasigma); noiseEpsilon = myeval(opts.Noise.epsilon); noiseTheta = myeval(opts.Noise.theta); noisecum = myeval(opts.Noise.cum); noiseCutOff = myeval(opts.Noise.cutoff); % arguably of minor relevance else noiseReevals = 0; % more convenient in later coding end %qqq hacking of a different parameter setting, e.g. for ccov or damps, % can be done here, but is not necessary anymore, see opts.CMA. % ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]); % ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]); % damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]); % cc = 1; disp(['CAVE: cc=' num2str(cc)]); end % Display initial message if countiter == 0 && flgdisplay if mu == 1 strw = '100'; elseif mu < 8 strw = [sprintf('%.0f', 100*weights(1)) ... sprintf(' %.0f', 100*weights(2:end)')]; else strw = [sprintf('%.2g ', 100*weights(1:2)') ... sprintf('%.2g', 100*weights(3)') '...' ... sprintf(' %.2g', 100*weights(end-1:end)') ']%, ']; end if irun > 1 strrun = [', run ' num2str(irun)]; else strrun = ''; end disp([' n=' num2str(N) ': (' num2str(mu) ',' ... num2str(lambda) ')-CMA-ES(w=[' ... strw ']%, ' ... 'mu_eff=' num2str(mueff,'%.1f') ... ') on function ' ... (fitfun) strrun]); if flgDiagonalOnly == 1 disp(' C is diagonal'); elseif flgDiagonalOnly disp([' C is diagonal for ' num2str(floor(flgDiagonalOnly)) ' iterations']); end end flush; countiter = countiter + 1; % Generate and evaluate lambda offspring fitness.raw = repmat(NaN, 1, lambda + noiseReevals); % parallel evaluation if flgEvalParallel arz = randn(N,lambda); if ~flgDiagonalOnly arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1) else arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz; end if noiseHandling if noiseEpsilon == 0 arx = [arx arx(:,1:noiseReevals)]; elseif flgDiagonalOnly arx = [arx arx(:,1:noiseReevals) + ... repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ... .* randn(N,noiseReevals)]; else arx = [arx arx(:,1:noiseReevals) + ... noiseEpsilon * sigma * ... (BD * randn(N,noiseReevals))]; end end % You may handle constraints here. You may either resample % arz(:,k) and/or multiply it with a factor between -1 and 1 % (the latter will decrease the overall step size) and % recalculate arx accordingly. Do not change arx or arz in any % other way. if ~bnd.isactive arxvalid = arx; else arxvalid = xintobounds(arx, lbounds, ubounds); end % You may handle constraints here. You may copy and alter % (columns of) arxvalid(:,k) only for the evaluation of the % fitness function. arx and arxvalid should not be changed. fitness.raw = feval(fitfun, arxvalid, varargin{:}); countevalNaN = countevalNaN + sum(isnan(fitness.raw)); counteval = counteval + sum(~isnan(fitness.raw)); end % non-parallel evaluation and remaining NaN-values % set also the reevaluated solution to NaN fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN; for k=find(isnan(fitness.raw)), % fitness.raw(k) = NaN; tries = flgEvalParallel; % in parallel case this is the first re-trial % Resample, until fitness is not NaN while isnan(fitness.raw(k)) if k <= lambda % regular samples (not the re-evaluation-samples) arz(:,k) = randn(N,1); % (re)sample if flgDiagonalOnly arx(:,k) = xmean + sigma * diagD .* arz(:,k); % Eq. (1) else arx(:,k) = xmean + sigma * (BD * arz(:,k)); % Eq. (1) end else % re-evaluation solution with index > lambda if flgDiagonalOnly arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1); else arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1)); end end % You may handle constraints here. You may either resample % arz(:,k) and/or multiply it with a factor between -1 and 1 % (the latter will decrease the overall step size) and % recalculate arx accordingly. Do not change arx or arz in any % other way. if ~bnd.isactive arxvalid(:,k) = arx(:,k); else arxvalid(:,k) = xintobounds(arx(:,k), lbounds, ubounds); end % You may handle constraints here. You may copy and alter % (columns of) arxvalid(:,k) only for the evaluation of the % fitness function. arx should not be changed. fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:}); tries = tries + 1; if isnan(fitness.raw(k)) countevalNaN = countevalNaN + 1; end if mod(tries, 100) == 0 warning([num2str(tries) ... ' NaN objective function values at evaluation ' ... num2str(counteval)]); end end counteval = counteval + 1; % retries due to NaN are not counted end fitness.sel = fitness.raw; % ----- handle boundaries ----- if 1 < 3 && bnd.isactive % Get delta fitness values val = myprctile(fitness.raw, [25 75]); % more precise would be exp(mean(log(diagC))) val = (val(2) - val(1)) / N / mean(diagC) / sigma^2; %val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ... % / N / mean(diagC) / sigma^2; % Catch non-sensible values if ~isfinite(val) warning('Non-finite fitness range'); val = max(bnd.dfithist); elseif val == 0 % happens if all points are out of bounds val = min(bnd.dfithist(bnd.dfithist>0)); % seems not to make sense, given all solutions are out of bounds elseif bnd.validfitval == 0 % flag that first sensible val was found bnd.dfithist = []; bnd.validfitval = 1; end % Store delta fitness values if length(bnd.dfithist) < 20+(3*N)/lambda bnd.dfithist = [bnd.dfithist val]; else bnd.dfithist = [bnd.dfithist(2:end) val]; end [tx ti] = xintobounds(xmean, lbounds, ubounds); % Set initial weights if bnd.iniphase if any(ti) bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist); if bnd.flgscale == 0 % scale only initial weights then dd = diagC; idx = find(bnd.isbounded); dd = dd(idx) / mean(dd); % remove mean scaling bnd.weights(idx) = bnd.weights(idx) ./ dd; end if bnd.validfitval && countiter > 2 bnd.iniphase = 0; end end end % Increase weights if 1 < 3 && any(ti) % any coordinate of xmean out of bounds % judge distance of xmean to boundary tx = xmean - tx; idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ... * sigma*sqrt(diagC)) ; % only increase if xmean is moving away idx = idx & (sign(tx) == sign(xmean - xold)); if ~isempty(idx) % increase % the factor became 1.2 instead of 1.1, because % changed from max to min in version 3.52 bnd.weights(idx) = 1.2^(min(1, mueff/10/N)) * bnd.weights(idx); end end % Calculate scaling biased to unity, product is one if bnd.flgscale ~= 0 bnd.scale = exp(0.9*(log(diagC)-mean(log(diagC)))); end % Assigned penalized fitness bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2; fitness.sel = fitness.raw + bnd.arpenalty; end % handle boundaries % ----- end handle boundaries ----- % compute noise measurement and reduce fitness arrays to size lambda if noiseHandling [noiseS] = local_noisemeasurement(fitness.sel(1:lambda), ... fitness.sel(lambda+(1:noiseReevals)), ... noiseReevals, noiseTheta, noiseCutOff); if countiter == 1 % TODO: improve this very rude way of initialization noiseSS = 0; noiseN = 0; % counter for mean end noiseSS = noiseSS + noisecum * (noiseS - noiseSS); % noise-handling could be done here, but the original sigma is still needed % disp([noiseS noiseSS noisecum]) fitness.rawar12 = fitness.raw; % just documentary fitness.selar12 = fitness.sel; % just documentary % qqq refine fitness based on both values if 11 < 3 % TODO: in case of outliers this mean is counterproductive % median out of three would be ok fitness.raw(1:noiseReevals) = ... % not so raw anymore (fitness.raw(1:noiseReevals) + fitness.raw(lambda+(1:noiseReevals))) / 2; fitness.sel(1:noiseReevals) = ... (fitness.sel(1:noiseReevals) + fitness.sel(lambda+(1:noiseReevals))) / 2; end fitness.raw = fitness.raw(1:lambda); fitness.sel = fitness.sel(1:lambda); end % Sort by fitness [fitness.raw, fitness.idx] = sort(fitness.raw); [fitness.sel, fitness.idxsel] = sort(fitness.sel); % minimization fitness.hist(2:end) = fitness.hist(1:end-1); % record short history of fitness.hist(1) = fitness.raw(1); % best fitness values if length(fitness.histbest) < 120+ceil(30*N/lambda) || ... (mod(countiter, 5) == 0 && length(fitness.histbest) < 2e4) % 20 percent of 1e5 gen. fitness.histbest = [fitness.raw(1) fitness.histbest]; % best fitness values fitness.histmedian = [median(fitness.raw) fitness.histmedian]; % median fitness values else fitness.histbest(2:end) = fitness.histbest(1:end-1); fitness.histmedian(2:end) = fitness.histmedian(1:end-1); fitness.histbest(1) = fitness.raw(1); % best fitness values fitness.histmedian(1) = median(fitness.raw); % median fitness values end fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of fitness.histsel(1) = fitness.sel(1); % best sel fitness values % Calculate new xmean, this is selection and recombination xold = xmean; % for speed up of Eq. (2) and (3) cmean = 1; % 1/min(max((lambda-1*N)/2, 1), N); % == 1/kappa xmean = (1-cmean) * xold + cmean * arx(:,fitness.idxsel(1:mu))*weights; zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma if mu == 1 fmean = fitness.sel(1); else fmean = NaN; % [] does not work in the latter assignment % fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:}); % counteval = counteval + 1; end % Cumulation: update evolution paths ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B*zmean); % Eq. (4) hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1); if flg_future_setting hsig = sum(ps.^2) / (1-(1-cs)^(2*countiter)) / N < 2 + 4/(N+1); % just simplified end % hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1); % hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.5 + 1/(N-0.5); % hsig = norm(ps) < 1.5 * sqrt(N); % hsig = 1; pc = (1-cc)*pc ... + hsig*(sqrt(cc*(2-cc)*mueff)/sigma/cmean) * (xmean-xold); % Eq. (2) if hsig == 0 % disp([num2str(countiter) ' ' num2str(counteval) ' pc update stalled']); end % Adapt covariance matrix neg.ccov = 0; % TODO: move parameter setting upwards at some point if ccov1 + ccovmu > 0 % Eq. (3) if flgDiagonalOnly % internal linear(?) complexity diagC = (1-ccov1_sep-ccovmu_sep+(1-hsig)*ccov1_sep*cc*(2-cc)) * diagC ... % regard old matrix + ccov1_sep * pc.^2 ... % plus rank one update + ccovmu_sep ... % plus rank mu update * (diagC .* (arz(:,fitness.idxsel(1:mu)).^2 * weights)); % * (repmat(diagC,1,mu) .* arz(:,fitness.idxsel(1:mu)).^2 * weights); diagD = sqrt(diagC); % replaces eig(C) else arpos = (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) / sigma; % "active" CMA update: negative update, in case controlling pos. definiteness if flgActiveCMA > 0 % set parameters neg.mu = mu; neg.mueff = mueff; if flgActiveCMA > 10 % flat weights with mu=lambda/2 neg.mu = floor(lambda/2); neg.mueff = neg.mu; end % neg.mu = ceil(min([N, lambda/4, mueff])); neg.mueff = mu; % i.e. neg.mu <= N % Parameter study: in 3-D lambda=50,100, 10-D lambda=200,400, 30-D lambda=1000,2000 a % three times larger neg.ccov does not work. % increasing all ccov rates three times does work (probably because of the factor (1-ccovmu)) % in 30-D to looks fine neg.ccov = (1 - ccovmu) * 0.25 * neg.mueff / ((N+2)^1.5 + 2*neg.mueff); neg.minresidualvariance = 0.66; % keep at least 0.66 in all directions, small popsize are most critical neg.alphaold = 0.5; % where to make up for the variance loss, 0.5 means no idea what to do % 1 is slightly more robust and gives a better "guaranty" for pos. def., % but does it make sense from the learning perspective for large ccovmu? neg.ccovfinal = neg.ccov; % prepare vectors, compute negative updating matrix Cneg and checking matrix Ccheck arzneg = arz(:,fitness.idxsel(lambda:-1:lambda - neg.mu + 1)); % i-th longest becomes i-th shortest % TODO: this is not in compliance with the paper Hansen&Ros2010, % where simply arnorms = arnorms(end:-1:1) ? [arnorms idxnorms] = sort(sqrt(sum(arzneg.^2, 1))); [ignore idxnorms] = sort(idxnorms); % inverse index arnormfacs = arnorms(end:-1:1) ./ arnorms; % arnormfacs = arnorms(randperm(neg.mu)) ./ arnorms; arnorms = arnorms(end:-1:1); % for the record if flgActiveCMA < 20 arzneg = arzneg .* repmat(arnormfacs(idxnorms), N, 1); % E x*x' is N % arzneg = sqrt(N) * arzneg ./ repmat(sqrt(sum(arzneg.^2, 1)), N, 1); % E x*x' is N end if flgActiveCMA < 10 && neg.mu == mu % weighted sum if mod(flgActiveCMA, 10) == 1 % TODO: prevent this with a less tight but more efficient check (see below) Ccheck = arzneg * diag(weights) * arzneg'; % in order to check the largest EV end artmp = BD * arzneg; Cneg = artmp * diag(weights) * artmp'; else % simple sum if mod(flgActiveCMA, 10) == 1 Ccheck = (1/neg.mu) * arzneg*arzneg'; % in order to check largest EV end artmp = BD * arzneg; Cneg = (1/neg.mu) * artmp*artmp'; end % check pos.def. and set learning rate neg.ccov accordingly, % this check makes the original choice of neg.ccov extremly failsafe % still assuming C == BD*BD', which is only approxim. correct if mod(flgActiveCMA, 10) == 1 && 1 - neg.ccov * arnorms(idxnorms).^2 * weights < neg.minresidualvariance % TODO: the simple and cheap way would be to set % fac = 1 - ccovmu - ccov1 OR 1 - mueff/lambda and % neg.ccov = fac*(1 - neg.minresidualvariance) / (arnorms(idxnorms).^2 * weights) % this is the more sophisticated way: % maxeigenval = eigs(arzneg * arzneg', 1, 'lm', eigsopts); % not faster maxeigenval = max(eig(Ccheck)); % norm is much slower, because (norm()==max(svd()) %disp([countiter log10([neg.ccov, maxeigenval, arnorms(idxnorms).^2 * weights, max(arnorms)^2]), ... % neg.ccov * arnorms(idxnorms).^2 * weights]) % pause % remove less than ??34*(1-cmu)%?? of variance in any direction % 1-ccovmu is the variance left from the old C neg.ccovfinal = min(neg.ccov, (1-ccovmu)*(1-neg.minresidualvariance)/maxeigenval); % -ccov1 removed to avoid error message?? if neg.ccovfinal < neg.ccov disp(['active CMA at iteration ' num2str(countiter) ... ': max EV ==', num2str([maxeigenval, neg.ccov, neg.ccovfinal])]); end end % xmean = xold; % the distribution does not degenerate!? % update C C = (1-ccov1-ccovmu+neg.alphaold*neg.ccovfinal+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix + ccov1 * pc*pc' ... % plus rank one update + (ccovmu + (1-neg.alphaold)*neg.ccovfinal) ... % plus rank mu update * arpos * (repmat(weights,1,N) .* arpos') ... - neg.ccovfinal * Cneg; % minus rank mu update else % no active (negative) update C = (1-ccov1-ccovmu+(1-hsig)*ccov1*cc*(2-cc)) * C ... % regard old matrix + ccov1 * pc*pc' ... % plus rank one update + ccovmu ... % plus rank mu update * arpos * (repmat(weights,1,N) .* arpos'); % is now O(mu*N^2 + mu*N), was O(mu*N^2 + mu^2*N) when using diag(weights) % for mu=30*N it is now 10 times faster, overall 3 times faster end diagC = diag(C); end end % the following is de-preciated and will be removed in future % better setting for cc makes this hack obsolete if 11 < 2 && ~flgscience % remove momentum in ps, if ps is large and fitness is getting worse. % this should rarely happen. % this might very well be counterproductive in dynamic environments if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ... fitness.histsel(1) > max(fitness.histsel(2:3)) ps = ps * sqrt(N*(1+max(0,log(sum(ps.^2)/N))) / sum(ps.^2)); if flgdisplay disp(['Momentum in ps removed at [niter neval]=' ... num2str([countiter counteval]) ']']); end end end % Adapt sigma if flg_future_setting % according to a suggestion from Dirk Arnold (2000) % exp(1) is still not reasonably small enough, maybe 2/3? sigma = sigma * exp(min(1, (sum(ps.^2)/N - 1)/2 * cs/damps)); % Eq. (5) else % exp(1) is still not reasonably small enough sigma = sigma * exp(min(1, (sqrt(sum(ps.^2))/chiN - 1) * cs/damps)); % Eq. (5) end % disp([countiter norm(ps)/chiN]); if 11 < 3 % testing with optimal step-size if countiter == 1 disp('*********** sigma set to const * ||x|| ******************'); end sigma = 0.04 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=1000:25e3 sigma = 0.3 * mueff * sqrt(sum(xmean.^2)) / N; % 20D,lam=(40,1000):17e3 % 75e3 with def (1.5) % 35e3 with damps=0.25 end if 11 < 3 if countiter == 1 disp('*********** xmean set to const ******************'); end xmean = ones(N,1); end % Update B and D from C if ~flgDiagonalOnly && (ccov1+ccovmu+neg.ccov) > 0 && mod(countiter, 1/(ccov1+ccovmu+neg.ccov)/N/10) < 1 C=triu(C)+triu(C,1)'; % enforce symmetry to prevent complex numbers [B,tmp] = eig(C); % eigen decomposition, B==normalized eigenvectors % effort: approx. 15*N matrix-vector multiplications diagD = diag(tmp); if any(~isfinite(diagD)) clear idx; % prevents error under octave save(['tmp' opts.SaveFilename]); error(['function eig returned non-finited eigenvalues, cond(C)=' ... num2str(cond(C)) ]); end if any(any(~isfinite(B))) clear idx; % prevents error under octave save(['tmp' opts.SaveFilename]); error(['function eig returned non-finited eigenvectors, cond(C)=' ... num2str(cond(C)) ]); end % limit condition of C to 1e14 + 1 if min(diagD) <= 0 if stopOnWarnings stopflag(end+1) = {'warnconditioncov'}; else warning(['Iteration ' num2str(countiter) ... ': Eigenvalue (smaller) zero']); diagD(diagD<0) = 0; tmp = max(diagD)/1e14; C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); end end if max(diagD) > 1e14*min(diagD) if stopOnWarnings stopflag(end+1) = {'warnconditioncov'}; else warning(['Iteration ' num2str(countiter) ': condition of C ' ... 'at upper limit' ]); tmp = max(diagD)/1e14 - min(diagD); C = C + tmp*eye(N,N); diagD = diagD + tmp*ones(N,1); end end diagC = diag(C); diagD = sqrt(diagD); % D contains standard deviations now % diagD = diagD / prod(diagD)^(1/N); C = C / prod(diagD)^(2/N); BD = B.*repmat(diagD',N,1); % O(n^2) end % if mod % Align/rescale order of magnitude of scales of sigma and C for nicer output % TODO: interference with sigmafacup: replace 1e10 with 2*sigmafacup % not a very usual case if 1 < 2 && sigma > 1e10*max(diagD) && sigma > 8e14 * max(insigma) fac = sigma; % / max(diagD); sigma = sigma/fac; pc = fac * pc; diagD = fac * diagD; if ~flgDiagonalOnly C = fac^2 * C; % disp(fac); BD = B .* repmat(diagD',N,1); % O(n^2), but repmat might be inefficient todo? end diagC = fac^2 * diagC; end if flgDiagonalOnly > 1 && countiter > flgDiagonalOnly % full covariance matrix from now on flgDiagonalOnly = 0; B = eye(N,N); BD = diag(diagD); C = diag(diagC); % is better, because correlations are spurious anyway end if noiseHandling if countiter == 1 % assign firstvarargin for noise treatment e.g. as #reevaluations if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) if irun == 1 firstvarargin = varargin{1}; else varargin{1} = firstvarargin; % reset varargin{1} end else firstvarargin = 0; end end if noiseSS < 0 && noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin varargin{1} = max(noiseMinMaxEvals(1), varargin{1} / noiseAlphaEvals^(1/4)); % still experimental elseif noiseSS > 0 if ~isempty(noiseCallback) % to be removed? res = feval(noiseCallback); % should also work without output argument!? if ~isempty(res) && res > 1 % TODO: decide for interface of callback % also a dynamic popsize could be done here sigma = sigma * noiseAlpha; end else if noiseMinMaxEvals(2) > noiseMinMaxEvals(1) && firstvarargin varargin{1} = min(noiseMinMaxEvals(2), varargin{1} * noiseAlphaEvals); end sigma = sigma * noiseAlpha; % lambda = ceil(0.1 * sqrt(lambda) + lambda); % TODO: find smallest increase of lambda with log-linear % convergence in iterations end % qqq experimental: take a mean to estimate the true optimum noiseN = noiseN + 1; if noiseN == 1 noiseX = xmean; else noiseX = noiseX + (3/noiseN) * (xmean - noiseX); end end end % ----- numerical error management ----- % Adjust maximal coordinate axis deviations if any(sigma*sqrt(diagC) > maxdx) sigma = min(maxdx ./ sqrt(diagC)); %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... % 'deviation at upper limit of ' num2str(maxdx)]); % stopflag(end+1) = {'maxcoorddev'}; end % Adjust minimal coordinate axis deviations if any(sigma*sqrt(diagC) < mindx) sigma = max(mindx ./ sqrt(diagC)) * exp(0.05+cs/damps); %warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... % 'deviation at lower limit of ' num2str(mindx)]); % stopflag(end+1) = {'mincoorddev'};; end % Adjust too low coordinate axis deviations if any(xmean == xmean + 0.2*sigma*sqrt(diagC)) if stopOnWarnings stopflag(end+1) = {'warnnoeffectcoord'}; else warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ... 'deviation too low' ]); if flgDiagonalOnly diagC = diagC + (ccov1_sep+ccovmu_sep) * (diagC .* ... (xmean == xmean + 0.2*sigma*sqrt(diagC))); else C = C + (ccov1+ccovmu) * diag(diagC .* ... (xmean == xmean + 0.2*sigma*sqrt(diagC))); end sigma = sigma * exp(0.05+cs/damps); end end % Adjust step size in case of (numerical) precision problem if flgDiagonalOnly tmp = 0.1*sigma*diagD; else tmp = 0.1*sigma*BD(:,1+floor(mod(countiter,N))); end if all(xmean == xmean + tmp) i = 1+floor(mod(countiter,N)); if stopOnWarnings stopflag(end+1) = {'warnnoeffectaxis'}; else warning(['Iteration ' num2str(countiter) ... ': main axis standard deviation ' ... num2str(sigma*diagD(i)) ' has no effect' ]); sigma = sigma * exp(0.2+cs/damps); end end % Adjust step size in case of equal function values (flat fitness) % isequalfuncvalues = 0; if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4)) % isequalfuncvalues = 1; if stopOnEqualFunctionValues arrEqualFunvals = [countiter arrEqualFunvals(1:end-1)]; % stop if this happens in more than 33% if arrEqualFunvals(end) > countiter - 3 * length(arrEqualFunvals) stopflag(end+1) = {'equalfunvals'}; end else if flgWarnOnEqualFunctionValues warning(['Iteration ' num2str(countiter) ... ': equal function values f=' num2str(fitness.sel(1)) ... ' at maximal main axis sigma ' ... num2str(sigma*max(diagD))]); end sigma = sigma * exp(0.2+cs/damps); end end % Adjust step size in case of equal function values if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0 if stopOnWarnings stopflag(end+1) = {'warnequalfunvalhist'}; else warning(['Iteration ' num2str(countiter) ... ': equal function values in history at maximal main ' ... 'axis sigma ' num2str(sigma*max(diagD))]); sigma = sigma * exp(0.2+cs/damps); end end % ----- end numerical error management ----- % Keep overall best solution out.evals = counteval; out.solutions.evals = counteval; out.solutions.mean.x = xmean; out.solutions.mean.f = fmean; out.solutions.mean.evals = counteval; out.solutions.recentbest.x = arxvalid(:, fitness.idx(1)); out.solutions.recentbest.f = fitness.raw(1); out.solutions.recentbest.evals = counteval + fitness.idx(1) - lambda; out.solutions.recentworst.x = arxvalid(:, fitness.idx(end)); out.solutions.recentworst.f = fitness.raw(end); out.solutions.recentworst.evals = counteval + fitness.idx(end) - lambda; if fitness.hist(1) < out.solutions.bestever.f out.solutions.bestever.x = arxvalid(:, fitness.idx(1)); out.solutions.bestever.f = fitness.hist(1); out.solutions.bestever.evals = counteval + fitness.idx(1) - lambda; bestever = out.solutions.bestever; end % Set stop flag if fitness.raw(1) <= stopFitness, stopflag(end+1) = {'fitness'}; end if counteval >= stopMaxFunEvals, stopflag(end+1) = {'maxfunevals'}; end if countiter >= stopMaxIter, stopflag(end+1) = {'maxiter'}; end if all(sigma*(max(abs(pc), sqrt(diagC))) < stopTolX) stopflag(end+1) = {'tolx'}; end if any(sigma*sqrt(diagC) > stopTolUpX) stopflag(end+1) = {'tolupx'}; end if sigma*max(diagD) == 0 % should never happen stopflag(end+1) = {'bug'}; end if countiter > 2 && myrange([fitness.sel fitness.hist]) <= stopTolFun stopflag(end+1) = {'tolfun'}; end if countiter >= length(fitness.hist) && myrange(fitness.hist) <= stopTolHistFun stopflag(end+1) = {'tolhistfun'}; end l = floor(length(fitness.histbest)/3); if 1 < 2 && stopOnStagnation && ... % leads sometimes early stop on ftablet, fcigtab countiter > N * (5+100/lambda) && ... length(fitness.histbest) > 100 && ... median(fitness.histmedian(1:l)) >= median(fitness.histmedian(end-l:end)) && ... median(fitness.histbest(1:l)) >= median(fitness.histbest(end-l:end)) stopflag(end+1) = {'stagnation'}; end if counteval >= stopFunEvals || countiter >= stopIter stopflag(end+1) = {'stoptoresume'}; if length(stopflag) == 1 && flgsaving == 0 error('To resume later the saving option needs to be set'); end end % read stopping message from file signals.par if flgreadsignals fid = fopen('./signals.par', 'rt'); % can be performance critical while fid > 0 strline = fgetl(fid); %fgets(fid, 300); if strline < 0 % fgets and fgetl returns -1 at end of file break; end % 'stop filename' sets stopflag to manual str = sscanf(strline, ' %s %s', 2); if strcmp(str, ['stop' opts.LogFilenamePrefix]) stopflag(end+1) = {'manual'}; break; end % 'skip filename run 3' skips a run, but not the last str = sscanf(strline, ' %s %s %s', 3); if strcmp(str, ['skip' opts.LogFilenamePrefix 'run']) i = strfind(strline, 'run'); if irun == sscanf(strline(i+3:end), ' %d ', 1) && irun <= myeval(opts.Restarts) stopflag(end+1) = {'skipped'}; end end end % while, break if fid > 0 fclose(fid); clear fid; % prevents strange error under octave end end out.stopflag = stopflag; % ----- output generation ----- if verbosemodulo > 0 && isfinite(verbosemodulo) if countiter == 1 || mod(countiter, 10*verbosemodulo) < 1 disp(['Iterat, #Fevals: Function Value (median,worst) ' ... '|Axis Ratio|' ... 'idx:Min SD idx:Max SD']); end if mod(countiter, verbosemodulo) < 1 ... || (verbosemodulo > 0 && isfinite(verbosemodulo) && ... (countiter < 3 || ~isempty(stopflag))) [minstd minstdidx] = min(sigma*sqrt(diagC)); [maxstd maxstdidx] = max(sigma*sqrt(diagC)); % format display nicely disp([repmat(' ',1,4-floor(log10(countiter))) ... num2str(countiter) ' , ' ... repmat(' ',1,5-floor(log10(counteval))) ... num2str(counteval) ' : ' ... num2str(fitness.hist(1), '%.13e') ... ' +(' num2str(median(fitness.raw)-fitness.hist(1), '%.0e ') ... ',' num2str(max(fitness.raw)-fitness.hist(1), '%.0e ') ... ') | ' ... num2str(max(diagD)/min(diagD), '%4.2e') ' | ' ... repmat(' ',1,1-floor(log10(minstdidx))) num2str(minstdidx) ':' ... num2str(minstd, ' %.1e') ' ' ... repmat(' ',1,1-floor(log10(maxstdidx))) num2str(maxstdidx) ':' ... num2str(maxstd, ' %.1e')]); end end % measure time for recording data if countiter < 3 time.c = 0.05; time.nonoutput = 0; time.recording = 0; time.saving = 0.15; % first saving after 3 seconds of 100 iterations time.plotting = 0; elseif countiter > 300 % set backward horizon, must be long enough to cover infrequent plotting etc % time.c = min(1, time.nonoutput/3 + 1e-9); time.c = max(1e-5, 0.1/sqrt(countiter)); % mean over all or 1e-5 end % get average time per iteration time.t1 = clock; time.act = max(0,etime(time.t1, time.t0)); time.nonoutput = (1-time.c) * time.nonoutput ... + time.c * time.act; time.recording = (1-time.c) * time.recording; % per iteration time.saving = (1-time.c) * time.saving; time.plotting = (1-time.c) * time.plotting; % record output data, concerning time issues if savemodulo && savetime && (countiter < 1e2 || ~isempty(stopflag) || ... countiter >= outiter + savemodulo) outiter = countiter; % Save output data to files for namecell = filenames(:)' name = namecell{:}; [fid, err] = fopen(['./' filenameprefix name '.dat'], 'a'); if fid < 1 % err ~= 0 warning(['could not open ' filenameprefix name '.dat']); else if strcmp(name, 'axlen') fprintf(fid, '%d %d %e %e %e ', countiter, counteval, sigma, ... max(diagD), min(diagD)); fprintf(fid, '%e ', sort(diagD)); fprintf(fid, '\n'); elseif strcmp(name, 'disp') % TODO elseif strcmp(name, 'fit') fprintf(fid, '%ld %ld %e %e %25.18e %25.18e %25.18e %25.18e', ... countiter, counteval, sigma, max(diagD)/min(diagD), ... out.solutions.bestever.f, ... fitness.raw(1), median(fitness.raw), fitness.raw(end)); if ~isempty(varargin) && length(varargin{1}) == 1 && isnumeric(varargin{1}) && varargin{1} ~= 0 fprintf(fid, ' %f', varargin{1}); end fprintf(fid, '\n'); elseif strcmp(name, 'stddev') fprintf(fid, '%ld %ld %e 0 0 ', countiter, counteval, sigma); fprintf(fid, '%e ', sigma*sqrt(diagC)); fprintf(fid, '\n'); elseif strcmp(name, 'xmean') if isnan(fmean) fprintf(fid, '%ld %ld 0 0 0 ', countiter, counteval); else fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean); end fprintf(fid, '%e ', xmean); fprintf(fid, '\n'); elseif strcmp(name, 'xrecentbest') % TODO: fitness is inconsistent with x-value fprintf(fid, '%ld %ld %25.18e 0 0 ', countiter, counteval, fitness.raw(1)); fprintf(fid, '%e ', arx(:,fitness.idx(1))); fprintf(fid, '\n'); end fclose(fid); end end % get average time for recording data time.t2 = clock; time.recording = time.recording + time.c * max(0,etime(time.t2, time.t1)); % plot if flgplotting && countiter > 1 if countiter == 2 iterplotted = 0; end if ~isempty(stopflag) || ... ((time.nonoutput+time.recording) * (countiter - iterplotted) > 1 && ... time.plotting < 0.05 * (time.nonoutput+time.recording)) local_plotcmaesdat(324, filenameprefix); iterplotted = countiter; % outplot(out); % outplot defined below if time.plotting == 0 % disregard opening of the window time.plotting = time.nonoutput+time.recording; else time.plotting = time.plotting + time.c * max(0,etime(clock, time.t2)); end end end if countiter > 100 + 20 && savemodulo && ... time.recording * countiter > 0.1 && ... % absolute time larger 0.1 second time.recording > savetime * (time.nonoutput+time.recording) / 100 savemodulo = floor(1.02 * savemodulo) + 1; % disp(['++savemodulo == ' num2str(savemodulo) ' at ' num2str(countiter)]); %qqq end end % if output % save everything time.t3 = clock; if ~isempty(stopflag) || time.saving < 0.05 * time.nonoutput || countiter == 100 xmin = arxvalid(:, fitness.idx(1)); fmin = fitness.raw(1); if flgsaving && countiter > 2 clear idx; % prevents error under octave % -v6 : non-compressed non-unicode for version 6 and earlier if ~isempty(strsaving) && ~isoctave if exist(opts.SaveFilename,'file') copyfile(opts.SaveFilename,[opts.SaveFilename, '.bak']); end save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart else if exist(opts.SaveFilename,'file') copyfile(opts.SaveFilename,[opts.SaveFilename, '.bak']); end save('-mat', opts.SaveFilename); % for inspection and possible restart end time.saving = time.saving + time.c * max(0,etime(clock, time.t3)); end end time.t0 = clock; % ----- end output generation ----- end % while, end generation loop % -------------------- Final Procedures ------------------------------- % Evaluate xmean and return best recent point in xmin fmin = fitness.raw(1); xmin = arxvalid(:, fitness.idx(1)); % Return best point of last generation. if length(stopflag) > sum(strcmp(stopflag, 'stoptoresume')) % final stopping out.solutions.mean.f = ... feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:}); counteval = counteval + 1; out.solutions.mean.evals = counteval; if out.solutions.mean.f < fitness.raw(1) fmin = out.solutions.mean.f; xmin = xintobounds(xmean, lbounds, ubounds); % Return xmean as best point end if out.solutions.mean.f < out.solutions.bestever.f out.solutions.bestever = out.solutions.mean; % Return xmean as bestever point out.solutions.bestever.x = xintobounds(xmean, lbounds, ubounds); bestever = out.solutions.bestever; end end % Save everything and display final message if flgsavingfinal clear idx; % prevents error under octave if ~isempty(strsaving) && ~isoctave save('-mat', strsaving, opts.SaveFilename); % for inspection and possible restart else save('-mat', opts.SaveFilename); % for inspection and possible restart end message = [' (saved to ' opts.SaveFilename ')']; else message = []; end if flgdisplay disp(['#Fevals: f(returned x) | bestever.f | stopflag' ... message]); if isoctave strstop = stopflag(:); else strcat(stopflag(:), '.'); end strstop = stopflag(:); %strcat(stopflag(:), '.'); disp([repmat(' ',1,6-floor(log10(counteval))) ... num2str(counteval, '%6.0f') ': ' num2str(fmin, '%.11e') ' | ' ... num2str(out.solutions.bestever.f, '%.11e') ' | ' ... strstop{1:end}]); if N < 102 disp(['mean solution:' sprintf(' %+.1e', xmean)]); disp(['std deviation:' sprintf(' %.1e', sigma*sqrt(diagC))]); disp(sprintf('use plotcmaesdat.m for plotting the output at any time (option LogModulo must not be zero)')); end if exist('sfile', 'var') disp(['Results saved in ' sfile]); end end out.arstopflags{irun} = stopflag; if any(strcmp(stopflag, 'fitness')) ... || any(strcmp(stopflag, 'maxfunevals')) ... || any(strcmp(stopflag, 'stoptoresume')) ... || any(strcmp(stopflag, 'manual')) break; end end % while irun <= Restarts % --------------------------------------------------------------- % --------------------------------------------------------------- function [x, idx] = xintobounds(x, lbounds, ubounds) % % x can be a column vector or a matrix consisting of column vectors % if ~isempty(lbounds) if length(lbounds) == 1 idx = x < lbounds; x(idx) = lbounds; else arbounds = repmat(lbounds, 1, size(x,2)); idx = x < arbounds; x(idx) = arbounds(idx); end else idx = 0; end if ~isempty(ubounds) if length(ubounds) == 1 idx2 = x > ubounds; x(idx2) = ubounds; else arbounds = repmat(ubounds, 1, size(x,2)); idx2 = x > arbounds; x(idx2) = arbounds(idx2); end else idx2 = 0; end idx = idx2-idx; % --------------------------------------------------------------- % --------------------------------------------------------------- function opts=getoptions(inopts, defopts) % OPTS = GETOPTIONS(INOPTS, DEFOPTS) handles an arbitrary number of % optional arguments to a function. The given arguments are collected % in the struct INOPTS. GETOPTIONS matches INOPTS with a default % options struct DEFOPTS and returns the merge OPTS. Empty or missing % fields in INOPTS invoke the default value. Fieldnames in INOPTS can % be abbreviated. % % The returned struct OPTS is first assigned to DEFOPTS. Then any % field value in OPTS is replaced by the respective field value of % INOPTS if (1) the field unambiguously (case-insensitive) matches % with the fieldname in INOPTS (cut down to the length of the INOPTS % fieldname) and (2) the field is not empty. % % Example: % In the source-code of the function that needs optional % arguments, the last argument is the struct of optional % arguments: % % function results = myfunction(mandatory_arg, inopts) % % Define four default options % defopts.PopulationSize = 200; % defopts.ParentNumber = 50; % defopts.MaxIterations = 1e6; % defopts.MaxSigma = 1; % % % merge default options with input options % opts = getoptions(inopts, defopts); % % % Thats it! From now on the values in opts can be used % for i = 1:opts.PopulationSize % % do whatever % if sigma > opts.MaxSigma % % do whatever % end % end % % For calling the function myfunction with default options: % myfunction(argument1, []); % For calling the function myfunction with modified options: % opt.pop = 100; % redefine PopulationSize option % opt.PAR = 10; % redefine ParentNumber option % opt.maxiter = 2; % opt.max=2 is ambiguous and would result in an error % myfunction(argument1, opt); % % 04/07/19: Entries can be structs itself leading to a recursive % call to getoptions. % if nargin < 2 || isempty(defopts) % no default options available opts=inopts; return; elseif isempty(inopts) % empty inopts invoke default options opts = defopts; return; elseif ~isstruct(defopts) % handle a single option value if isempty(inopts) opts = defopts; elseif ~isstruct(inopts) opts = inopts; else error('Input options are a struct, while default options are not'); end return; elseif ~isstruct(inopts) % no valid input options error('The options need to be a struct or empty'); end opts = defopts; % start from defopts % if necessary overwrite opts fields by inopts values defnames = fieldnames(defopts); idxmatched = []; % indices of defopts that already matched for name = fieldnames(inopts)' name = name{1}; % name of i-th inopts-field if isoctave for i = 1:size(defnames, 1) idx(i) = strncmpi(defnames(i), name, length(name)); end else idx = strncmpi(defnames, name, length(name)); end if sum(idx) > 1 error(['option "' name '" is not an unambigous abbreviation. ' ... 'Use opts=RMFIELD(opts, ''' name, ... ''') to remove the field from the struct.']); end if sum(idx) == 1 defname = defnames{find(idx)}; if ismember(find(idx), idxmatched) error(['input options match more than ones with "' ... defname '". ' ... 'Use opts=RMFIELD(opts, ''' name, ... ''') to remove the field from the struct.']); end idxmatched = [idxmatched find(idx)]; val = getfield(inopts, name); % next line can replace previous line from MATLAB version 6.5.0 on and in octave % val = inopts.(name); if isstruct(val) % valid syntax only from version 6.5.0 opts = setfield(opts, defname, ... getoptions(val, getfield(defopts, defname))); elseif isstruct(getfield(defopts, defname)) % next three lines can replace previous three lines from MATLAB % version 6.5.0 on % opts.(defname) = ... % getoptions(val, defopts.(defname)); % elseif isstruct(defopts.(defname)) warning(['option "' name '" disregarded (must be struct)']); elseif ~isempty(val) % empty value: do nothing, i.e. stick to default opts = setfield(opts, defnames{find(idx)}, val); % next line can replace previous line from MATLAB version 6.5.0 on % opts.(defname) = inopts.(name); end else warning(['option "' name '" disregarded (unknown field name)']); end end % --------------------------------------------------------------- % --------------------------------------------------------------- function res=myeval(s) if ischar(s) res = evalin('caller', s); else res = s; end % --------------------------------------------------------------- % --------------------------------------------------------------- function res=myevalbool(s) if ~ischar(s) % s may not and cannot be empty res = s; else % evaluation string s if strncmpi(s, 'yes', 3) || strncmpi(s, 'on', 2) ... || strncmpi(s, 'true', 4) || strncmp(s, '1 ', 2) res = 1; elseif strncmpi(s, 'no', 2) || strncmpi(s, 'off', 3) ... || strncmpi(s, 'false', 5) || strncmp(s, '0 ', 2) res = 0; else try res = evalin('caller', s); catch error(['String value "' s '" cannot be evaluated']); end try res ~= 0; catch error(['String value "' s '" cannot be evaluated reasonably']); end end end % --------------------------------------------------------------- % --------------------------------------------------------------- function res = isoctave % any hack to find out whether we are running octave s = version; res = 0; if exist('fflush', 'builtin') && eval(s(1)) < 7 res = 1; end % --------------------------------------------------------------- % --------------------------------------------------------------- function flush if isoctave feval('fflush', stdout); end % --------------------------------------------------------------- % --------------------------------------------------------------- % ----- replacements for statistic toolbox functions ------------ % --------------------------------------------------------------- % --------------------------------------------------------------- function res=myrange(x) res = max(x) - min(x); % --------------------------------------------------------------- % --------------------------------------------------------------- function res = myprctile(inar, perc, idx) % % Computes the percentiles in vector perc from vector inar % returns vector with length(res)==length(perc) % idx: optional index-array indicating sorted order % N = length(inar); flgtranspose = 0; % sizes if size(perc,1) > 1 perc = perc'; flgtranspose = 1; if size(perc,1) > 1 error('perc must not be a matrix'); end end if size(inar, 1) > 1 && size(inar,2) > 1 error('data inar must not be a matrix'); end % sort inar if nargin < 3 || isempty(idx) [sar idx] = sort(inar); else sar = inar(idx); end res = []; for p = perc if p <= 100*(0.5/N) res(end+1) = sar(1); elseif p >= 100*((N-0.5)/N) res(end+1) = sar(N); else % find largest index smaller than required percentile availablepercentiles = 100*((1:N)-0.5)/N; i = max(find(p > availablepercentiles)); % interpolate linearly res(end+1) = sar(i) ... + (sar(i+1)-sar(i))*(p - availablepercentiles(i)) ... / (availablepercentiles(i+1) - availablepercentiles(i)); end end if flgtranspose res = res'; end % --------------------------------------------------------------- % --------------------------------------------------------------- % --------------------------------------------------------------- % --------------------------------------------------------------- function [s ranks rankDelta] = local_noisemeasurement(arf1, arf2, lamreev, theta, cutlimit) % function [s ranks rankDelta] = noisemeasurement(arf1, arf2, lamreev, theta) % % Input: % arf1, arf2 : two arrays of function values. arf1 is of size 1xlambda, % arf2 may be of size 1xlamreev or 1xlambda. The first lamreev values % in arf2 are (re-)evaluations of the respective solutions, i.e. % arf1(1) and arf2(1) are two evaluations of "the first" solution. % lamreev: number of reevaluated individuals in arf2 % theta : parameter theta for the rank change limit, between 0 and 1, % typically between 0.2 and 0.7. % cutlimit (optional): output s is computed as a mean of rankchange minus % threshold, where rankchange is <=2*(lambda-1). cutlimit limits % abs(rankchange minus threshold) in this calculation to cutlimit. % cutlimit=1 evaluates basically the sign only. cutlimit=2 could be % the rank change with one solution (both evaluations of it). % % Output: % s : noise measurement, s>0 means the noise measure is above the % acceptance threshold % ranks : 2xlambda array, corresponding to [arf1; arf2], of ranks % of arf1 and arf2 in the set [arf1 arf2], values are in [1:2*lambda] % rankDelta: 1xlambda array of rank movements of arf2 compared to % arf1. rankDelta(i) agrees with the number of values from % the set [arf1 arf2] that lie between arf1(i) and arf2(i). % % Note: equal function values might lead to somewhat spurious results. % For this case a revision is advisable. %%% verify input argument sizes if size(arf1,1) ~= 1 error('arf1 must be an 1xlambda array'); elseif size(arf2,1) ~= 1 error('arf2 must be an 1xsomething array'); elseif size(arf1,2) < size(arf2,2) % not really necessary, but saver error('arf2 must not be smaller than arf1 in length'); end lam = size(arf1, 2); if size(arf1,2) ~= size(arf2,2) arf2(end+1:lam) = arf1((size(arf2,2)+1):lam); end if nargin < 5 cutlimit = inf; end %%% capture unusual values if any(diff(arf1) == 0) % this will presumably interpreted as rank change, because % sort(ones(...)) returns 1,2,3,... warning([num2str(sum(diff(arf1)==0)) ' equal function values']); end %%% compute rank changes into rankDelta % compute ranks [ignore, idx] = sort([arf1 arf2]); [ignore, ranks] = sort(idx); ranks = reshape(ranks, lam, 2)'; rankDelta = ranks(1,:) - ranks(2,:) - sign(ranks(1,:) - ranks(2,:)); %%% compute rank change limits using both ranks(1,...) and ranks(2,...) for i = 1:lamreev sumlim(i) = ... 0.5 * (... myprctile(abs((1:2*lam-1) - (ranks(1,i) - (ranks(1,i)>ranks(2,i)))), ... theta*50) ... + myprctile(abs((1:2*lam-1) - (ranks(2,i) - (ranks(2,i)>ranks(1,i)))), ... theta*50)); end %%% compute measurement %s = abs(rankDelta(1:lamreev)) - sumlim; % lives roughly in 0..2*lambda % max: 1 rankchange in 2*lambda is always fine s = abs(rankDelta(1:lamreev)) - max(1, sumlim); % lives roughly in 0..2*lambda % cut-off limit idx = abs(s) > cutlimit; s(idx) = sign(s(idx)) * cutlimit; s = mean(s); % --------------------------------------------------------------- % --------------------------------------------------------------- % --------------------------------------------------------------- % --------------------------------------------------------------- % just a "local" copy of plotcmaesdat.m, with manual_mode set to zero function local_plotcmaesdat(figNb, filenameprefix, filenameextension, objectvarname) % PLOTCMAESDAT; % PLOTCMAES(FIGURENUMBER_iBEGIN_iEND, FILENAMEPREFIX, FILENAMEEXTENSION, OBJECTVARNAME); % plots output from CMA-ES, e.g. cmaes.m, Java class CMAEvolutionStrategy... % mod(figNb,100)==1 plots versus iterations. % % PLOTCMAES([101 300]) plots versus iteration, from iteration 300. % PLOTCMAES([100 150 800]) plots versus function evaluations, between iteration 150 and 800. % % Upper left subplot: blue/red: function value of the best solution in the % recent population, cyan: same function value minus best % ever seen function value, green: sigma, red: ratio between % longest and shortest principal axis length which is equivalent % to sqrt(cond(C)). % Upper right plot: time evolution of the distribution mean (default) or % the recent best solution vector. % Lower left: principal axes lengths of the distribution ellipsoid, % equivalent with the sqrt(eig(C)) square root eigenvalues of C. % Lower right: magenta: minimal and maximal "true" standard deviation % (with sigma included) in the coordinates, other colors: sqrt(diag(C)) % of all diagonal elements of C, if C is diagonal they equal to the % lower left. % % Files [FILENAMEPREFIX name FILENAMEEXTENSION] are used, where % name = axlen, OBJECTVARNAME (xmean|xrecentbest), fit, or stddev. % manual_mode = 0; if nargin < 1 || isempty(figNb) figNb = 325; end if nargin < 2 || isempty(filenameprefix) filenameprefix = 'outcmaes'; end if nargin < 3 || isempty(filenameextension) filenameextension = '.dat'; end if nargin < 4 || isempty(objectvarname) objectvarname = 'xmean'; objectvarname = 'xrecentbest'; end % load data d.x = load([filenameprefix objectvarname filenameextension]); % d.x = load([filenameprefix 'xmean' filenameextension]); % d.x = load([filenameprefix 'xrecentbest' filenameextension]); d.f = load([filenameprefix 'fit' filenameextension]); d.std = load([filenameprefix 'stddev' filenameextension]); d.D = load([filenameprefix 'axlen' filenameextension]); % interpret entries in figNb for cutting out some data if length(figNb) > 1 iend = inf; istart = figNb(2); if length(figNb) > 2 iend = figNb(3); end figNb = figNb(1); d.x = d.x(d.x(:,1) >= istart & d.x(:,1) <= iend, :); d.f = d.f(d.f(:,1) >= istart & d.f(:,1) <= iend, :); d.std = d.std(d.std(:,1) >= istart & d.std(:,1) <= iend, :); d.D = d.D(d.D(:,1) >= istart & d.D(:,1) <= iend, :); end % decide for x-axis iabscissa = 2; % 1== versus iterations, 2==versus fevals if mod(figNb,100) == 1 iabscissa = 1; % a short hack end if iabscissa == 1 xlab ='iterations'; elseif iabscissa == 2 xlab = 'function evaluations'; end if size(d.x, 2) < 1000 minxend = 1.03*d.x(end, iabscissa); else minxend = 0; end % set up figure window if manual_mode figure(figNb); % just create and raise the figure window else if 1 < 3 && evalin('caller', 'iterplotted') == 0 && evalin('caller', 'irun') == 1 figure(figNb); % incomment this, if figure raise in the beginning is not desired elseif ismember(figNb, findobj('Type', 'figure')) set(0, 'CurrentFigure', figNb); % prevents raise of existing figure window else figure(figNb); end end % plot fitness etc foffset = 1e-99; dfit = d.f(:,6)-min(d.f(:,6)); [ignore idxbest] = min(dfit); dfit(dfit<1e-98) = NaN; subplot(2,2,1); hold off; dd = abs(d.f(:,7:8)) + foffset; dd(d.f(:,7:8)==0) = NaN; semilogy(d.f(:,iabscissa), dd, '-k'); hold on; % additional fitness data, for example constraints values if size(d.f,2) > 8 dd = abs(d.f(:,9:end)) + 10*foffset; % a hack % dd(d.f(:,9:end)==0) = NaN; semilogy(d.f(:,iabscissa), dd, '-m'); hold on; if size(d.f,2) > 12 semilogy(d.f(:,iabscissa),abs(d.f(:,[7 8 11 13]))+foffset,'-k'); hold on; end end idx = find(d.f(:,6)>1e-98); % positive values if ~isempty(idx) % otherwise non-log plot gets hold semilogy(d.f(idx,iabscissa), d.f(idx,6)+foffset, '.b'); hold on; end idx = find(d.f(:,6) < -1e-98); % negative values if ~isempty(idx) semilogy(d.f(idx, iabscissa), abs(d.f(idx,6))+foffset,'.r'); hold on; end semilogy(d.f(:,iabscissa),abs(d.f(:,6))+foffset,'-b'); hold on; semilogy(d.f(:,iabscissa),dfit,'-c'); hold on; semilogy(d.f(:,iabscissa),(d.f(:,4)),'-r'); hold on; % AR semilogy(d.std(:,iabscissa), [max(d.std(:,6:end)')' ... min(d.std(:,6:end)')'], '-m'); % max,min std maxval = max(d.std(end,6:end)); minval = min(d.std(end,6:end)); text(d.std(end,iabscissa), maxval, sprintf('%.0e', maxval)); text(d.std(end,iabscissa), minval, sprintf('%.0e', minval)); semilogy(d.std(:,iabscissa),(d.std(:,3)),'-g'); % sigma % plot best f semilogy(d.f(idxbest,iabscissa),min(dfit),'*c'); hold on; semilogy(d.f(idxbest,iabscissa),abs(d.f(idxbest,6))+foffset,'*r'); hold on; ax = axis; ax(2) = max(minxend, ax(2)); axis(ax); yannote = 10^(log10(ax(3)) + 0.05*(log10(ax(4))-log10(ax(3)))); text(ax(1), yannote, ... [ 'f=' num2str(d.f(end,6), '%.15g') ]); title('blue:abs(f), cyan:f-min(f), green:sigma, red:axis ratio'); grid on; subplot(2,2,2); hold off; plot(d.x(:,iabscissa), d.x(:,6:end),'-'); hold on; ax = axis; ax(2) = max(minxend, ax(2)); axis(ax); % add some annotation lines [ignore idx] = sort(d.x(end,6:end)); % choose no more than 25 indices idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); yy = repmat(NaN, 2, size(d.x,2)-5); yy(1,:) = d.x(end, 6:end); yy(2,idx(idxs)) = linspace(ax(3), ax(4), length(idxs)); plot([d.x(end,iabscissa) ax(2)], yy, '-'); plot(repmat(d.x(end,iabscissa),2), [ax(3) ax(4)], 'k-'); for i = idx(idxs) text(ax(2), yy(2,i), ... ['x(' num2str(i) ')=' num2str(yy(1,i))]); end lam = 'NA'; if size(d.x, 1) > 1 && d.x(end, 1) > d.x(end-1, 1) lam = num2str((d.x(end, 2) - d.x(end-1, 2)) / (d.x(end, 1) - d.x(end-1, 1))); end title(['Object Variables (' num2str(size(d.x, 2)-5) ... '-D, popsize~' lam ')']);grid on; subplot(2,2,3); hold off; semilogy(d.D(:,iabscissa), d.D(:,6:end), '-'); ax = axis; ax(2) = max(minxend, ax(2)); axis(ax); title('Principal Axes Lengths');grid on; xlabel(xlab); subplot(2,2,4); hold off; % semilogy(d.std(:,iabscissa), d.std(:,6:end), 'k-'); hold on; % remove sigma from stds d.std(:,6:end) = d.std(:,6:end) ./ (d.std(:,3) * ones(1,size(d.std,2)-5)); semilogy(d.std(:,iabscissa), d.std(:,6:end), '-'); hold on; if 11 < 3 % max and min std semilogy(d.std(:,iabscissa), [d.std(:,3).*max(d.std(:,6:end)')' ... d.std(:,3).*min(d.std(:,6:end)')'], '-m', 'linewidth', 2); maxval = max(d.std(end,6:end)); minval = min(d.std(end,6:end)); text(d.std(end,iabscissa), d.std(end,3)*maxval, sprintf('max=%.0e', maxval)); text(d.std(end,iabscissa), d.std(end,3)*minval, sprintf('min=%.0e', minval)); end ax = axis; ax(2) = max(minxend, ax(2)); axis(ax); % add some annotation lines [ignore idx] = sort(d.std(end,6:end)); % choose no more than 25 indices idxs = round(linspace(1, size(d.x,2)-5, min(size(d.x,2)-5, 25))); yy = repmat(NaN, 2, size(d.std,2)-5); yy(1,:) = d.std(end, 6:end); yy(2,idx(idxs)) = logspace(log10(ax(3)), log10(ax(4)), length(idxs)); semilogy([d.std(end,iabscissa) ax(2)], yy, '-'); semilogy(repmat(d.std(end,iabscissa),2), [ax(3) ax(4)], 'k-'); for i = idx(idxs) text(ax(2), yy(2,i), [' ' num2str(i)]); end title('Standard Deviations in Coordinates divided by sigma');grid on; xlabel(xlab); if figNb ~= 324 % zoom on; % does not work in Octave end drawnow; % --------------------------------------------------------------- % --------------- TEST OBJECTIVE FUNCTIONS ---------------------- % --------------------------------------------------------------- %%% Unimodal functions function f=fjens1(x) % % use population size about 2*N % f = sum((x>0) .* x.^1, 1); if any(any(x<0)) idx = sum(x < 0, 1) > 0; f(idx) = 1e3; % f = f + 1e3 * sum(x<0, 1); % f = f + 10 * sum((x<0) .* x.^2, 1); f(idx) = f(idx) + 1e-3*abs(randn(1,sum(idx))); % f(idx) = NaN; end function f=fsphere(x) f = sum(x.^2,1); function f=fmax(x) f = max(abs(x), [], 1); function f=fssphere(x) f=sqrt(sum(x.^2, 1)); % lb = -0.512; ub = 512; % xfeas = x; % xfeas(x<lb) = lb; % xfeas(x>ub) = ub; % f=sum(xfeas.^2, 1); % f = f + 1e-9 * sum((xfeas-x).^2); function f=fspherenoise(x, Nevals) if nargin < 2 || isempty(Nevals) Nevals = 1; end [N,popsi] = size(x); % x = x .* (1 + 0.3e-0 * randn(N, popsi)/(2*N)); % actuator noise fsum = 10.^(0*(0:N-1)/(N-1)) * x.^2; % f = 0*rand(1,1) ... % + fsum ... % + fsum .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)) ... % + 1*fsum.^0.9 .* 2*randn(1,popsi) / (2*N); % % f = fsum .* exp(0.1*randn(1,popsi)); f = fsum .* (1 + (10/(N+10)/sqrt(Nevals))*randn(1,popsi)); % f = fsum .* (1 + (0.1/N)*randn(1,popsi)./randn(1,popsi).^1); idx = rand(1,popsi) < 0.0; if sum(idx) > 0 f(idx) = f(idx) + 1e3*exp(randn(1,sum(idx))); end function f=fmixranks(x) N = size(x,1); f=(10.^(0*(0:(N-1))/(N-1))*x.^2).^0.5; if size(x, 2) > 1 % compute ranks, if it is a population [ignore, idx] = sort(f); [ignore, ranks] = sort(idx); k = 9; % number of solutions randomly permuted, lambda/2-1 % works still quite well (two time slower) for i = k+1:k-0:size(x,2) idx(i-k+(1:k)) = idx(i-k+randperm(k)); end %disp([ranks' f']) [ignore, ranks] = sort(idx); %disp([ranks' f']) %pause f = ranks+1e-9*randn(1,1); end function f = fsphereoneax(x) f = x(1)^2; f = mean(x)^2; function f=frandsphere(x) N = size(x,1); idx = ceil(N*rand(7,1)); f=sum(x(idx).^2); function f=fspherelb0(x, M) % lbound at zero for 1:M needed if nargin < 2 M = 0; end N = size(x,1); % M active bounds, f_i = 1 for x = 0 f = -M + sum((x(1:M) + 1).^2); f = f + sum(x(M+1:N).^2); function f=fspherehull(x) % Patton, Dexter, Goodman, Punch % in -500..500 % spherical ridge through zeros(N,1) % worst case start point seems x = 2*100*sqrt(N) % and small step size N = size(x,1); f = norm(x) + (norm(x-100*sqrt(N)) - 100*N)^2; function f=fellilb0(x, idxM, scal) % lbound at zero for 1:M needed N = size(x,1); if nargin < 3 || isempty(scal) scal = 100; end scale=scal.^((0:N-1)/(N-1)); if nargin < 2 || isempty(idxM) idxM = 1:N; end %scale(N) = 1e0; % M active bounds xopt = 0.1; x(idxM) = x(idxM) + xopt; f = scale.^2*x.^2; f = f - sum((xopt*scale(idxM)).^2); % f = exp(f) - 1; % f = log10(f+1e-19) + 19; f = f + 1e-19; function f=fcornersphere(x) w = ones(size(x,1)); w(1) = 2.5; w(2)=2.5; idx = x < 0; f = sum(x(idx).^2); idx = x > 0; f = f + 2^2*sum(w(idx).*x(idx).^2); function f=fsectorsphere(x, scal) % % This is deceptive for cumulative sigma control CSA in large dimension: % The strategy (initially) diverges for N=50 and popsize = 150. (Even % for cs==1 this can be observed for larger settings of N and % popsize.) The reason is obvious from the function topology. % Divergence can be avoided by setting boundaries or adding a % penalty for large ||x||. Then, convergence can be observed again. % Conclusion: for popsize>N cumulative sigma control is not completely % reasonable, but I do not know better alternatives. In particular: % TPA takes longer to converge than CSA when the latter still works. % if nargin < 2 || isempty (scal) scal = 1e3; end f=sum(x.^2,1); idx = x<0; f = f + (scal^2 - 1) * sum((idx.*x).^2,1); if 11 < 3 idxpen = find(f>1e9); if ~isempty(idxpen) f(idxpen) = f(idxpen) + 1e8*sum(x(:,idxpen).^2,1); end end function f=fstepsphere(x, scal) if nargin < 2 || isempty (scal) scal = 1e0; end N = size(x,1); f=1e-11+sum(scal.^((0:N-1)/(N-1))*floor(x+0.5).^2); f=1e-11+sum(floor(scal.^((0:N-1)/(N-1))'.*x+0.5).^2); % f=1e-11+sum(floor(x+0.5).^2); function f=fstep(x) % in -5.12..5.12 (bounded) N = size(x,1); f=1e-11+6*N+sum(floor(x)); function f=flnorm(x, scal, e) if nargin < 2 || isempty(scal) scal = 1; end if nargin < 3 || isempty(e) e = 1; end if e==inf f = max(abs(x)); else N = size(x,1); scale = scal.^((0:N-1)/(N-1))'; f=sum(abs(scale.*x).^e); end function f=fneumaier3(x) % in -n^2..n^2 % x^*-i = i(n+1-i) N = size(x,1); % f = N*(N+4)*(N-1)/6 + sum((x-1).^2) - sum(x(1:N-1).*x(2:N)); f = sum((x-1).^2) - sum(x(1:N-1).*x(2:N)); function f = fmaxmindist(y) % y in [-1,1], y(1:2) is first point on a plane, y(3:4) second etc % points best % 5 1.4142 % 8 1.03527618 % 10 0.842535997 % 20 0.5997 pop = size(y,2); N = size(y,1)/2; f = []; for ipop = 1:pop if any(abs(y(:,ipop)) > 1) f(ipop) = NaN; else x = reshape(y(:,ipop), [2, N]); f(ipop) = inf; for i = 1:N f(ipop) = min(f(ipop), min(sqrt(sum((x(:,[1:i-1 i+1:N]) - repmat(x(:,i), 1, N-1)).^2, 1)))); end end end f = -f; function f=fchangingsphere(x) N = size(x,1); global scale_G; global count_G; if isempty(count_G) count_G=-1; end count_G = count_G+1; if mod(count_G,10) == 0 scale_G = 10.^(2*rand(1,N)); end %disp(scale(1)); f = scale_G*x.^2; function f= flogsphere(x) f = 1-exp(-sum(x.^2)); function f= fexpsphere(x) f = exp(sum(x.^2)) - 1; function f=fbaluja(x) % in [-0.16 0.16] y = x(1); for i = 2:length(x) y(i) = x(i) + y(i-1); end f = 1e5 - 1/(1e-5 + sum(abs(y))); function f=fschwefel(x) f = 0; for i = 1:size(x,1), f = f+sum(x(1:i))^2; end function f=fcigar(x, ar) if nargin < 2 || isempty(ar) ar = 1e3; end f = x(1,:).^2 + ar^2*sum(x(2:end,:).^2,1); function f=fcigtab(x) f = x(1,:).^2 + 1e8*x(end,:).^2 + 1e4*sum(x(2:(end-1),:).^2, 1); function f=ftablet(x) f = 1e6*x(1,:).^2 + sum(x(2:end,:).^2, 1); function f=felli(x, lgscal, expon, expon2) % lgscal: log10(axis ratio) % expon: x_i^expon, sphere==2 N = size(x,1); if N < 2 error('dimension must be greater one'); end % x = x - repmat(-0.5+(1:N)',1,size(x,2)); % optimum in 1:N if nargin < 2 || isempty(lgscal), lgscal = 3; end if nargin < 3 || isempty(expon), expon = 2; end if nargin < 4 || isempty(expon2), expon2 = 1; end f=((10^(lgscal*expon)).^((0:N-1)/(N-1)) * abs(x).^expon).^(1/expon2); % if rand(1,1) > 0.015 % f = NaN; % end % f = f + randn(size(f)); function f=fellitest(x) beta = 0.9; N = size(x,1); f = (1e6.^((0:(N-1))/(N-1))).^beta * (x.^2).^beta; function f=fellii(x, scal) N = size(x,1); if N < 2 error('dimension must be greater one'); end if nargin < 2 scal = 1; end f= (scal*(1:N)).^2 * (x).^2; function f=fellirot(x) N = size(x,1); global ORTHOGONALCOORSYSTEM_G if isempty(ORTHOGONALCOORSYSTEM_G) ... || length(ORTHOGONALCOORSYSTEM_G) < N ... || isempty(ORTHOGONALCOORSYSTEM_G{N}) coordinatesystem(N); end f = felli(ORTHOGONALCOORSYSTEM_G{N}*x); function f=frot(x, fun, varargin) N = size(x,1); global ORTHOGONALCOORSYSTEM_G if isempty(ORTHOGONALCOORSYSTEM_G) ... || length(ORTHOGONALCOORSYSTEM_G) < N ... || isempty(ORTHOGONALCOORSYSTEM_G{N}) coordinatesystem(N); end f = feval(fun, ORTHOGONALCOORSYSTEM_G{N}*x, varargin{:}); function coordinatesystem(N) if nargin < 1 || isempty(N) arN = 2:30; else arN = N; end global ORTHOGONALCOORSYSTEM_G ORTHOGONALCOORSYSTEM_G{1} = 1; for N = arN ar = randn(N,N); for i = 1:N for j = 1:i-1 ar(:,i) = ar(:,i) - ar(:,i)'*ar(:,j) * ar(:,j); end ar(:,i) = ar(:,i) / norm(ar(:,i)); end ORTHOGONALCOORSYSTEM_G{N} = ar; end function f=fplane(x) f=x(1); function f=ftwoaxes(x) f = sum(x(1:floor(end/2),:).^2, 1) + 1e6*sum(x(floor(1+end/2):end,:).^2, 1); function f=fparabR(x) f = -x(1,:) + 100*sum(x(2:end,:).^2,1); function f=fsharpR(x) f = abs(-x(1, :)).^2 + 100 * sqrt(sum(x(2:end,:).^2, 1)); function f=frosen(x) if size(x,1) < 2 error('dimension must be greater one'); end N = size(x,1); popsi = size(x,2); f = 1e2*sum((x(1:end-1,:).^2 - x(2:end,:)).^2,1) + sum((x(1:end-1,:)-1).^2,1); % f = f + f^0.9 .* (2*randn(1,popsi) ./ randn(1,popsi).^0 / (2*N)); function f=frosenlin(x) if size(x,1) < 2 error('dimension must be greater one'); end x_org = x; x(x>30) = 30; x(x<-30) = -30; f = 1e2*sum(-(x(1:end-1,:).^2 - x(2:end,:)),1) + ... sum((x(1:end-1,:)-1).^2,1); f = f + sum((x-x_org).^2,1); % f(any(abs(x)>30,1)) = NaN; function f=frosenrot(x) N = size(x,1); global ORTHOGONALCOORSYSTEM_G if isempty(ORTHOGONALCOORSYSTEM_G) ... || length(ORTHOGONALCOORSYSTEM_G) < N ... || isempty(ORTHOGONALCOORSYSTEM_G{N}) coordinatesystem(N); end f = frosen(ORTHOGONALCOORSYSTEM_G{N}*x); function f=frosenmodif(x) f = 74 + 100*(x(2)-x(1)^2)^2 + (1-x(1))^2 ... - 400*exp(-sum((x+1).^2)/2/0.05); function f=fschwefelrosen1(x) % in [-10 10] f=sum((x.^2-x(1)).^2 + (x-1).^2); function f=fschwefelrosen2(x) % in [-10 10] f=sum((x(2:end).^2-x(1)).^2 + (x(2:end)-1).^2); function f=fdiffpow(x) [N popsi] = size(x); if N < 2 error('dimension must be greater one'); end f = sum(abs(x).^repmat(2+10*(0:N-1)'/(N-1), 1, popsi), 1); f = sqrt(f); function f=fabsprod(x) f = sum(abs(x),1) + prod(abs(x),1); function f=ffloor(x) f = sum(floor(x+0.5).^2,1); function f=fmaxx(x) f = max(abs(x), [], 1); %%% Multimodal functions function f=fbirastrigin(x) % todo: the volume needs to be a constant N = size(x,1); idx = (sum(x, 1) < 0.5*N); % global optimum f = zeros(1,size(x,2)); f(idx) = 10*(N-sum(cos(2*pi*x(:,idx)),1)) + sum(x(:,idx).^2,1); idx = ~idx; f(idx) = 0.1 + 10*(N-sum(cos(2*pi*(x(:,idx)-2)),1)) + sum((x(:,idx)-2).^2,1); function f=fackley(x) % -32.768..32.768 % Adding a penalty outside the interval is recommended, % because for large step sizes, fackley imposes like frand % N = size(x,1); f = 20-20*exp(-0.2*sqrt(sum(x.^2)/N)); f = f + (exp(1) - exp(sum(cos(2*pi*x))/N)); % add penalty outside the search interval f = f + sum((x(x>32.768)-32.768).^2) + sum((x(x<-32.768)+32.768).^2); function f = fbohachevsky(x) % -15..15 f = sum(x(1:end-1).^2 + 2 * x(2:end).^2 - 0.3 * cos(3*pi*x(1:end-1)) ... - 0.4 * cos(4*pi*x(2:end)) + 0.7); function f=fconcentric(x) % in +-600 s = sum(x.^2); f = s^0.25 * (sin(50*s^0.1)^2 + 1); function f=fgriewank(x) % in [-600 600] [N, P] = size(x); f = 1 - prod(cos(x'./sqrt(1:N))) + sum(x.^2)/4e3; scale = repmat(sqrt(1:N)', 1, P); f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3; % f = f + 1e4*sum(x(abs(x)>5).^2); % if sum(x(abs(x)>5).^2) > 0 % f = 1e4 * sum(x(abs(x)>5).^2) + 1e8 * sum(x(x>5)).^2; % end function f=fgriewrosen(x) % F13 or F8F2 [N, P] = size(x); scale = repmat(sqrt(1:N)', 1, P); y = [x(2:end,:); x(1,:)]; x = 100 * (x.^2 - y) + (x - 1).^2; % Rosenbrock part f = 1 - prod(cos(x./scale), 1) + sum(x.^2, 1)/4e3; f = sum(1 - cos(x) + x.^2/4e3, 1); function f=fspallpseudorastrigin(x, scal, skewfac, skewstart, amplitude) % by default multi-modal about between -30 and 30 if nargin < 5 || isempty(amplitude) amplitude = 40; end if nargin < 4 || isempty(skewstart) skewstart = 0; end if nargin < 3 || isempty(skewfac) skewfac = 1; end if nargin < 2 || isempty(scal) scal = 1; end N = size(x,1); scale = 1; if N > 1 scale=scal.^((0:N-1)'/(N-1)); end % simple version: % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); % skew version: y = repmat(scale, 1, size(x,2)) .* x; idx = find(x > skewstart); if ~isempty(idx) y(idx) = skewfac*y(idx); end f = amplitude * (0*N-prod(cos((2*pi)^0*y),1)) + 0.05 * sum(y.^2,1) ... + randn(1,1); function f=frastrigin(x, scal, skewfac, skewstart, amplitude) % by default multi-modal about between -30 and 30 if nargin < 5 || isempty(amplitude) amplitude = 10; end if nargin < 4 || isempty(skewstart) skewstart = 0; end if nargin < 3 || isempty(skewfac) skewfac = 1; end if nargin < 2 || isempty(scal) scal = 1; end N = size(x,1); scale = 1; if N > 1 scale=scal.^((0:N-1)'/(N-1)); end % simple version: % f = amplitude*(N - sum(cos(2*pi*(scale.*x)))) + sum((scale.*x).^2); % skew version: y = repmat(scale, 1, size(x,2)) .* x; idx = find(x > skewstart); % idx = intersect(idx, 2:2:10); if ~isempty(idx) y(idx) = skewfac*y(idx); end f = amplitude * (N-sum(cos(2*pi*y),1)) + sum(y.^2,1); function f=frastriginmax(x) N = size(x,1); f = (N/20)*807.06580387678 - (10 * (N-sum(cos(2*pi*x),1)) + sum(x.^2,1)); f(any(abs(x) > 5.12)) = 1e2*N; function f = fschaffer(x) % -100..100 N = size(x,1); s = x(1:N-1,:).^2 + x(2:N,:).^2; f = sum(s.^0.25 .* (sin(50*s.^0.1).^2+1), 1); function f=fschwefelmult(x) % -500..500 % N = size(x,1); f = - sum(x.*sin(sqrt(abs(x))), 1); f = 418.9829*N - 1.27275661e-5*N - sum(x.*sin(sqrt(abs(x))), 1); % penalty term f = f + 1e4*sum((abs(x)>500) .* (abs(x)-500).^2, 1); function f=ftwomax(x) % Boundaries at +/-5 N = size(x,1); f = -abs(sum(x)) + 5*N; function f=ftwomaxtwo(x) % Boundaries at +/-10 N = size(x,1); f = abs(sum(x)); if f > 30 f = f - 30; end f = -f; function f=frand(x) f=1./(1-rand(1, size(x,2))) - 1; % CHANGES % 12/04/28: (3.61) stopIter is relative to countiter after resume (thanks to Tom Holden) % 12/04/28: (3.61) some syncing from 3.32.integer branch (cmean introduced, ...) % 12/02/19: "future" setting of ccum, correcting for large mueff, is default now % 11/11/15: bug-fix: max value for ccovmu_sep setting corrected % 10/11/11: (3.52.beta) boundary handling: replace max with min in change % rate formula. Active CMA: check of pos.def. improved. % Plotting: value of lambda appears in the title. % 10/04/03: (3.51.beta) active CMA cleaned up. Equal fitness detection % looks into history now. % 10/03/08: (3.50.beta) "active CMA" revised and bug-fix of ambiguous % option Noise.alpha -> Noise.alphasigma. % 09/10/12: (3.40.beta) a slightly modified version of "active CMA", % that is a negative covariance matrix update, use option % CMA.active. In 10;30;90-D the gain on ftablet is a factor % of 1.6;2.5;4.4 (the scaling improves by sqrt(N)). On % Rosenbrock the gain is about 25%. On sharp ridge the % behavior is improved. Cigar is unchanged. % 09/08/10: local plotcmaesdat remains in backround % 09/08/10: bug-fix in time management for data writing, logtime was not % considered properly (usually not at all). % 09/07/05: V3.24: stagnation termination added % 08/09/27: V3.23: momentum alignment is out-commented and de-preciated % 08/09/25: V3.22: re-alignment of sigma and C was buggy % 08/07/15: V3.20, CMA-parameters are options now. ccov and mucov were replaced % by ccov1 \approx ccov/mucov and ccovmu \approx (1-1/mucov)*ccov % 08/06/30: file name xrecent was change to xrecentbest (compatible with other % versions) % 08/06/29: time stamp added to output files % 08/06/28: bug fixed with resume option, commentary did not work % 08/06/28: V3.10, uncertainty (noise) handling added (re-implemented), according % to reference "A Method for Handling Uncertainty..." from below. % 08/06/28: bug fix: file xrecent was empty % 08/06/01: diagonalonly clean up. >1 means some iterations. % 08/05/05: output is written to file preventing an increasing data % array and ease long runs. % 08/03/27: DiagonalOnly<0 learns for -DiagonalOnly iterations only the % diagonal with a larger learning rate. % 08/03 (2.60): option DiagonalOnly>=1 invokes a time- and space-linear % variant with only diagonal elements of the covariance matrix % updating. This can be useful for large dimensions, say > 100. % 08/02: diag(weights) * ... replaced with repmat(weights,1,N) .* ... % in C update, implies O(mu*N^2) instead of O(mu^2*N + mu*N^2). % 07/09: tolhistfun as termination criterion added, "<" changed to % "<=" also for TolFun to allow for stopping on zero difference. % Name tolfunhist clashes with option tolfun. % 07/07: hsig threshold made slighly smaller for large dimension, % useful for lambda < lambda_default. % 07/06: boundary handling: scaling in the boundary handling % is omitted now, see bnd.flgscale. This seems not to % have a big impact. Using the scaling is worse on rotated % functions, but better on separable ones. % 07/05: boundary handling: weight i is not incremented anymore % if xmean(i) moves towards the feasible space. Increment % factor changed to 1.2 instead of 1.1. % 07/05: boundary handling code simplified not changing the algorithm % 07/04: bug removed for saving in octave % 06/11/10: more testing of outcome of eig, fixed max(D) to max(diag(D)) % 06/10/21: conclusive final bestever assignment in the end % 06/10/21: restart and incpopsize option implemented for restarts % with increasing population size, version 2.50. % 06/09/16: output argument bestever inserted again for convenience and % backward compatibility % 06/08: output argument out and struct out reorganized. % 06/01: Possible parallel evaluation included as option EvalParallel % 05/11: Compatibility to octave implemented, package octave-forge % is needed. % 05/09: Raise of figure and waiting for first plots improved % 05/01: Function coordinatesystem cleaned up. % 05/01: Function prctile, which requires the statistics toolbox, % replaced by myprctile. % 05/01: Option warnonequalfunctionvalues included. % 04/12: Decrease of sigma removed. Problems on fsectorsphere can % be addressed better by adding search space boundaries. % 04/12: Boundary handling simpyfied. % 04/12: Bug when stopping criteria tolx or tolupx are vectors. % 04/11: Three input parameters are obligatory now. % 04/11: Bug in boundary handling removed: Boundary weights can decrease now. % 04/11: Normalization for boundary weights scale changed. % 04/11: VerboseModulo option bug removed. Documentation improved. % 04/11: Condition for increasing boundary weights changed. % 04/10: Decrease of sigma when fitness is getting consistenly % worse. Addresses the problems appearing on fsectorsphere for % large population size. % 04/10: VerboseModulo option included. % 04/10: Bug for condition for increasing boundary weights removed. % 04/07: tolx depends on initial sigma to achieve scale invariance % for this stopping criterion. % 04/06: Objective function value NaN is not counted as function % evaluation and invokes resampling of the search point. % 04/06: Error handling for eigenvalue beeing zero (never happens % with default parameter setting) % 04/05: damps further tuned for large mueff % o Details for stall of pc-adaptation added (variable hsig % introduced). % 04/05: Bug in boundary handling removed: A large initial SIGMA was % corrected not until *after* the first iteration, which could % lead to a complete failure. % 04/05: Call of function range (works with stats toolbox only) % changed to myrange. % 04/04: Parameter cs depends on mueff now and damps \propto sqrt(mueff) % instead of \propto mueff. % o Initial stall to adapt C (flginiphase) is removed and % adaptation of pc is stalled for large norm(ps) instead. % o Returned default options include documentation. % o Resume part reorganized. % 04/03: Stopflag becomes cell-array. % --------------------------------------------------------------- % CMA-ES: Evolution Strategy with Covariance Matrix Adaptation for % nonlinear function minimization. To be used under the terms of the % GNU General Public License (http://www.gnu.org/copyleft/gpl.html). % Author (copyright): Nikolaus Hansen, 2001-2008. % e-mail: nikolaus.hansen AT inria.fr % URL:http://www.bionik.tu-berlin.de/user/niko % References: See below. % --------------------------------------------------------------- % % GENERAL PURPOSE: The CMA-ES (Evolution Strategy with Covariance % Matrix Adaptation) is a robust search method which should be % applied, if derivative based methods, e.g. quasi-Newton BFGS or % conjucate gradient, (supposably) fail due to a rugged search % landscape (e.g. noise, local optima, outlier, etc.). On smooth % landscapes CMA-ES is roughly ten times slower than BFGS. For up to % N=10 variables even the simplex direct search method (Nelder & Mead) % is often faster, but far less robust than CMA-ES. To see the % advantage of the CMA, it will usually take at least 30*N and up to % 300*N function evaluations, where N is the search problem dimension. % On considerably hard problems the complete search (a single run) is % expected to take at least 30*N^2 and up to 300*N^2 function % evaluations. % % SOME MORE COMMENTS: % The adaptation of the covariance matrix (e.g. by the CMA) is % equivalent to a general linear transformation of the problem % coding. Nevertheless every problem specific knowlegde about the best % linear transformation should be exploited before starting the % search. That is, an appropriate a priori transformation should be % applied to the problem. This also makes the identity matrix as % initial covariance matrix the best choice. % % The strategy parameter lambda (population size, opts.PopSize) is the % preferred strategy parameter to play with. If results with the % default strategy are not satisfactory, increase the population % size. (Remark that the crucial parameter mu (opts.ParentNumber) is % increased proportionally to lambda). This will improve the % strategies capability of handling noise and local minima. We % recomment successively increasing lambda by a factor of about three, % starting with initial values between 5 and 20. Casually, population % sizes even beyond 1000+100*N can be sensible. % % % --------------------------------------------------------------- %%% REFERENCES % % The equation numbers refer to % Hansen, N. and S. Kern (2004). Evaluating the CMA Evolution % Strategy on Multimodal Test Functions. Eighth International % Conference on Parallel Problem Solving from Nature PPSN VIII, % Proceedings, pp. 282-291, Berlin: Springer. % (http://www.bionik.tu-berlin.de/user/niko/ppsn2004hansenkern.pdf) % % Further references: % Hansen, N. and A. Ostermeier (2001). Completely Derandomized % Self-Adaptation in Evolution Strategies. Evolutionary Computation, % 9(2), pp. 159-195. % (http://www.bionik.tu-berlin.de/user/niko/cmaartic.pdf). % % Hansen, N., S.D. Mueller and P. Koumoutsakos (2003). Reducing the % Time Complexity of the Derandomized Evolution Strategy with % Covariance Matrix Adaptation (CMA-ES). Evolutionary Computation, % 11(1). (http://mitpress.mit.edu/journals/pdf/evco_11_1_1_0.pdf). % % Ros, R. and N. Hansen (2008). A Simple Modification in CMA-ES % Achieving Linear Time and Space Complexity. To appear in Tenth % International Conference on Parallel Problem Solving from Nature % PPSN X, Proceedings, Berlin: Springer. % % Hansen, N., A.S.P. Niederberger, L. Guzzella and P. Koumoutsakos % (2009?). A Method for Handling Uncertainty in Evolutionary % Optimization with an Application to Feedback Control of % Combustion. To appear in IEEE Transactions on Evolutionary % Computation.
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
viewFollowModel.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/viewFollowModel.m
353
utf_8
51b26c7830cbc39343278139ee6c06d3
% Function that shifts view window to follow the hip of the model % ---------------------------------------- function viewFollowModel(u, ViewWin) % Check if an object is out of bounds % -------------------------- % get hip x pos hipX = u(13); % shift to align with hip set(gca, 'XLim', [hipX - ViewWin/2, hipX + ViewWin/2]);
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
updateSphereObjects.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/updateSphereObjects.m
2,108
utf_8
b35e83e59c33ce62e45950e85a4be938
% --------------------- % Update Sphere Objects % --------------------- function updateSphereObjects( SphereObjects, u, x, intactFlag) % extract sphere objects L_HJ_Obj = SphereObjects(1); L_BallObj = SphereObjects(2); L_HeelObj = SphereObjects(3); L_AJ_Obj = SphereObjects(4); L_KJ_Obj = SphereObjects(5); R_HJ_Obj = SphereObjects(6); if(intactFlag) R_BallObj = SphereObjects( 7); R_HeelObj = SphereObjects( 8); R_AJ_Obj = SphereObjects( 9); R_KJ_Obj = SphereObjects(10); end % shift spheres to their new position set(L_HJ_Obj, 'XData', get(L_HJ_Obj, 'XData') + u( 3) - x( 3), ... 'ZData', get(L_HJ_Obj, 'ZData') + u( 4) - x( 4)) set(L_KJ_Obj, 'XData', get(L_KJ_Obj, 'XData') + u( 5) - x( 5), ... 'ZData', get(L_KJ_Obj, 'ZData') + u( 6) - x( 6)) set(L_AJ_Obj, 'XData', get(L_AJ_Obj, 'XData') + u( 7) - x( 7), ... 'ZData', get(L_AJ_Obj, 'ZData') + u( 8) - x( 8)) set(L_BallObj, 'XData', get(L_BallObj, 'XData') + u( 9) - x( 9), ... 'ZData', get(L_BallObj, 'ZData') + u(10) - x(10)) set(L_HeelObj, 'XData', get(L_HeelObj, 'XData') + u(11) - x(11), ... 'ZData', get(L_HeelObj, 'ZData') + u(12) - x(12)) set(R_HJ_Obj, 'XData', get(R_HJ_Obj, 'XData') + u(13) - x(13), ... 'ZData', get(R_HJ_Obj, 'ZData') + u(14) - x(14)) if(intactFlag) set(R_KJ_Obj, 'XData', get(R_KJ_Obj, 'XData') + u(15) - x(15), ... 'ZData', get(R_KJ_Obj, 'ZData') + u(16) - x(16)) set(R_AJ_Obj, 'XData', get(R_AJ_Obj, 'XData') + u(17) - x(17), ... 'ZData', get(R_AJ_Obj, 'ZData') + u(18) - x(18)) set(R_BallObj, 'XData', get(R_BallObj, 'XData') + u(19) - x(19), ... 'ZData', get(R_BallObj, 'ZData') + u(20) - x(20)) set(R_HeelObj, 'XData', get(R_HeelObj, 'XData') + u(21) - x(21), ... 'ZData', get(R_HeelObj, 'ZData') + u(22) - x(22)) end end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
moveViewWindow.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/moveViewWindow.m
2,334
utf_8
699168442374fe41171b7192de971a8b
% Function that shifts view window and % and the light sources if model is out % of view % ---------------------------------------- function moveViewWindow( uInt, uRef, uImp, ViewWin, TolFrac, curFrame, frameFocus1, frameFocus2) % Check if an object is out of bounds % -------------------------- % get axis limits XLimits = get(gca, 'XLim'); if curFrame < frameFocus1 % get min and max xpos of object minX = min([uRef(1:2:17), uImp(1:2:17), uInt(1:2:end)]); maxX = max([uRef(1:2:17), uImp(1:2:17), uInt(1:2:end)]); % shift if object past right border if XLimits(2) < ( maxX + ViewWin*TolFrac ) % initiate shift to the right set(gca, 'XLim', [maxX - ViewWin*TolFrac, maxX + ViewWin*(1-TolFrac)]); end % zoom out if object pastleft border XLimits = get(gca, 'XLim'); if XLimits(1) > ( minX - ViewWin*TolFrac ) % initiate zoom to the left set(gca, 'XLim', [minX-ViewWin*TolFrac, XLimits(2)]); end elseif curFrame > frameFocus2 % get min and max xpos of object minX = min([uInt(1:2:end)]); maxX = max([uInt(1:2:end)]); % shift if object past right border if XLimits(2) < ( maxX + ViewWin*TolFrac ) % initiate shift to the right set(gca, 'XLim', [maxX - ViewWin*TolFrac, maxX + ViewWin*(1-TolFrac)]); end % zoom out if object pastleft border XLimits = get(gca, 'XLim'); if XLimits(1) > ( minX - ViewWin*TolFrac ) % initiate zoom to the left set(gca, 'XLim', [minX-ViewWin*TolFrac, XLimits(2)]); end else % get min and max xpos of object minX = min([uRef(1:2:17), uInt(1:2:end)]); maxX = max([uRef(1:2:17), uInt(1:2:end)]); % shift if object past right border if XLimits(2) < ( maxX + ViewWin*TolFrac ) % initiate shift to the right set(gca, 'XLim', [maxX - ViewWin*TolFrac, maxX + ViewWin*(1-TolFrac)]); end % zoom out if object pastleft border XLimits = get(gca, 'XLim'); if XLimits(1) > ( minX - ViewWin*TolFrac ) % initiate zoom to the left set(gca, 'XLim', [minX-ViewWin*TolFrac, XLimits(2)]); end end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
updateConeObjects.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/updateConeObjects.m
2,396
utf_8
31d366c061992c364b93420652b82f7a
% ------------------- % Update Cone Objects % ------------------- function updateConeObjects( ConeObjects, u, x, t, intactFlag) % extract cone objects HAT_ConeObj = ConeObjects(1); L_ThighObj = ConeObjects(2); L_ShankObj = ConeObjects(3); L_FootObj = ConeObjects(4); R_ThighObj = ConeObjects(5); if(intactFlag) R_ShankObj = ConeObjects(6); R_FootObj = ConeObjects(7); end % at the initial time step t=0, scale cone objects to their actual length if t==0 % set HAT length HAT_Length = 2*sqrt( (u(1)-u(3))^2 + (u(2)-u(4))^2 ); set(HAT_ConeObj, 'ZData', get(HAT_ConeObj, 'ZData') * HAT_Length); % set left thigh length L_ThighLength = sqrt( (u(3)-u(5))^2 + (u(4)-u(6))^2 ); set(L_ThighObj, 'ZData', get(L_ThighObj, 'ZData') * L_ThighLength); % set left shank length L_ShankLength = sqrt( (u(5)-u(7))^2 + (u(6)-u(8))^2 ); set(L_ShankObj, 'ZData', get(L_ShankObj, 'ZData') * L_ShankLength); % set left foot length L_FootLength = sqrt( (u(9)-u(11))^2 + (u(10)-u(12))^2 ); set(L_FootObj, 'ZData', get(L_FootObj, 'ZData') * L_FootLength); % set right thigh length R_ThighLength = sqrt( (u(13)-u(15))^2 + (u(14)-u(16))^2 ); set(R_ThighObj, 'ZData', get(R_ThighObj, 'ZData') * R_ThighLength); if(intactFlag) % set right shank length R_ShankLength = sqrt( (u(15)-u(17))^2 + (u(16)-u(18))^2 ); set(R_ShankObj, 'ZData', get(R_ShankObj, 'ZData') * R_ShankLength); % set right foot length R_FootLength = sqrt( (u(19)-u(21))^2 + (u(20)-u(22))^2 ); set(R_FootObj, 'ZData', get(R_FootObj, 'ZData') * R_FootLength); end end % rotate and shift cones to their new angles and positions rotTransObj( HAT_ConeObj, u(3:4), u(1:2), x(3:4), x(1:2)) rotTransObj( L_ThighObj, u(5:6), u(3:4), x(5:6), x(3:4)) rotTransObj( L_ShankObj, u(7:8), u(5:6), x(7:8), x(5:6)) rotTransObj( L_FootObj, u(11:12), u(9:10), x(11:12), x(9:10)) rotTransObj( R_ThighObj, u(15:16), u(13:14), x(15:16), x(13:14)) if(intactFlag) rotTransObj( R_ShankObj, u(17:18), u(15:16), x(17:18), x(15:16)) rotTransObj( R_FootObj, u(21:22), u(19:20), x(21:22), x(19:20)) end end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
checkViewWin.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/checkViewWin.m
2,270
utf_8
831e6ecccb0f9ccae4eb72b673c7731f
% Function that shifts view window and % and the light sources if model is out % of view % ---------------------------------------- function ViewShiftParams = checkViewWin( u, t, ViewWin, TolFrac, ViewShiftParams, tShiftTot) % Check For Shift Initiation % -------------------------- if ViewShiftParams(1)==0 % get axis limits XLimits = get(gca, 'XLim'); % get min and max xpos of object minX = u(1); maxX = u(1); % check right border if XLimits(2) < ( maxX + ViewWin*TolFrac ) % initiate shift to the right StartPos = XLimits(1); dShiftTot = (minX - ViewWin*TolFrac) - StartPos; ViewShiftParams = [1 t StartPos dShiftTot]; set(gca, 'XLim', [minX - ViewWin*TolFrac minX + ViewWin*(1-TolFrac)]); % check left border elseif XLimits(1) > ( minX - ViewWin*TolFrac ) % initiate shift to the left StartPos = XLimits(1); dShiftTot = StartPos - (minX + ViewWin*TolFrac - ViewWin); ViewShiftParams = [-1 t StartPos dShiftTot]; set(gca, 'XLim', [maxX - ViewWin*(1-TolFrac) maxX + ViewWin*TolFrac]); end end % Shift View Window % ----------------- if ViewShiftParams(1)~=0 % get current shift time tShift = t - ViewShiftParams(2); % check for end of shift phase if tShift > tShiftTot % reset view window shift parameters ViewShiftParams(1) = 0; else ShiftDir = ViewShiftParams(1); % get shift direction dShiftTot = ViewShiftParams(4); % get shift distance StartPos = ViewShiftParams(3); % get start position % get new distance to former axis limit if tShiftTot == 0 xLimShift = dShiftTot; else if tShift <= tShiftTot/2 xLimShift = 2*dShiftTot * (tShift/tShiftTot)^2; else xLimShift = dShiftTot-2*dShiftTot*((tShiftTot-tShift)/tShiftTot)^2; end end % shift axis limits set(gca, 'XLim', StartPos + ShiftDir*xLimShift+[0 ViewWin]); end end end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
createProstheticObjects.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/createProstheticObjects.m
1,159
utf_8
e21c0b190710500412169a03987106ae
% ----------------- % Create Prosthetic % ----------------- function prostheticObjects = createProstheticObjects(prosKneeFile, ... prosShankFile, prosFootFile, yShiftGlobal) if nargin == 0 yShiftGlobal = 0; prosKneeFile = '../Prosthesis/kneeStatorForAnim.STL'; prosShankFile = '../Prosthesis/shankForAnim.STL'; prosFootFile = '../Prosthesis/footForAnim.STL'; end [vProsKnee, fProsKnee] = stlread(prosKneeFile); vProsKnee(:,2) = vProsKnee(:,2) - 0.1 + yShiftGlobal; [vProsShank, fProsShank] = stlread(prosShankFile); vProsShank(:,2) = vProsShank(:,2) - 0.1 + yShiftGlobal; [vProsFoot, fProsFoot] = stlread(prosFootFile); vProsFoot(:,2) = vProsFoot(:,2) - 0.1 + yShiftGlobal; prosColor = [0.5, 0.5, 0.5]; prosKneePatch = patch('Faces',fProsKnee,'Vertices',vProsKnee); prosShankPatch = patch('Faces',fProsShank,'Vertices',vProsShank); prosFootPatch = patch('Faces',fProsFoot,'Vertices',vProsFoot); prostheticObjects = [prosKneePatch, prosShankPatch, prosFootPatch]; set(prostheticObjects,'Visible','off','FaceColor',prosColor,'EdgeColor','none'); end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
updateProstheticObjects.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/updateProstheticObjects.m
2,186
utf_8
73a0c737b168a0bdd6f340abdadc5e31
% ------------------------- % Update Prosthetic Objects % ------------------------- function updateProstheticObjects(prostheticObjects, u, x) %extract objects prosKneeObj = prostheticObjects(1); prosShankObj = prostheticObjects(2); prosFootObj = prostheticObjects(3); kneeVertices = get(prosKneeObj, 'Vertices'); shankVertices = get(prosShankObj, 'Vertices'); footVertices = get(prosFootObj, 'Vertices'); %move objects back to origin numKneeVertices = size(kneeVertices,1); transKneeOld = repmat([x(15), 0, x(16)], numKneeVertices, 1); kneeVertices = kneeVertices - transKneeOld; numShankVertices = size(shankVertices,1); transShankOld = repmat([x(15), 0, x(16)], numShankVertices, 1); shankVertices = shankVertices - transShankOld; numFootVertices = size(footVertices,1); transFootOld = repmat([x(17), 0, x(18)], numFootVertices, 1); footVertices = footVertices - transFootOld; %rotate object vertices RotKnee = [ cos(u(19) - x(19)), 0, sin(u(19) - x(19)); 0, 1, 0; -sin(u(19) - x(19)), 0, cos(u(19) - x(19))]; kneeVertices = (RotKnee*(kneeVertices'))'; RotShank = [ cos(u(20) - x(20)), 0, sin(u(20) - x(20)); 0, 1, 0; -sin(u(20) - x(20)), 0, cos(u(20) - x(20))]; shankVertices = (RotShank*(shankVertices'))'; RotFoot = [ cos(u(21) - x(21)), 0, sin(u(21) - x(21)); 0, 1, 0; -sin(u(21) - x(21)), 0, cos(u(21) - x(21))]; footVertices = (RotFoot*(footVertices'))'; %translate obj vertices transKneeNew = repmat([u(15), 0, u(16)], numKneeVertices, 1); kneeVertices = kneeVertices + transKneeNew; transShankNew = repmat([u(15), 0, u(16)], numShankVertices, 1); shankVertices = shankVertices + transShankNew; transFootNew = repmat([u(17), 0, u(18)], numFootVertices, 1); footVertices = footVertices + transFootNew; %update object vertices set(prosKneeObj, 'Vertices', kneeVertices); set(prosShankObj, 'Vertices', shankVertices); set(prosFootObj, 'Vertices', footVertices); end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
rotTransObj.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/rotTransObj.m
778
utf_8
f12a437adeb1352a04364476971416dd
% --------------------------- % Rotate and Translate Ojects % --------------------------- function rotTransObj( Object, LowXY, TopXY, LowXYold, TopXYold ) % calculate change in rotation angle compared to previous angle dalpha = atan2( LowXY(1)- TopXY(1), TopXY(2)- LowXY(2)) ... -atan2(LowXYold(1)-TopXYold(1), TopXYold(2)-LowXYold(2)); % get actual x and z data and shift it back to zero xAct = get(Object, 'XData')-LowXYold(1); zAct = get(Object, 'ZData')-LowXYold(2); % rotate and shift x and z data to new angle and position xNew = cos(dalpha)*xAct - sin(dalpha)*zAct + LowXY(1); zNew = sin(dalpha)*xAct + cos(dalpha)*zAct + LowXY(2); % update cone object set(Object, 'XData', xNew, 'ZData', zNew); end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
createWalkwayObject.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/createWalkwayObject.m
1,640
utf_8
6840f7f3828b66d080c8e7e3231330c4
% -------------- % Create Walkway % -------------- function createWalkwayObject(WayCol, rCP, width) %set nPlates <= 0 to load walkway from file. Else, Walkway will be flat and of length specified in meters if nargin ==2 width = 1; end ground = load('groundHeight.mat'); zPts = ground.groundZ; % - rCP/2; xPts = ground.groundX; numPts = length(zPts); % initialize vertex and face matrices floorVertices = nan(2*numPts,3); %Vertices floorFaces = nan(numPts-1,4); %Faces sideVertices = nan(2*numPts,3); %SideVertices sideFaces = nan(numPts-1,4); %SideFaces % loop through plates for pIdx = 1:numPts % add ground vertices floorVertices((2*pIdx-1):(2*pIdx),:) = [xPts(pIdx), -width/2, zPts(pIdx); ... xPts(pIdx), width/2, zPts(pIdx)]; %add side walls sideVertices((2*pIdx-1):(2*pIdx),:) = [xPts(pIdx), -width/2, zPts(pIdx); ... xPts(pIdx), -width/2, -20]; % add faces lastVertex = 2*pIdx; if pIdx~=1 floorFaces(pIdx-1,:) = [lastVertex-3, lastVertex-2, lastVertex, lastVertex-1]; sideFaces(pIdx-1,:) = [lastVertex-3 lastVertex-2 lastVertex lastVertex-1]; end end % create walkway patch patch('Vertices', floorVertices, 'Faces', floorFaces, 'FaceColor', WayCol, ... 'EdgeColor', [0.5 0.5 0.5], 'LineWidth', 1); %{ patch('Vertices', sideVertices, 'Faces', sideFaces, 'FaceColor', WayCol, ... 'EdgeColor', [0.5 0.5 0.5], 'LineWidth', 1); %} end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
animInit.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/animInit.m
1,343
utf_8
85e28e9f2b5f6e7a75be053444a6aecf
% --------------------------- % Initialize Animation Figure % --------------------------- function animInit(namestr) % ----------------- % Initialize Figure % ----------------- % check whether figure exists already figExists = size(findobj('Tag',namestr),1) ~= 0; % if not, initialize figure if ~figExists % define figure element figure( ... 'Tag', namestr, ... 'Name', namestr, ... 'NumberTitle', 'off', ... 'BackingStore', 'off', ... 'MenuBar', 'default', ... 'Color', [1 1 1], ... 'Position', [20 20 1920 1080], ... 'Renderer', 'OpenGL'); % define axes element axes('Position', [0 0 1 1], 'FontSize', 8); end % ---------------------------------- % Reset Figure to Simulation Default % ---------------------------------- % reset axes to default properties cla reset; % change some properties set(gca, 'SortMethod', 'depth', ... 'Color', [1 1 1], ... 'XColor', [0 0 0], ... 'YColor', [0 0 0]); axis image; hold on; end
github
nthatte/Neuromuscular-Transfemoral-Prosthesis-Model-master
createWalkwayObjectOld.m
.m
Neuromuscular-Transfemoral-Prosthesis-Model-master/Animation/createWalkwayObjectOld.m
2,364
utf_8
595a830c4e5c8a568ce88665c6d018e6
% -------------- % Create Walkway % -------------- function zPlates = createWalkwayObject(WayCol, rCP, width) %set nPlates <= 0 to load walkway from file. Else, Walkway will be flat and of length specified in meters if nargin ==2 width = 1; end zPlates = load('groundHeight.mat'); zPlates = zPlates.groundy - rCP/2; nPlates = length(zPlates); % initialize vertex and face matrices VM = []; %Vertices FM = []; %Faces sideVertices = []; %SideVertices sideFaces = []; %SideFaces PlateLength = 1; %[m] % loop through plates for pIdx = 1:nPlates % add four plate vertices VM = [ VM; ... (pIdx-1)*PlateLength -width/2 zPlates(pIdx); ... (pIdx-1)*PlateLength width/2 zPlates(pIdx); ... pIdx*PlateLength -width/2 zPlates(pIdx); ... pIdx*PlateLength width/2 zPlates(pIdx)]; % add two faces (vertical from previous plate to new plate % and horizontal for the new plate) LastVertex = 4*pIdx; if pIdx==1 FM = [LastVertex-3 LastVertex-2 LastVertex LastVertex-1]; else FM = [ FM; ... LastVertex-5 LastVertex-4 LastVertex-2 LastVertex-3; ... LastVertex-3 LastVertex-2 LastVertex LastVertex-1]; end end [xd, zd] = stairs(0:(nPlates-1),zPlates); xd(end+1) = 100; zd(end+1) = zd(end); yd = -width/2*ones(size(xd)); for i = 1:nPlates sideVertices = [ sideVertices; ... xd(2*i-1), -width/2, zd(2*i-1); ... xd(2*i), -width/2, zd(2*i); ... xd(2*i-1), -width/2, -20; ... xd(2*i), -width/2, -20]; ... LastVertex = 4*i; sideFaces = [ sideFaces; ... LastVertex-3 LastVertex-2 LastVertex LastVertex-1]; end % create walkway patch patch('Vertices', VM, 'Faces', FM, 'FaceColor', WayCol, ... 'EdgeColor', [0.5 0.5 0.5], 'LineWidth', 1); patch('Vertices', sideVertices, 'Faces', sideFaces, 'FaceColor', WayCol, ... 'EdgeColor', [0.5 0.5 0.5], 'LineWidth', 1); end
github
albanie/wider2pascal-master
wider2pascal.m
.m
wider2pascal-master/wider2pascal.m
4,620
utf_8
37fd191fc3bc24bc8847b3eebc64bd05
function wider2pascal(widerRootDir, widerDevkitDir) %WIDER2PASCAL converts the WIDER database into Pascal format % WIDER2PASCAL(widerDir, targetDir) generates a folder % structure mimicking the Pascal VOC 2007 devkit format % containing faces from the WIDER database % % `widerRootDir` is a path to the WIDER dataset (contains % subfolders called WIDER_train, WIDER_val, WIDER_test % and wider_face_split % % `widerDevkitDir` is a path to where the new VOCdevkit-style % folder structure will be generated % % The generated folder structure contains only the subset of % files required for bounding box object detection: % % widerDekitDir / % WIDER / % Annotations / % JPEGImages / % ImageSets / % % % Author: Samuel Albanie % create the target subdirectories annotationsDir = fullfile(widerDevkitDir, 'WIDER', 'Annotations'); jpegImagesDir = fullfile(widerDevkitDir, 'WIDER', 'JPEGImages'); imageSetsDir = fullfile(widerDevkitDir, 'WIDER', 'ImageSets'); % the data structures are identical for the training and % validation sets (the annotations for the test set are % not publicly available and so are not used here generateAnnotations(widerRootDir, annotationsDir, 'train'); generateAnnotations(widerRootDir, annotationsDir, 'val'); copyImages(widerRootDir, jpegImagesDir, 'train'); copyImages(widerRootDir, jpegImagesDir, 'val'); generateImageSets(widerRootDir, imageSetsDir, 'train'); generateImageSets(widerRootDir, imageSetsDir, 'val'); %------------------------------------------------------------------- function generateAnnotations(widerRootDir, annotationsDir, partition) %------------------------------------------------------------------ % generate the Pascal VOC-style xml annotation files % for the given partition % make sure that target directory exists if ~exist(annotationsDir, 'dir') mkdir(annotationsDir); end % load data for partition partitionData = load(fullfile(widerRootDir, ... 'wider_face_split', ... sprintf('wider_face_%s.mat', ... partition))); % loop over WIDER events for i = 1: numel(partitionData.event_list) % extract images and bounding box per event files = partitionData.file_list{i}; bboxList = partitionData.face_bbx_list{i}; % loop over the images associated with each event for j = 1:numel(files) imgName = strcat(files{j}, '.jpg'); imgDir = fullfile(widerRootDir, sprintf('WIDER_%s', partition), 'images', partitionData.event_list{i}, strcat(files{j}, '.jpg')); annotationFileName = fullfile(annotationsDir, ... strcat(files{j}, '.xml')); generatePascalXML(imgDir, imgName, bboxList{j}, annotationFileName); end end clc %------------------------------------------------------------------- function copyImages(widerRootDir, jpegImagesDir, partition) %------------------------------------------------------------------ % Copy the files from seperate WIDER "events" into a single % directory, Pascal-style. % make sure that target directory exists if ~exist(jpegImagesDir, 'dir') mkdir(jpegImagesDir); end % load data for partition partitionData = load(fullfile(widerRootDir, ... 'wider_face_split', ... sprintf('wider_face_%s.mat', ... partition))); % loop over WIDER events for i = 1: numel(partitionData.event_list) imgPaths = cellfun(@(x) fullfile(widerRootDir, ... sprintf('WIDER_%s', partition), ... 'images', ... partitionData.event_list{i}, ... strcat(x, '.jpg')), ... partitionData.file_list{i}, ... 'UniformOutput', false); % copy the images to the target folder for j = 1:numel(imgPaths) copyfile(imgPaths{j}, jpegImagesDir); end end clc %------------------------------------------------------------------- function generateImageSets(widerRootDir, imageSetsDir, partition) %------------------------------------------------------------------ % Write the names of the images in the training and validation % sets to files named 'train.txt' and 'val.txt' % make sure that target directory exists if ~exist(imageSetsDir, 'dir') mkdir(imageSetsDir); end % load data for partition partitionData = load(fullfile(widerRootDir, ... 'wider_face_split', ... sprintf('wider_face_%s.mat', ... partition))); % write to file targetPath = fullfile(imageSetsDir, sprintf('%s.txt', partition)); files = vertcat(partitionData.file_list{:}); fileID = fopen(targetPath, 'w'); for i = 1:numel(files) fprintf(fileID, '%s\n', files{i}); end fclose(fileID); clc
github
edeno/Jadhav-2016-Data-Analysis-master
get_marks.m
.m
Jadhav-2016-Data-Analysis-master/Xinyi-ripple-decoding/get_marks.m
802
utf_8
9dd2914c9c1d6ed7afd1243e31d4dc90
function [mark_spike_times, marks] = get_marks(animal, day, tetrode_number) num_tetrodes = length(tetrode_number); mark_spike_times = cell(num_tetrodes, 1); marks = cell(num_tetrodes, 1); for tetrode_ind = 1:num_tetrodes, [mark_spike_times{tetrode_ind}, marks{tetrode_ind}] = get_mark_data_by_tetrode(animal, day, tetrode_number(tetrode_ind)); end end function [mark_spike_times, marks] = get_mark_data_by_tetrode(animal, day, tetrode_number) mark_data_file = load(get_mark_filename('bond', day, tetrode_number)); params = mark_data_file.filedata.params; mark_spike_times = params(:, 1); marks = params(:, 2:5); % tetrode wire maxes end function [filename] = get_mark_filename(animal, day, tetrode_number) filename = sprintf('bond_data/%s%02d-%02d_params.mat', animal, day, tetrode_number); end
github
edeno/Jadhav-2016-Data-Analysis-master
condition_empirical_movement_transition_matrix_on_state.m
.m
Jadhav-2016-Data-Analysis-master/Xinyi-ripple-decoding/condition_empirical_movement_transition_matrix_on_state.m
1,593
utf_8
ab2ac69b782c7b3955c01a55c6b4a285
function [empirical_movement_transition_matrix] = condition_empirical_movement_transition_matrix_on_state(linear_distance_bins, linear_distance, state_index) %% calculate emipirical movement transition matrix, then Gaussian smoothed num_linear_distance_bins = length(linear_distance_bins); stateM = zeros(num_linear_distance_bins); [~, state_bin] = histc(linear_distance(state_index), linear_distance_bins); state_disM = [state_bin(1:end-1) state_bin(2:end)]; for bin_ind = 1:num_linear_distance_bins sp0 = state_disM(state_disM(:, 1) == bin_ind, 2); %by departure x_k-1 (by column); sp0 is the departuring x_(k-1); if ~isempty(sp0) stateM(:, bin_ind) = histc(sp0, linspace(1, num_linear_distance_bins, num_linear_distance_bins)) ./ size(sp0, 1); else stateM(:, bin_ind) = zeros(1, num_linear_distance_bins); end end %%%if too many zeros: for bin_ind = 1:num_linear_distance_bins if sum(stateM(:, bin_ind)) == 0 stateM(:, bin_ind) = 1 / num_linear_distance_bins; else stateM(:, bin_ind) = stateM(:,bin_ind) ./ sum(stateM(:, bin_ind)); end end [dx, dy] = meshgrid([-1:1]); sigma = 0.5; normalizing_weight = gaussian(sigma, dx, dy) / sum(sum(gaussian(sigma, dx, dy))); %normalizing weights stateM_gaussian_smoothed = conv2(stateM, normalizing_weight, 'same'); %gaussian smoothed empirical_movement_transition_matrix = stateM_gaussian_smoothed * diag(1 ./ sum(stateM_gaussian_smoothed, 1)); %normalized to confine probability to 1 end function [value] = gaussian(sigma, x, y) value = exp(-(x.^2 + y.^2) / 2 / sigma^2); %gaussian end
github
edeno/Jadhav-2016-Data-Analysis-master
get_ripple_index.m
.m
Jadhav-2016-Data-Analysis-master/Xinyi-ripple-decoding/get_ripple_index.m
2,826
utf_8
f0ad2c35dfa49c680a64d260c0d4d9a1
function [ripple_time_extent, position_time_milliseconds, dt] = get_ripple_index(pos, ripplescons, spikes, tetrode_index, neuron_index) %% calculate ripple starting and end times position_time = pos.data(:, 1); %time stamps for animal's trajectory in seconds position_time_milliseconds = to_milliseconds(position_time(1)):to_milliseconds(position_time(end)); %position time stamps in milliseconds [ripple_time_extent] = get_ripple_extent(ripplescons, ... position_time_milliseconds); [num_spikes_per_ripple] = get_number_spikes_per_ripple(tetrode_index, ... neuron_index, spikes, position_time_milliseconds, ripple_time_extent); [running_speed_at_ripple] = get_running_speed_at_ripple(pos, ripple_time_extent, ... position_time, position_time_milliseconds); ripple_time_extent = ripple_time_extent(running_speed_at_ripple < 4 & num_spikes_per_ripple > 0, :); dt = 1 / (1000 * (position_time(2) - position_time(1))); end function [x] = to_milliseconds(x) x = round(x * 1000); end function [ripple_time_extent] = get_ripple_extent(ripplescons, ... position_time_milliseconds) ripple_start_time = to_milliseconds(ripplescons{1}.starttime); ripple_end_time = to_milliseconds(ripplescons{1}.endtime); traj_Ind = find(ripplescons{1}.maxthresh > 4); ripple_start_time = ripple_start_time(traj_Ind); ripple_end_time = ripple_end_time(traj_Ind); ripple_time_extent = [ripple_start_time - position_time_milliseconds(1) - 1, ... ripple_end_time - position_time_milliseconds(1) - 1]; end function [running_speed_at_ripple] = get_running_speed_at_ripple(pos, ... ripple_time_extent, position_time_stamps, position_time_milliseconds) running_speed = pos.data(:, 5); running_speed_at_ripple = nan(size(ripple_time_extent, 1), 1); for ripple_number = 1:size(ripple_time_extent, 1) ripple_ind = find(position_time_stamps * 1000 > position_time_milliseconds(ripple_time_extent(ripple_number, 1)) & ... position_time_stamps * 1000 < position_time_milliseconds(ripple_time_extent(ripple_number, 2))); running_speed_at_ripple(ripple_number) = running_speed(ripple_ind(1), 1); end end function [num_spikes_per_ripple] = get_number_spikes_per_ripple(tetrode_index, ... neuron_index, spikes, position_time_milliseconds, ripple_time_extent) for neuron_ind = 1:size(tetrode_index, 2) spike_times_milliseconds = to_milliseconds(spikes{tetrode_index(neuron_ind)}{neuron_index(neuron_ind)}.data(:,1)); is_spike(neuron_ind, :) = ismember(position_time_milliseconds, spike_times_milliseconds); end num_spikes_per_ripple = nan(size(ripple_time_extent, 1), 1); for ripple_number = 1:size(ripple_time_extent, 1) is_ripple_spike = is_spike(:, ripple_time_extent(ripple_number, 1):ripple_time_extent(ripple_number, 2)); num_spikes_per_ripple(ripple_number) = sum(is_ripple_spike(:)); end end
github
sanghosuh/lens_nmf-matlab-master
pmi.m
.m
lens_nmf-matlab-master/evaluation/topic_coherence/pmi.m
1,396
utf_8
76f1342186702ed4834e5c2df7d4e322
% Point-wise Mutual Information (PMI) % % Written by Sangho Suh ([email protected]) % Dept. of Computer Science and Engineering, % Korea University % % Reference: % % [1] J. Kim and H. Park. Sparse nonnegative matrix factorization for % clustering. 2008. % [2] D. Newman, J. H. Lau, K. Grieser, and T. Baldwin. Automatic evaluation % of topic coherence. In Proc. the Annual Conference of the North % American Chapter of the Association for Computational Linguistics % (NAACL HLT), pages 100?108, 2010. % % Please send bug reports, comments, or questions to Sangho Suh. % This comes with no guarantee or warranty of any kind. % % Last modified 10/17/2016 % % this function returns a single value % i.e. an average value from a number of pmi values % % <Inputs> % % A : Input matrix (m x n) % Wtopk_idx : Cell array containing matrix with indices for top keywords % mcnt : Number of methods % epsilon : (Default: 1e-3) % % <Output> % % pmi_vals : A matrix of PMI values % function [pmi_vals] = pmi(A, Wtopk_idx, mcnt, epsilon) % create a zero matrix to store PMI values pmi_vals = zeros(size(Wtopk_idx{1},2),mcnt); for i=1:mcnt for topic_idx=1:size(Wtopk_idx{i},2) pmi_vals(topic_idx,i) = compute_pmi_log2(A, Wtopk_idx{i}(:,topic_idx),epsilon); end end end
github
sanghosuh/lens_nmf-matlab-master
compute_pmi_log2.m
.m
lens_nmf-matlab-master/evaluation/topic_coherence/compute_pmi_log2.m
3,977
utf_8
9731fc95c0d82e7dfeb5a219dc361689
% Point-wise Mutual Information (PMI) % % Written by Sangho Suh ([email protected]) % Dept. of Computer Science and Engineering, % Korea University % % Reference: % % [1] J. Kim and H. Park. Sparse nonnegative matrix factorization for % clustering. 2008. % [2] D. Newman, J. H. Lau, K. Grieser, and T. Baldwin. Automatic evaluation % of topic coherence. In Proc. the Annual Conference of the North % American Chapter of the Association for Computational Linguistics % (NAACL HLT), pages 100?108, 2010. % % Please send bug reports, comments, or questions to Sangho Suh. % This comes with no guarantee or warranty of any kind. % % Last modified 10/17/2016 % % this function returns a single value % i.e. an average value from a number of pmi values % % <Inputs> % % A : Input matrix (m x n) % term_idx_mat : Wtopk matrix with corresponding indices % epsilon : Value to prevent log(0) (Default: 1e-3) % % <Output> % % pmi_val : PMI value % function [pmi_val] = compute_pmi_log2(A, term_idx_mat,epsilon) % create a term-by-document matrix consisting of only 1 and 0 % where 1 denotes term occurrence in the corresponding column A(A~=0)=1; % topic coherence for a topic (Keyword-wise similarity) if size(term_idx_mat,2)==1 % if a single column, i.e., one topic term_idx = term_idx_mat(:); % create an array for storing PMI values between pairs of keywords within a topic pmi_vals = zeros( length(term_idx)*(length(term_idx)-1)/2, 1); cnt = 1; % calculate PMI values on pairs of keywords in a topic for i=1:(length(term_idx)-1) for j=(i+1):length(term_idx) % if keywords do NOT co-occur in document(s) if( ( mean ( A(term_idx(i),:) & A(term_idx(j),:) ) ) == 0 ) pmi_vals(cnt) = 0; % if keywords co-occur in document(s), calculate their PMI value else pmi_vals(cnt) = log2( (mean(A(term_idx(i),:) & A(term_idx(j),:))+epsilon) / (mean(A(term_idx(i),:))*mean(A(term_idx(j),:))) ); end cnt = cnt + 1; end % get average from array of PMI values pmi_val = mean(pmi_vals); end % topic coherence for topics (Topic-wise similarity) else % if more than one topic, find the similarity between topics % create an array for storing PMI values between topics pmi_val_tlvl = zeros( size(term_idx_mat,2)*(size(term_idx_mat,2)-1)/2, 1 ); cnt_tlvl = 1; % calculate PMI values between keywords of topics for k=1:(size(term_idx_mat,2)-1) for l=(k+1):size(term_idx_mat,2) term_idx1 = term_idx_mat(:,k); term_idx2 = term_idx_mat(:,l); % create an array for storing PMI values between keywords of topics pmi_vals = zeros( length(term_idx1)*length(term_idx2), 1 ); cnt = 1; for i=1:length(term_idx1) for j=1:length(term_idx2) % if keywords do NOT co-occur in document(s) if( (mean(A(term_idx1(i),:) & A(term_idx2(j),:))) == 0 ) pmi_vals(cnt) = 0; % if keywords co-occur in document(s), calculate their PMI value else pmi_vals(cnt) = log2((mean(A(term_idx1(i),:) & A(term_idx2(j),:))+epsilon) / (mean(A(term_idx1(i),:))*mean(A(term_idx2(j),:)))); end cnt = cnt + 1; end end pmi_val_tlvl(cnt_tlvl) = mean(pmi_vals); cnt_tlvl = cnt_tlvl + 1; end end % get average from array of PMI values pmi_val = mean(pmi_val_tlvl); end end