#
# A labeled poset may be specified as a pair (P,V), where P is the set
# of covering pairs and V is a subset of P such that the digraph obtained
# from P by reversing the orientation of the arcs in V is acyclic.
#
# If P has vertex set X, then labelings(P,X,iv,In,Out,f) traverses the
# set of all such subsets V that omit every covering edge in Out, and
# include every covering edge in In. For each such V, the assignment
#
#    new := f(new,P,X,V)
#
# is applied, and then the final value of 'new' is returned.
# The initial value assigned to new is 'iv'.
#
# We do not check whether In and Out are disjoint subsets of P.

labelings:=proc(P,X,iv,In,Out,f) local Q,new,V,J,R,i;
  V:=P minus Out; Q:=[op(V minus In)];
  new:=iv; J:=[$1..nops(Q)];
  do
    R:=(P minus V) union map(x->[x[2],x[1]],V);
    if not has_cycles(R) then new:=f(new,P,X,V,args[7..nargs]) fi;
    if nops(J)>0 then i:=J[1] else break fi;
    J:=subs(i=($1..i-1),J);
    V:={op(1..i-1,Q),op(subs(Q[i]=NULL,V))};
  od; new
end;

#  Decide if directed graph R has any directed cycles.
#  R must be a set of ordered pairs [a,b].

has_cycles:=proc(R) local Q,X;
  if nops(R)=0 then RETURN(false) fi;
  X:=map(x->x[1],R);
  if X=map(op,R) then RETURN(true) fi;
  Q:=map(proc(e,y) if member(e[2],y) then e fi end,R,X);
  procname(Q);
end;

