%This software implements the point matching algorithm described in the paper:
%"Rotation Invariant Nonrigid Point Set Matching in Cluttered Scenes", IEEE transaction on Image Processing, 2012

%Author: Wei Lian (Changzhi University, Changzhi, 046011, Shanxi Province, P.R. China, Email: lianwei3 at gmail.com)

%If you use this software for research purposes, you should cite the aforementioned paper in any resulting publications.


function [energy,pointer]=treeTri_DP_simi_referenceKnown(node,edges,scdist,Jx,Ypair,pointer,refer,lambda)
%use similarity measure
% lambda=1;
Ny=size(Ypair,2);
energy=zeros(Ny,1);
%prediction step
invJnod=inv([Jx(:,:,1);Jx(:,:,node)]);%inv of Jacabian of point pair 1, node
transnod=invJnod*Ypair;%4 x Ny,similarity transformation between (1, node) in X and (refer, a point) in Y
for ii=1:size(edges,1)%traverse node's children
    if edges(ii,1)==node||edges(ii,2)==node
        if edges(ii,1)==node
            nex=edges(ii,2);
        else
            nex=edges(ii,1);
        end
        edges2=edges;
        edges2(ii,:)=[];%prune the edge [node,nex]
        [leafen,pointer]=treeTri_DP_simi_referenceKnown(nex,edges2,scdist,Jx,Ypair,pointer,refer,lambda);%leaf energy
        %%similarity transformation for two frame edges
        invJnex=inv([Jx(:,:,1); Jx(:,:,nex)]);%inv of Jacabian of point pair 1, nex
        transnex=invJnex*Ypair;%4 x Ny
        candidate=lambda*squeeze(sum(abs(repmat(transnod,[1,1,Ny])-repmat(permute(transnex,[1,3,2]),[1,Ny,1]))))+...
            repmat(leafen',[Ny,1]);%Ny x Ny
        [candmin,index]=min(candidate,[],2);%Ny x 1
        pointer(:,nex)=index;
        energy=energy+candmin;
    end
end
energy=energy+scdist(:,refer,node);
