
# Check to see if P is in canonical form (i.e., no poset isomorphic
# to P precedes it in lexorder). Here, pg is a list of substitutions
# on the vertex set of P that generate the isomorphs of P.
# (Since P is narrow, pg is a list of commuting involutions.)

# If P has a type that is self-dual, and canform is called with an
# optional third argument consisting of the dualizing permutation
# of the vertices, then we return true only if the canonical form of
# dual(P) does not precede P in lexorder. 

canform:=proc(P,pg) local Q,pi,dP;
  for pi in pg do
    Q:=subs(pi,P);
    if `canform/compare`(P,Q) then RETURN(false) fi
  od;
  if nargs<3 then RETURN(true) fi;
  dP:=map(x->[x[2],x[1]],subs(args[3],P));
  for pi in pg do
    Q:=subs(pi,dP);
    if `canform/compare`(dP,Q) then dP:=Q fi;
  od;
  not `canform/compare`(P,dP);
end;

# Compare two edge sets of the same cardinality. If the lexfirst edge in
# the symmetric difference of P and Q belongs to Q, return true.

`canform/compare`:=proc(P,Q) local f,e,J;
  if P=Q then RETURN(false) fi;
  J:=P minus Q; f:=J[1];
  for e in J do
    if e[1]<f[1] or (e[1]=f[1] and e[2]<f[2]) then f:=e fi
  od;
  J:=Q minus P;
  for e in J do
    if e[1]<f[1] or (e[1]=f[1] and e[2]<f[2]) then RETURN(true) fi
  od; false
end:

# Given a type vector T for a class of narrow posets, return
# true if the dual type comes strictly after T in lexorder.
# In that case, assign to args[2] a list pg of substitutions
# that generate potential isomorphs for each poset of type T.
# If a third argument is present, and T is a self-dual type,
# assign to args[3] the dualizing vertex substitution.

`canform/dual`:=proc(T) local rT,M,N,a,i,pg,pi;
  rT:=[seq(T[-i],i=-nops(T)..-1)];
  for i to nops(T) while T[i]=rT[i] do od;
  if i<=nops(T) and (T[i][1]>rT[i][1] or
    (T[i][1]=rT[i][1] and T[i][2]>rT[i][2])) then RETURN(false) fi;
  if nargs>2 and i>nops(T) then
    pi:=NULL; N:=0;
    for a in T do 
      M:=N; N:=N+a[1]+a[2];
      if a[2]=0 then pi:=pi,N else
        pi:=pi,seq(i,i=N-a[1]+1..N),seq(i,i=M+1..M+a[2]) fi;
    od;
    pi:=[pi]; pi:={seq(i=N+1-pi[i],i=1..N)};
    assign(args[3],pi);
  fi;
  N:=0; pg:=NULL;
  for a in T do
    M:=N; N:=N+a[1]+a[2];
    if a[1]=a[2] and a[1]>1 then
      pg:=pg,{seq(op([i=i+a[1],i+a[1]=i]),i=M+1..M+a[1])} fi;
  od;
  assign(args[2],[pg]); true
end;

