#
# mobius(P,X) returns a 'sparse' table of values for the mobius function
#  of the poset P with vertex set X.
# mobius(P,n) does the same but assumes X={1,...,n}.
# mobius(P)   does the same, but assumes there are no isolated vertices. 
# mobius(P,[a,b]) returns the value of the mobius function at [a,b].
# mobius(P,X,[a,b]) and mobius(P,n,[a,b]) function similarly.
#
`posets/mobius`:=proc() local P,X,x,y,z,down,mu,n;
  n:=nargs; P:=args[1];
  if type(args[n],'list') then
    if args[n][1]=args[n][2] then RETURN(1) fi;
    P:=posets['subinterval'](args);
    if P=NULL then RETURN(0) else X:=map(op,P) fi;
  elif n>2 then ERROR(`invalid arguments`)
  else X:=args[2..n] fi;
  X:=map(op,posets['filter'](P,X));
  down:=`posets/downsets`(P,X);
  if type(args[n],'list') then
    mu:=table([X[1]=1]); X:=subsop(1=NULL,X);
    for x in X do mu[x]:=-convert([seq(mu[y],y=down[x])],`+`) od
  else
    mu:=table('sparse');
    for x in X do mu[x,x]:=1;
      for y in down[x] do
        mu[y,x]:=-convert([seq(mu[y,z],z=down[x])],`+`)
      od
    od; op(mu)
  fi
end:
#
save `posets/mobius`, cat(HomeLib,`/posets/mobius.m`);
read cat(HomeLib,`/help/posets/mobius`);
quit;

