#
# rm_isom(L) removes extra isomorphic copies from a list (or set) L of 
# of directed graphs. Isolated vertices are ignored for the purpose of
# isomorphism testing. If L is a list, the result returned will be the
# sublist of L formed by the earliest instance of each isomorphism class
# in the list. If L is a set, the result will be a subset of L.
#
# We use the invariants associated with the fast discriminant as a hash
# function that sorts graphs into buckets.
# As soon as a bucket contains 3 or more graphs, the presumption is that
# we are better off using 'canon' to distinguish the graphs; for a bucket
# of two, we use 'isom'. For a singleton, we don't need to do anything.
#
# Note that before a bucket overflows, it is stored as a list of indices j,
# and can[j] holds the canonical vertex partition provided by 'fastdisc'.
# After overflow, it gets converted to a *set* of indices j and can[j]
# holds the canonical relabeling of the graph.
#
# Haven't tested for the actual cross-over point between isom versus canon.
# It could be at bucket sizes > 3.
#
`posets/rm_isom`:=proc(L) local can,bckt,i,j,mu,shp,J,P,new,u,q;
  can:=table(); bckt:=table('sparse');
  for i to nops(L) do
    mu:=`posets/fastdisc`(L[i],[map(op,L[i])]);
    shp:=`posets/separate`(L[i],mu,q);
    shp:=map(x->[x[1],nops(x[2])],shp);
    J:=bckt[shp]; if J=0 then J:=[] fi;
    if type(J,'set') then
      P:=`posets/canorder`(L[i],mu,0)[1]; new:=i;
      for j in J do if can[j]=P then new:=NULL; break fi od;
      if new=i then can[i]:=P; bckt[shp]:={op(J),i} fi;
    else
      J:=[op(J),i]; can[i]:=mu;
      if nops(J)>=3 then # the bucket is too full
        new:=`posets/rm_isom/overflow`(J,L,can);
        for u in new do can[u[1]]:=u[2] od;
        J:=map(x->op(1,x),new)
      fi;
      bckt[shp]:=J
    fi;
  od;
  new:=map(`posets/rm_isom/final`,[entries(bckt)],L,can);
  if type(L,'set') then {seq(L[i],i=new)}
    else [seq(L[i],i=sort(new))] fi
end:
#
# Clean out the overflowing bucket; note that it is important
# that the return value is a *set* of pairs [j,P]. 
#
`posets/rm_isom/overflow`:=proc(J,L,can) local lg,res,j,P;
  lg:=NULL; res:=NULL;
  for j in J do
    P:=`posets/canorder`(L[j],can[j],0)[1];
    if not member(P,[lg]) then lg:=lg,P; res:=res,j fi
  od;
  res:=zip((x,y)->[x,y],[res],[lg]); {op(res)}
end:
#
# Empty out the buckets: if there are any doubletons
# remaining that never overflowed, deal with them.
#
`posets/rm_isom/final`:=proc(J,L,can) local oJ,pi;
  oJ:=op(J);
  if nops(oJ)<>2 or type(oJ,'set') then RETURN(op(oJ)) fi;
  pi:=`posets/cisom`(L[oJ[1]],can[oJ[1]],L[oJ[2]],can[oJ[2]]);
  if pi=NULL then op(oJ) else oJ[1] fi;
end:
#
save `posets/rm_isom`, `posets/rm_isom/overflow`, `posets/rm_isom/final`,
  cat(HomeLib,`/posets/rm_isom.m`);
read cat(HomeLib,`/help/posets/rm_isom`);
quit;

