#
# f_poly(P,X,q) evaluates the f-polynomial of a bounded poset P with
#  vertex set X at q; i.e., the sum of f_k * q^k, where f_k is the
#  number of chains from 0 to 1 of length k.
# f_poly(P,n,q) does the same, assuming X={1,2,...,n}.
# f_poly(P,q) does the same (there shouldn't be isolated vertices).
#
`posets/f_poly`:=proc(P) local PS,f,q;
  PS:=`posets/f_poly/unbind`(args[1..nargs-1]);
  if nops(P)=0 then f:=1 else f:=q*posets['chains'](PS,q) fi;
  expand(subs(q=args[nargs],f));
end:
#
# Do the same for the h-polynomial. If f is the f-poly, then
#  the h-poly is h(q)=(1-q)^d * f(q/(1-q)), where d=degree(f).
#
`posets/h_poly`:=proc(P) local PS,f,d,z,q;
  PS:=`posets/f_poly/unbind`(args[1..nargs-1]);
  if nops(P)=0 then RETURN(1) fi;
  f:=posets['chains'](PS,q); d:=degree(f,q);
  f:=expand(z^d*q*subs(q=q/z,f));
  expand(subs(q=args[nargs],z=1-args[nargs],f))
end:
#
# Return the poset structure obtained by deleting the maximum and
# minimum elements, or scream if the poset lacks these features.
# Note that if args[2] is a linear extension, we do the right thing.
#
`posets/f_poly/unbind`:=proc(P) local X,x0,x1;
  if nargs>2 then ERROR(`invalid arguments`)
    elif nargs=1 then X:=map(op,P)
    elif type(args[2],'integer') then X:={$1..args[2]}
    else X:=args[2] fi;
  x0:={op(X)} minus map(e->op(2,e),P);
  if nops(x0)=1 then x0:=op(x0) else 
    ERROR(`the poset lacks a minimum element`) fi;
  x1:={op(X)} minus map(e->op(1,e),P);
  if nops(x1)=1 then x1:=op(x1) else
    ERROR(`the poset lacks a maximum element`) fi;
  map(proc(e,x,y) if e[1]<>x and e[2]<>y then e fi end,P,x0,x1),
    subs(x0=NULL,x1=NULL,X)
end:
#
save `posets/f_poly`, `posets/h_poly`, `posets/f_poly/unbind`,
  cat(HomeLib,`/posets/f_poly.m`);
read cat(HomeLib,`/help/posets/f_poly`);
read cat(HomeLib,`/help/posets/h_poly`);
quit;

