function y = flowGrad(G, levelIdx, nodeInfo)
% Gradient flow analysis of mapper adjacency graph 
%	y = flowGrad(G, levelIdx, nodeInfo)

numLevel = length(levelIdx);

% Construct the downward gradient flow as a directed graph
dG = triu(G,0);

localMax = find(sum(dG,1)==0);
dd = zeros(length(G),1);
if nargin<3,
	dd(localMax)=1;
else
	for i=1:length(localMax),
		dd(localMax(i)) = length(nodeInfo{localMax(i)}.set);
	end
end
dG = dG + diag(dd);

dG_inf=dG^numLevel;
for i=1:length(G),
	y.assign{i}=find(dG_inf(:,i)>0);
end

% Construct the induced markov chain 
MarkovT = dG*diag(1./sum(dG,1));

y.localMax = localMax;
y.gradFlow = dG;
y.equilibrium = MarkovT^numLevel;

disp(sprintf(' Number of local maxima: %d', length(y.localMax)));