#
# ideals(P,X) generates a lexordered list of all order ideals of a poset P
#  with vertex set X.
# ideals(P,n) does the same, using X={1,...,n}.
# ideals(P) does the same, assuming that P has no isolated vertices.
# In the lexorder, ideal I precedes ideal J if the "last" member of the
#  symmetric difference of I and J occurs in J. Here, "last" is determined
#  by some chosen linear extension of the vertex set of P.
# To force a particular choice of linear extension, provide X as a *list*
#  of vertices in the desired order.
# Optionally, if the final argument (the 2nd or 3rd) is:
#  -a name, such as q, then the generating series for ideals is returned
#   (i.e., the sum of q^nops(I) for all ideals I of P)
#  -a range, such as 2..7, the result is a lexordered list of ideals of P
#   with sizes in this range.
#
`posets/ideals`:=proc(P) local Q,X,n,lb,ub,q;
  lb:=NULL; q:=NULL; n:=nargs;
  if type(args[n],'range') then
    lb:=op(1,args[n]); ub:=op(2,args[n]); n:=n-1
  elif type(args[n],'name') then
    q:=args[n]; n:=n-1 fi;
  if n>2 then ERROR(`invalid arguments`)
    elif n=2 and type(args[2],'list') then X:=args[2]
    else X:=map(op,posets['filter'](args[1..n])) fi;
  if lb=NULL then lb:=0; ub:=nops(X)
    elif nops(X)<lb or ub<0 or ub<lb then RETURN([]) fi;
  Q:=posets['closure'](P,X);
  if q=NULL then `posets/ideals/list`(Q,X,lb,ub)
    else `posets/ideals/series`(Q,X,q) fi
end:
#
# Ideals either omit the last member of X, or they do not...
# The input is always kept sane:  nops(X) >= lb <= ub >= 0.
#
`posets/ideals/list`:=proc(Q,X,lb,ub) local n,mx,P,Y,L,J,j;
  n:=nops(X);
  if n=0 then RETURN([{}])
    elif n-1<lb then
      if n<=ub then RETURN([{op(X)}]) else RETURN([]) fi
  fi;
  mx:=X[n]; Y:=subsop(n=NULL,X);
  P:=map(proc(e,y) if e[2]<>y then e fi end,Q,mx);
  L:=procname(P,Y,lb,ub);
  Y:=map(proc(x,y,Z) if not member([x,y],Z) then x fi end,Y,mx,Q);
  J:={op(X)} minus {op(Y)}; j:=nops(J);
  if j>ub then RETURN(L) elif j>1 then
    P:=map(proc(e,Z) if member(e[1],Z) then e fi end,P,Y) fi;
  [op(L),op(map((x,y)->{op(x),op(y)},procname(P,Y,lb-j,ub-j),J))]
end:
#
# For a series, we can escape when the last member of X is isolated.
#
`posets/ideals/series`:=proc(Q,X,q) local n,mx,P,Y,f,j;
  if nops(Q)=0 then RETURN(expand((1+q)^nops(X))) fi;
  n:=nops(X); mx:=X[n]; Y:=subsop(n=NULL,X);
  P:=map(proc(e,y) if e[2]<>y then e fi end,Q,mx);
  f:=procname(P,Y,q);
  Y:=map(proc(x,y,Z) if not member([x,y],Z) then x fi end,Y,mx,Q);
  j:=n-nops(Y);
  if j=1 then f+expand(q*f) else
    P:=map(proc(e,Z) if member(e[1],Z) then e fi end,P,Y);
    f+expand(q^j*procname(P,Y,q))
  fi
end:
#
save `posets/ideals`, `posets/ideals/list`, `posets/ideals/series`,
  cat(HomeLib,`/posets/ideals.m`);
read cat(HomeLib,`/help/posets/ideals`);
quit;

