#
# Given a linear extension X of P, generate the up-table of legal
# inclusions in J(P) relative to a labeling with inversion set V,
# and assign to args[4] the partition of the vertices into ranks in
# descending order. An inclusion I < J is legal iff J-I contains no
# pair i,j with [i,j] in V.
#
# We'd rather have the down-table, but once we are handed a linear
# extension, the up-table is more natural to compute. An alternative
# is to view this as the down-table of dual(P) relative to dual(V),
# assigning to args[4] the natural (ascending) rank partition.
#
# After k rounds of the main loop, we have computed both the up-table
# of legal inclusions (leg) and upward cover table for all ideals (Jup)
# for the subposet formed by the first k members of X.
#
`posets/labtab`:=proc(P,X,V) local up,red,loc,Jup,bot,leg,m,x,y,i,j,K,new;
  up:=`posets/downsets`(P,X,'up');
  red:=`posets/labtab/red`(P,X,V); m:=1;
  loc:=table([seq(x=1,x=X)]); Jup:=table([1={}]);
  bot:=table([seq(x=1,x=X)]); leg:=table([1={}]);
  for x in X do
    K:=table('sparse'); new:={loc[x]};
    while nops(new)>0 do
      for i in new do m:=m+1; K[i]:=m od;
      new:={seq(op(Jup[i]),i=new)}
    od;
    new:=map(op,[indices(K)]);
    for i in new do
      Jup[K[i]]:=[seq(K[j],j=Jup[i])];
      leg[K[i]]:=[seq(K[j],j=leg[i])];
      Jup[i]:=[K[i],op(Jup[i])];
      leg[i]:=[K[i],op(leg[i])];
    od;
    new:={bot[x]};
    while nops(new)>0 do
      for i in new do
        leg[i]:=subs(0=NULL,[op(leg[i]),seq(K[j],j=leg[i])])
      od;
      new:={seq(op(Jup[i]),i=new)}
    od;
    for y in up[x] do loc[y]:=K[loc[y]];
      if member(x,red[y]) then bot[y]:=K[bot[y]] fi
    od;
  od;
  assign(args[4],`posets/labtab/rankpart`(Jup)); op(leg)
end:
#
# Build the red-table: red[x] = ideal generated by all y with [y,x] in V.
#
`posets/labtab/red`:=proc(P,X,V) local down,red,e,x;
  down:=`posets/downsets`(P,X);
  red:=table([seq(x={},x=X)]);
  for e in V do red[e[2]]:={op(red[e[2]]),e[1],op(down[e[1]])} od;
  op(red)
end:
#
# Get the (reverse) rank partition from a table of up-covers,
# given that 1 is a minimum element.
#
`posets/labtab/rankpart`:=proc(up) local R,r,i;
  R:=table([1={1}]);
  for r while nops(R[r])>0 do R[r+1]:={seq(op(up[i]),i=R[r])} od;
  [seq(R[-i],i=1-r..-1)]
end:
#
save `posets/labtab`, `posets/labtab/red`, `posets/labtab/rankpart`,
  cat(HomeLib,`/posets/labtab.m`);
quit;

