#
# traverse - iterate over isomorphism classes of posets on n points
#
# Calling sequence:
#  traverse(n,iv,f,<parameters>);
#
# Parameters:
#  n  = a positive integer (the number of vertices)
#  iv = an initial value
#  f  = a procedure
#
# The traverse function provides a very space-efficient means of searching
# through or iterating over each isomorphism class of posets on a given
# number of vertices. On a fast machine, it is reasonable to use this
# to search through n-vertex posets for n=10 or more.
#
# When called with arguments (n,iv,f), the procedure begins by assigning
# the value of iv to a local variable 'res'. Then for each isomorphism
# class of posets P on n points it performs the assignment
#   res := f(res,P,down,n)
# thereby allowing a running total to be accumulated over all posets.
# When the loop is finished, it returns the final value assigned to 'res'.
#
# Any additional parameters a,b,... supplied to 'traverse', are passed on
# to f. In other words, for each P, res := f(res,P,down,n,a,b,...) is computed. 
#
# The vertex set of each poset P is {1,...,n}, but the ordering will not
# necessarily be natural -- there may be pairs [i,j] in P with i>j as well
# as pairs [i,j] with i<j.
#
# Debugging note: it is important that f always return a non-NULL value 
# (in fact, an expression sequence of length 1); otherwise, subsequent
# invocations of f will get confused when parsing arguments.
#
traverse:=proc(n,iv,f) local Rank,Cstack,P,X,Y,i,j,st,cc,res;
  Rank:=0; Cstack:=table(); st:=time();
  P:=[{},[seq({i},i=1..n)]];
  X:={$1..n}; res:=iv;
  do
    res:=f(res,P[1],P[2],n,args[4..nargs]);
    Y:=X minus map(x->x[1],P[1]);
    cc:={seq(seq(`traverse/accept`([j,i],P[1],P[2],X),j=X minus P[2][i]),i=Y)};
    if nops(cc)>0 then Rank:=Rank+1 else
      do cc:=Cstack[Rank];
        if nops(cc)=0 then Rank:=Rank-1 else break fi;
      od;
      if Rank=0 then break fi
    fi;
    Cstack[Rank]:=subsop(1=NULL,cc); P:=cc[1]
  od; res
end;

# Decide whether the poset Q obtained by adding edge e to P identifies
# e as its "canonical" edge. If so, return the canonical form of Q.

`traverse/accept`:=proc(e,P,down,X) local Q,i,Y,ct,d,pi,new;
  for i in P do
    if member(i[1],down[e[1]]) and member(e[2],down[i[2]]) then RETURN() fi
  od;
  Q:={op(P),e}; Y:=map(op,Q) minus map(x->x[1],Q);
  ct:=table([seq(i=0,i=Y)]);
  for i in Q do if member(i[2],Y) then ct[i[2]]:=ct[i[2]]+1 fi od;
  d:=min(seq(ct[i],i=Y)); if ct[e[2]]<>d then RETURN() fi;
  Y:=map(proc(x,y,z) if y[x]=z then x fi end,Y,ct,d);
  pi:=`posets/canorder`(Q,[Y,X minus Y]);
  Q:=subs({seq(pi[i]=i,i=1..nops(pi))},Q);
  i:=min(op(map(proc(x) if x[2]=1 then x[1] fi end,Q)));
  if [pi[i],pi[1]]=e or posets['isom'](P,Q minus {[i,1]}) then
    new:=map(proc(x,A,U,y) if member(y,A[x]) then {op(A[x]),op(U)}
      else A[x] fi end,pi,down,down[e[1]],e[2]);
    [Q,subs({seq(pi[i]=i,i=1..nops(pi))},new)]
  fi;
end;

