#
# fastW(P,X,t,<options>) computes the W-polynomial of the poset P,X,
#  using the quadratic 'ideals' algorithm.
# optional arguments (in any order):
#    ideals   - a list of order ideals of (P,X), sorted by increasing size
#  'enriched' - compute the enriched W-polynomial instead
#      V      - (a subset of P) compute the W-polynomial relative to a
#               labeling in which descents occur at the edges of V.
#
# We do not check if V is admissible.

fastW:=proc(P,X,t) local V,Y,i,anti,flag;
  if type(X,'integer') then Y:={$1..X} else Y:=X fi;
  anti:=0; flag:=true; V:={};
  for i from 4 to nargs do
    if args[i]='enriched' then flag:=false
      elif type(args[i],'set') then V:=args[i]
      elif type(args[i],'list') then anti:=args[i]
      else ERROR(`invalid options`)
    fi
  od;
  if anti=0 then anti:=`fastW/ideals`(P,Y) fi;
  if flag then `fastW/ordinary`(anti,V,nops(Y),t)
    else `fastW/enriched`(anti,P minus V,V,nops(Y),t) fi
end;

# generate the list of order ideals of P, sorted by increasing size

`fastW/ideals`:=proc(P,X) local down,Q,i,j,A,anti;
  down:=posets['closure'](P,X,'table');
  Q:={seq(seq([i,j],i=down[j]),j=X)};
  anti:=posets['antichains'](Q,X,true);
  anti:=[seq({op(A),seq(op(down[i]),i=A)},A=anti)];
  sort(anti,(x,y)->evalb(nops(x)<nops(y)))
end:

# the usual W-polynomial

`fastW/ordinary`:=proc(anti,V,n,t) local m,res,i,j,k,C;
  m:=nops(anti); res:=table([1=1]);
  for i from 2 to m do res[i]:=0;
    for j to i-1 do
      k:=nops(anti[i])-nops(anti[j]);
      C:=anti[i] minus anti[j];
      if nops(C)<>k then next fi;
      if `fastW/admit`(C,V) then res[i]:=res[i]+res[j] fi
    od;
    res[i]:=expand(t*res[i]);
  od;
  res:=res[m];
  res:=[seq(coeff(res,t,i)*t^i*(1-t)^(n-i),i=0..n)];
  expand(convert(res,`+`));
end:

# the enriched W-polynomial

`fastW/enriched`:=proc(anti,U,V,n,t) local m,f,res,i,j,k,C,new;
  m:=nops(anti);
  res:=table([1=1]); new:=table([1=1]);
  for i from 2 to m do
    res[i]:=0; new[i]:=0;
    for j to i-1 do
      k:=nops(anti[i])-nops(anti[j]);
      C:=anti[i] minus anti[j];
      if nops(C)<>k then next fi;
      if k=1 or `fastW/admit`(C,U) then new[i]:=new[i]+res[j] fi;
      if k=1 or `fastW/admit`(C,V) then res[i]:=res[i]+new[j] fi;
    od;
    res[i]:=expand(t*(res[i]+new[i]));
    new[i]:=new[i]+res[i];
  od;
  f:=res[m]; f:=[seq(coeff(f,t,i)*(1-t)^i*t^(n-i)/2^i,i=0..n)];
  f:=expand((1+t)*convert(f,`+`));
  if f<>subs(t=-t,f) then ERROR(`this cannot happen`) fi;
  expand(convert([seq(coeff(f,t,2*i)*(1-t)^i,i=0..(n+1)/2)],`+`));
end:

`fastW/admit`:=proc(C,V) local e;
  for e in V do
    if member(e[1],C) and member(e[2],C) then RETURN(false) fi;
  od; true
end:

