#
# J(P,X) returns the abstract poset of order ideals of a poset P with
#  vertex set X.
# The vertices of the output are numbered 1 to m following the lexorder
#  used by 'ideals'; i.e., ideals(P,X)[i] is the i-th vertex of J(P,X).
# J(P,n) does the same, assuming X={1,2,...,n}.
# J(P) does the same, assuming there are no isolated vertices.
# The vertex set X can be a linear extension of P (a *list*, not a *set*)
#  in order to control the lexordering used for the ideals.
# The output is always a naturally labeled poset.
#
# Append 'table' to get the table of upward covers.
# A fact of life: given that we want a natural numbering of the ideals,
#  downward covers are significantly more expensive to compute.
#
`posets/J`:=proc(P) local X,up,Jup,m,loc,x,y,i,j,K,L;
  m:=nargs; if args[m]='table' then m:=m-1 fi;
  if m>2 then ERROR(`invalid arguments`)
    elif m=2 and type(args[2],'list') then X:=args[2]
    else X:=map(op,posets['filter'](args[1..m])) fi;
  up:=`posets/downsets`(P,X,'up');
  loc:=table([seq(x=1,x=X)]);
  Jup:=table([1={}]); m:=1;
  for x in X do
    K:=table([1={loc[x]}]);
    for j while nops(K[j])>0 do K[j+1]:={seq(op(Jup[i]),i=K[j])} od;
    K:=sort([seq(op(K[i]),i=1..j-1)]);
    L:=[seq(K[j]=m+j,j=1..nops(K))];
    for j to nops(K) do i:=m+j;
      Jup[i]:=subs(L,Jup[K[j]]);
      Jup[K[j]]:={op(Jup[K[j]]),i};
    od;
    for y in up[x] do if member(loc[y],K,'j') then loc[y]:=m+j fi od;
    m:=m+nops(K)
  od;
  if args[nargs]='table' then op(Jup)
    elif m=1 then {},1
    else {seq(seq([i,j],j=Jup[i]),i=1..m)} fi
end:
#
save `posets/J`, cat(HomeLib,`/posets/J.m`);
read cat(HomeLib,`/help/posets/J`);
quit;

