#
# W(P,X,q,t) returns the W-polynomial of a poset P with vertex set X,
#  evaluated at (q,t).
# W(P,n,q,t) does the same, using X={1,...,n}.
# W(P,q,t) does the same, assuming P has no isolated vertices.
# W(P,X,q,t,S), where S is a subset of the cover relations of P, returns
#  the W-polynomial relative to a labeling in which descents occur at S.
# W(P,n,q,t,S), W(P,q,t,S) function similarly.
# All of the above calling sequences can have the optional string 'ideals'
#  or 'linear' appended. The former selects an algorithm that is quadratic
#  in the number of order ideals, the latter is linear in the number of
#  linear extensions.
#
`posets/W`:=proc(P) local main,flag,V,X,k,q,t,n,Q;
  V:={}; flag:=0; main:=`posets/W/`;
  for k from nargs by -1 to 3 do
    if type(args[k],'set') then V:=args[k]
      elif args[k]='linear' then flag:=-1
      elif args[k]='ideals' then flag:=1
      elif args[k]='omega' then main:=`posets/omega/`
      else break
    fi
  od;
  t:=args[k]; k:=k-1;
  if main=`posets/omega/` then q:=NULL; else q:=args[k]; k:=k-1 fi;
  if k>2 then ERROR(`invalid arguments`)
    elif k=1 then X:=map(op,P)
    elif type(args[2],'integer') then X:={$1..args[2]}
    else X:=args[2] fi;
  Q:=(P minus V) union map(x->[x[2],x[1]],V);
  n:=nops(X); X:=map(op,posets['filter'](Q,X));
  if nops(X)<>n then
    ERROR(`not an admissible subset`)
  elif q=1 and t=1 then
    `posets/W/count`(P,n)
  elif flag>0 or (flag=0 and n>6) then
    X:=map(op,posets['filter'](P,{op(X)}));
    cat(main,'ideals')(P,X,V,q,t)
  else
    Q:=subs({seq(X[k]=k,k=1..n)},P);
    cat(main,'linear')(Q,{$1..n},0,1,q,t) fi;
end:
#
`posets/W/linear`:=proc(P,X,x0,m0,q,t) local top,x,m,Q,f;
  if nops(X)=0 then RETURN(m0) fi;
  top:=X minus map(e->op(1,e),P); f:=0;
  for x in top do
    if x>x0 then m:=q^nops(X)*t*m0 else m:=m0 fi;
    Q:=map(proc(e,y) if e[2]<>y then e fi end,P,x);
    f:=f+procname(Q,X minus {x},x,m,q,t);
  od; f
end:
#
`posets/W/ideals`:=proc(P,X,V,q,t) local down,R,f,n;
  n:=nops(X);
  if 2*nops(V)>nops(P) or n=0 then
    down:=`posets/labtab`(P,X,V,'R');
    f:=`posets/flagtool`(down,R,(r,w,z)->z/w^r,(r,w,z)->1-z/w^r,q,q^n*t);
  else
    down:=`posets/labtab`(P,X,P minus V,'R');
    f:=t*`posets/flagtool`(down,R,1,(r,w,z)->z/w^r-1,q,q^n*t);
  fi;
  expand(q^n*f)
end:
#
# Special voodoo for fast counting of extensions (q=t=1).
#
`posets/W/count`:=proc(P,n) local X,up,m,j,ct;
  X:=map(op,P); up:=posets['J'](P,X,'table');
  m:=nops([indices(up)]); up[m]:=1;
  while m>1 do
    m:=m-1; ct:=0;
    for j in up[m] do ct:=ct+up[j] od; up[m]:=ct;
  od;
  for m from nops(X)+1 to n do up[1]:=m*up[1] od; up[1]
end:
#
save `posets/W`, `posets/W/linear`, `posets/W/ideals`, `posets/W/count`,
  cat(HomeLib,`/posets/W.m`);
read cat(HomeLib,`/help/posets/W`);
quit;

