#
# filter(D,X) returns the filtration of acyclic graph D with vertex set X.
#  filtration = [F1,F2,...,F_r], where F1={minimal elements of D},
#  F2={minimal elements of D-F1}, etc...
# filter(D,n) does the same, using the vertex set {1,...,n}.
# filter(D) does the same, assuming that D has no isolated vertices.
#  Reference: Knuth, TAOCP Vol I., Sec. 2.2.3.
# The inner loop is ugly, but faster than the more natural mapping.
#
`posets/filter`:=proc(P) local X,ct,up,e,x,y,F,G,res;
  if nargs=1 then X:=map(op,P)
    elif type(args[2],'integer') then X:={$1..args[2]}
    else X:=args[2] fi;
  up:=table([seq(x=NULL,x=X)]);
  ct:=table('sparse'); res:=NULL;
  for e in P do ct[e[2]]:=ct[e[2]]+1; up[e[1]]:=up[e[1]],e[2] od;
  F:=NULL; for x in X do if ct[x]=0 then F:=F,x fi od;
  while F<>NULL do
    res:=res,{F}; G:=[F]; F:=NULL;
    for x in G do for y in [up[x]] do
      if ct[y]=1 then F:=F,y else ct[y]:=ct[y]-1 fi
    od od;
  od; [res]
end:
#
save `posets/filter`, cat(HomeLib,`/posets/filter.m`);
read cat(HomeLib,`/help/posets/filter`);
quit;

