#
# ranked(P,X) returns true/false if the poset P with vertex set X is/not
#  ranked; i.e., there exists an integer-valued function r() on X such
#  that r(y)-r(x)=1 for all (covering) relations [x,y] in P.
# ranked(P,n) does the same, if X={1,...,n}.
# ranked(P) does the same, disregarding any isolated vertices of P.
# ranked(P,X,'R') does the same, and if the result is true,
#  then R is assigned a partition [X_0,X_1,...,X_r] of X into ranks.
# ranked(P,n,'R') and ranked(P,'R') operate similarly. 
#
`posets/ranked`:=proc() local P,X,n,e,res,u,v,rk,i,r,a;
  n:=nargs; if type(args[n],'name') then n:=n-1 fi;
  if n>2 then ERROR(`invalid arguments`)
    elif n=1 then X:=map(op,args[1])
    elif type(args[2],'integer') then X:={$1..args[2]}
    else X:=args[2] fi;
  n:=nops(X); res:=[seq(a[i],i=1..n)];
  P:=subs({seq(X[i]=i,i=1..n)},args[1]);
  for e in P do
    i:=res[e[2]]-res[e[1]]-1;
    if i=0 then next elif type(i,'integer') then RETURN(false) fi;
    u:=indets(res[e[1]])[1]; v:=indets(res[e[2]])[1];
    i:=subs(u=0,v=0,i);
    if i>0 then res:=subs(u=v+i,res) else res:=subs(v=u-i,res) fi;
  od;
  if not type(args[nargs],'name') then RETURN(true) fi;
  res:=subs({seq(v=0,v=indets(res))},res);
  r:=max(op(res),-1); rk:=table([seq(i=NULL,i=0..r)]);
  for i to n do rk[res[i]]:=rk[res[i]],X[i] od;
  assign(args[nargs],[seq({rk[i]},i=0..r)]); true
end:
#
save `posets/ranked`, cat(HomeLib,`/posets/ranked.m`);
read cat(HomeLib,`/help/posets/ranked`);
quit;

