#
# toQ(f,<options>) will convert a symmetric function f in the omega algebra
# into a sum of Q-functions. <options> is a sequence of zero or more of the
# following expressions (in any order):
# (1) a list of partitions that support the Q-function expansion of f.
# (2) an equation 'nrows=<integer>', where <integer> is a positive integer
#     that specifies that all calculations should take place in the ring
#     spanned by Q-functions with at most <integer> rows.
# (3) a name 'b' that specifies a basis f is expressed in.
#
# WARNING: the code for (2) is experimental. It could fail to find an
#  answer when combined with (1) in rare (unknown) ways.
#
`QF/toQ`:=proc() local f,opt,nrows,vars,sp,ser,n,c,d,eqs,res,j,t;
  f:=args[1]; nrows:=0;
  for opt in [args[2..nargs]] do
    if type(opt,'list') then sp:=opt
      elif type(opt,`=`) then nrows:=op(2,opt)
      elif type(opt,'name') then f:=f,opt
    fi
  od;
  f:=QF['toq'](f); d:=SF['stdeg'](f,'q');
  vars:=[seq(cat('q',j),j=1..d)];
  if not assigned(sp) then
    f:=map(x->op(1,x),`SF/homog_cmps`(f,'q'));
    f:=map(`QF/toQ`,f,'q',args[2..nargs],[]);
    RETURN(convert(f,`+`))
  elif nrows>0 then
    nrows:=min(nrows,degree(f,{op(vars)}));
    if sp=[] then sp:=QF['DPar'](d,nrows)
      else sp:=map(proc(x,y) if nops(x)<=y then x fi end,sp,nrows) fi;
    n:=nops(sp); eqs:=NULL;
    res:=convert([seq(c[j]*Q[op(sp[j])],j=1..n)],`+`);
    sp:=map(proc(x) subsop(1=1,x) end,sp);
    f:=QF['toq'](res-f,'Q[]');
    for opt in sp do
      ser:=taylor(convert([seq((1+j*t)/(1-j*t),j=opt)],`*`),t,d+1);
      eqs:=eqs,subs({seq(cat('q',j)=coeff(ser,t,j),j=1..d)},f);
    od;
  else
    if sp=[] then sp:=QF['DPar'](d,degree(f,{op(vars)})) fi;
    n:=nops(sp); res:=convert([seq(c[j]*Q[op(sp[j])],j=1..n)],`+`);
    f:=QF['toddq'](res-f,'Q[]');
    eqs:=coeffs(f,vars);
  fi;
  eqs:=`QF/linsolve`({eqs},{seq(c[j],j=1..n)});
  subs(map(normal,eqs),res);
end:
#
save `QF/toQ`, cat(HomeLib,`/QF/toQ.m`);
read cat(HomeLib,`/help/QF/toQ`);
quit;

