#
# Implement a generic sum over flags (chains) in a ranked, bounded poset.
# In the input, 'down' should be a table of downsets for each vertex,
#  and R the rank partition of the vertex set. The blocks of R must be
#  listed in order of increasing rank.
# The arguments f and g should be procedures that compute weights to be
#  applied to each chain as follows: if a chain 0 < x < y < ... < 1
#  passes through ranks 0 < a < b < ... < r, and skips ranks c,d,...
#  then the weight of the chain is g(c)*g(d)*...*f(a)*f(b)*...*f(r).
# Any additional arguments supplied are passed on to f and g.
# By convention, the last rank in every chain is r=rank(1), so every
#  chain weight includes the factor f(r).
# When g=1 or g=1-f, the result is the flag f-vector or h-vector.
# Note that f(i) is called exactly once each for i=1..r,
#  and g(i) is called i times for i=1..r-1.
# We don't check that the poset actually is ranked or bounded.
#
`posets/flagtool`:=proc(down,R,f,g) local wt,rk,res,x,y,r,win;
  wt:=table(); rk:=table([R[1][1]=0]);
  res:=table([R[1][1]=1]);
  for r to nops(R)-1 do
    win:=f(r,args[5..nargs]); wt[r-1,r]:=1;
    for x in R[r+1] do
      rk[x]:=r; res[x]:=0;
      for y in down[x] do    
        if not assigned(wt[rk[y],r]) then
          wt[rk[y],r]:=wt[rk[y],r-1]*g(r-1,args[5..nargs]) fi;
        res[x]:=res[x]+res[y]*wt[rk[y],r]
      od;
      res[x]:=expand(res[x]*win);
    od;
  od; res[R[r][1]]
end:
#
save `posets/flagtool`, cat(HomeLib,`/posets/flagtool.m`);
quit;

