#
# Given a directed graph G with vertex set X, return the partition
#  of X induced by the strongly connected components of G.
# If a third argument is present, it is assigned the acyclic digraph Q
#  induced on the components: if there is an edge [x,y] involving
#  a vertex x from component i and a vertex y from a component j<>i,
#  then [i,j] is an edge of Q.
# The components of the partition are listed in an order consistent with G:
#  if [i,j] is an edge of Q, then i < j (as integers).
#
# Example:
#   C:=strongcomps(G,X,'Q');
#   P:=posets['covers'](Q);
#   posets['plot_poset'](P,nops(C),labels);
#
`posets/strongcomps`:=proc(G) local X,down,x,C,cof,F,Q,i,alive,m;
  m:=nargs; if type(args[m],'name') then m:=m-1 fi;
  if m=1 then X:=map(op,G)
    elif type(args[2],'integer') then X:={$1..args[2]}
    else X:=args[2]
  fi;
  down:=`posets/coversets`(G,X,0); # the 0 asks for loops
  for x in X do down[x]:=`posets/strongcomps/sat`(x,down) od;
  C:=table(); alive:=X;
  for i while nops(alive)>0 do
    F:=down[alive[1]]; m:=nops(F);
    F:=map(proc(x,Y,z) if nops(Y[x])=z then x fi end,F,down,m);
    C[i]:=F,m; alive:=alive minus F;
  od;
  C:=map(y->y[1],sort([entries(C)],(u,v)->evalb(u[2]<=v[2])));
  if type(args[nargs],'name') then
    cof:=table([seq(seq(x=i,x=C[i]),i=1..nops(C))]);
    Q:=map((x,Y)->[Y[x[1]],Y[x[2]]],G,cof);
    Q:=map(x->if x[1]<>x[2] then x fi,Q);
    assign(args[nargs],Q);
  fi; C
end:
#
# Given a table of down-neighbors, generate the set of
# all vertices reachable from x by a downward path.
#
`posets/strongcomps/sat`:=proc(x,down) local old,new,y;
  old:={x}; new:=down[x];
  while nops(new)>nops(old) do
    old:=new; new:={seq(op(down[y]),y=old)}
  od; new
end:
#
save `posets/strongcomps`, `posets/strongcomps/sat`,
  cat(HomeLib,`/posets/strongcomps.m`);
read cat(HomeLib,`/help/posets/strongcomps`);
quit;

