#
# Refine the vertex partition mu of digraph G so that vertices in the
# same block have the same "separation" invariant: for vertex x, this is
#   number of edges x -> block j
#   number of edges x <- block j
# If a third argument is a variable z, then the return value is a list
# of pairs [g,A], where A is block of the new vertex partition, and g
# is the value of its separation invariant, expressed as a Laurent poly
# in the variable z.
#
`posets/separate`:=proc(G,mu) local B,f,i,j,e,q,nu;
  B:=table([seq(seq(j=i,j=mu[i]),i=1..nops(mu))]);
  f:=table('sparse'); if nargs>2 then q:=args[3] fi;
  for e in G do
    f[e[1]]:=f[e[1]]+q^(-B[e[2]]);
    f[e[2]]:=f[e[2]]+q^B[e[1]];
  od;
  nu:=map(`posets/separate/one`,mu,f);
  if nargs>2 then [seq([f[i[1]],i],i=nu)] else nu fi;
end:
#
# Refine a particular block using the invariant data in the table f:
# We must return a canonically ordered sequence of subsets of X such
# that u,v appear in the same subset iff they have the same invariant.
#
# Currently, the canonical order is derived from 'tcoeff'.
# Possibly other sorting orders will give nicer results.
#
`posets/separate/one`:=proc(X,f) local pi,i,t,g,l;
  if nops(X)=1 then RETURN(X) fi;
  pi:=table('sparse');
  for i in X do l:=f[i]; pi[l]:=pi[l]+t[i] od;
  g:=map(op,[indices(pi)]);
  g:=sort(g,(x,y)->evalb(tcoeff(y-x)>0));
  seq(map(op,indets(pi[i])),i=g);
end:
#
save `posets/separate`, `posets/separate/one`,
  cat(HomeLib,`/posets/separate.m`);
quit;

