#
# Generate a table whose x entry is the set of vertices y covered by x.
# We do not confirm that P is a covering relation, so the x entry is
#  really the set of y such that [y,x] is a member of P.
# Add a flag as args[3] to add loops [x,x] at each vertex x.
#
`posets/coversets`:=proc(P,X) local x,e,cov;
  if nargs>2 then cov:=table([seq(x=x,x=X)]);
    else cov:=table([seq(x=NULL,x=X)]) fi;
  for e in P do cov[e[2]]:=cov[e[2]],e[1] od;
  for x in X do cov[x]:={cov[x]} od; op(cov)
end:
#
# Do the same, but here we want the x entry to be the set of all y<x
#  in the transitive closure of P.
# Or add the flag 'up' as args[3], to get {y: y>x} instead.
# IMPORTANT: here, X must be a linear extension of P; i.e., a *list*
#  of the vertices of P so that y<x in P implies y precedes x in X.
# If P is known to be transitive, then the same result can be obtained
#  more cheaply by computing coversets.
#
`posets/downsets`:=proc(P,X) local down,x,y,i;
  if not type(X,'list') then
    ERROR(`vertices must be in a list`)
  elif nargs>2 then
    procname(posets['dual'](P),[seq(X[-i],i=-nops(X)..-1)])
  else
    down:=`posets/coversets`(P,X);
    for x in X do down[x]:={op(down[x]),seq(op(down[y]),y=down[x])} od;
    op(down)
  fi
end:
#
save `posets/coversets`, `posets/downsets`,
  cat(HomeLib,`/posets/downsets.m`);
quit;

