
/* This file defines TrigSimpCombine. TrigSimpCombine is designed to
   simplify expressions like Cos(a)*Sin(b) to additions
   only (in effect, removing multiplications between
   trigonometric functions).

   The accepted expressions allow additions and multiplications
   between trig. functions, and raising trig. functions to an
   integer power.

   You can invoke it by calling TrigSimpCombine(f). Examples:
	TrigSimpCombine(Cos(a)*Sin(a^2+b)^2)
	TrigSimpCombine(Cos(a)*Sin(a)^2)
	TrigSimpCombine(Cos(a)^3*Sin(a)^2)
	TrigSimpCombine(d*Cos(a)^3*Sin(a)^2)
	TrigSimpCombine(Cos(a)^3*Sin(a)^2)
	TrigSimpCombine(Cos(a)*Sin(a))
	TrigSimpCombine(Cos(a)*Sin(b)*Cos(c))
   
 */


/* FSin, FCos and :*: are used for the internal representation
   of the expression to work on:
   - a*b -> a:*:b   this is used because we want to expand powers,
     without the standard engine collapsing them back again.
   - a*Sin(b) -> FSin(a,b) and a*Cos(b) -> FCos(a,b). This makes
     adding and multiplying expressions with trig. functions, non-trig.
     functions, constants, etc. a lot easier.
*/
RuleBase("FSin",{f,x});
RuleBase("FCos",{f,x});
RuleBase(":*:",{x,y});
Infix(":*:",3);


IsTrig(f) := (Type(f) = "Sin" Or Type(f) = "Cos");
IsFTrig(f) := (Type(f) = "FSin" Or Type(f) = "FCos");
IsMul(f) := (Type(f) = "*");
IsMulF(f) := (Type(f) = ":*:");

IsPow(f):=
  (Type(f) = "^" And
   IsInteger(f[2]) And
   f[2] > 1
  );


/* Convert Sin/Cos to FSin/FCos */
RuleBase("TrigChange",{f});
Rule("TrigChange",1,1,Type(f)="Cos") FCos(1,f[1]);
Rule("TrigChange",1,1,Type(f)="Sin") FSin(1,f[1]);

/* Do a full replacement to internal format on a term. */
RuleBase("FReplace",{f});
UnFence("FReplace",1);
Rule("FReplace",1,1,IsMul(f))  Substitute(f[1]) :*: Substitute(f[2]);
Rule("FReplace",1,2,IsPow(f))  (Substitute(f[1]) :*: Substitute(f[1])) :*: Substitute(f[1]^(f[2]-2));
Rule("FReplace",1,3,IsTrig(f)) TrigChange(f);
FTest(f):=(IsMul(f) Or IsPow(f) Or IsTrig(f));

/* Central function that converts to internal format */
FToInternal(f):=Substitute(f,"FTest","FReplace");

FReplaceBack(f):=(Substitute(f[1])*Substitute(f[2]));
UnFence("FReplaceBack",1);
FFromInternal(f):=Substitute(f,"IsMulF","FReplaceBack");


/* FLog(s,f):=[WriteString(s:" ");Write(f);NewLine();]; */
 FLog(s,f):=[]; 


/* FSimpTerm simplifies the current term, wrt. trigonometric functions. */
RuleBase("FSimpTerm",{f,rlist});
UnFence("FSimpTerm",2);

/* Addition: add all the subterms */
Rule("FSimpTerm",2,1,Type(f) = "+")
[
  Local(result,lst);
  lst:=Flatten(f,"+");

  result:={{},{}};
FLog("simpadd",lst);

  ForEach(tt,lst)
  [
    Local(new);
    new:=FSimpTerm(tt,{{},{}});
    result:={Concat(result[1],new[1]),Concat(result[2],new[2])};
  ];
  result;
];


TrigNegate(f):=
[
  UnList({f[0],-(f[1]),f[2]});
];

Rule("FSimpTerm",2,1,Type(f) = "-" And NrArgs(f)=1)
[
  Local(result);
  result:=FSimpTerm(f[1],{{},{}});
  Substitute(result,"IsFTrig","TrigNegate");
];
Rule("FSimpTerm",2,1,Type(f) = "-" And NrArgs(f)=2)
[
  Local(result1,result2);
  result1:=FSimpTerm(f[1],{{},{}});
  result2:=FSimpTerm(-(f[2]),{{},{}});
  {Concat(result1[1],result2[1]),Concat(result1[2],result2[2])};
];

Rule("FSimpTerm",2,2,Type(f) = ":*:")
[
  FSimpFactor({Flatten(f,":*:")});
];
Rule("FSimpTerm",2,3,Type(f) = "FSin")
[
  {rlist[1],f:(rlist[2])};
];
Rule("FSimpTerm",2,3,Type(f) = "FCos")
[
  {f:(rlist[1]),rlist[2]};
];

Rule("FSimpTerm",2,4,True)
[
  {(FCos(f,0)):(rlist[1]),rlist[2]};
];

/* FSimpFactor does the difficult part. it gets a list, representing
   factors, a*b*c -> {{a,b,c}}, and has to add terms from it.
   Special cases to deal with:
   - (a+b)*c -> a*c+b*c -> {{a,c},{b,c}}
   - {a,b,c} where one of them is not a trig function or an addition:
     replace with FCos(b,0), which is b*Cos(0) = b
   - otherwise, combine two factors and make them into an addition.
   - the lists should get shorter, but the number of lists should
     get longer, until there are only single terms to be added.
 */
FSimpFactor(flist):=
[
  Local(rlist);
  rlist:={{},{}};
  /* Loop over each term */
  While(flist != {})
  [
    Local(term);
FLog("simpfact",flist);
    term:=Head(flist);
    flist:=Tail(flist);
    FProcessTerm(term);
  ];
FLog("simpfact",flist);

FLog("rlist",rlist);
  rlist;
];
UnFence("FSimpFactor",1);


RuleBase("FProcessTerm",{t});
UnFence("FProcessTerm",1);

/* Deal with (a+b)*c -> a*c+b*c */
Rule("FProcessTerm",1,1,Type(t[1]) = "+")
[
  Local(split,term1,term2);
  split:=t[1];
  term1:=FlatCopy(t);
  term2:=FlatCopy(t);
  term1[1]:=split[1];
  term2[1]:=split[2];
  DestructiveInsert(flist,1,term1);
  DestructiveInsert(flist,1,term2);
];
Rule("FProcessTerm",1,1,Type(t[1]) = "-" And NrArgs(t[1]) = 2)
[
  Local(split,term1,term2);
  split:=t[1];
  term1:=FlatCopy(t);
  term2:=FlatCopy(t);
  term1[1]:=split[1];
  term2[1]:=split[2];
  DestructiveInsert(term2,1,FCos(-1,0));
  DestructiveInsert(flist,1,term1);
  DestructiveInsert(flist,1,term2);
];

Rule("FProcessTerm",1,1,Length(t)>1 And Type(t[2]) = "-" And NrArgs(t[2]) = 2)
[
  Local(split,term1,term2);
  split:=t[2];
  term1:=FlatCopy(t);
  term2:=FlatCopy(t);
  term1[2]:=split[1];
  term2[2]:=split[2];
  DestructiveInsert(term2,1,FCos(-1,0));
  DestructiveInsert(flist,1,term1);
  DestructiveInsert(flist,1,term2);
];

Rule("FProcessTerm",1,1,Type(t[1]) = ":*:")
[
  Local(split,term);
  split:=t[1];
  term:=FlatCopy(t);
  term[1]:=split[1];
  DestructiveInsert(term,1,split[2]);
  DestructiveInsert(flist,1,term);
];

Rule("FProcessTerm",1,1,Length(t)>1 And Type(t[2]) = ":*:")
[
  Local(split,term);
  split:=t[2];
  term:=FlatCopy(t);
  term[2]:=split[1];
  DestructiveInsert(term,1,split[2]);
  DestructiveInsert(flist,1,term);
];

Rule("FProcessTerm",1,1,Type(t[1]) = "-" And NrArgs(t[1]) = 1)
[
  Local(split,term);
  split:=t[1];
  term:=FlatCopy(t);
  term[1]:=split[1];
  DestructiveInsert(term,1,FCos(-1,0));
  DestructiveInsert(flist,1,term);
];
Rule("FProcessTerm",1,1,Length(t)>1 And Type(t[2]) = "-" And NrArgs(t[2]) = 1)
[
  Local(split,term);
  split:=t[2];
  term:=FlatCopy(t);
  term[2]:=split[1];
  DestructiveInsert(term,1,FCos(-1,0));
  DestructiveInsert(flist,1,term);
];


/* Deal with (a*(b+c) -> a*b+a*c */
Rule("FProcessTerm",1,1,Length(t)>1 And Type(t[2]) = "+")
[
  Local(split,term1,term2);
  split:=t[2];
  term1:=FlatCopy(t);
  term2:=FlatCopy(t);
  term1[2]:=split[1];
  term2[2]:=split[2];
  DestructiveInsert(flist,1,term1);
  DestructiveInsert(flist,1,term2);
];



/* Deal with a*FCos(1,b) ->FCos(a,0)*FCos(1,b) */
Rule("FProcessTerm",1,2,Not(IsFTrig(t[1])) )
[
  t[1]:=FCos(t[1],0);
  DestructiveInsert(flist,1,t);
];
Rule("FProcessTerm",1,2,Length(t)>1 And Not(IsFTrig(t[2])) )
[
  t[2]:=FCos(t[2],0);
  DestructiveInsert(flist,1,t);
];


Rule("FProcessTerm",1,4,Length(t)=1 And Type(t[1]) = "FCos") 
[
  DestructiveInsert(rlist[1],1,t[1]);
];
Rule("FProcessTerm",1,4,Length(t)=1 And Type(t[1]) = "FSin") 
[
  DestructiveInsert(rlist[2],1,t[1]);
];

/* Now deal with the real meat: FSin*FCos etc. Reduce the multiplication
   of the first two terms to an addition, adding two new terms to
   the pipe line.
 */
Rule("FProcessTerm",1,5,Length(t)>1)
[
  Local(x,y,term1,term2,news);
  x:=t[1];
  y:=t[2];
  news:=TrigSimpCombineB(x,y);
  /* Drop one term */
  t:=Tail(t);
  term1:=FlatCopy(t);
  term2:=FlatCopy(t);
  term1[1]:=news[1];
  term2[1]:=news[2];
  DestructiveInsert(flist,1,term1);
  DestructiveInsert(flist,1,term2);
];

/* TrigSimpCombineB : take two FSin/FCos factors, and write them out into two terms */
RuleBase("TrigSimpCombineB",{x,y});
Rule("TrigSimpCombineB",2,1,Type(x) = "FCos" And Type(y) = "FCos")
     { FCos((x[1]*y[1])/2,x[2]+y[2]) , FCos((x[1]*y[1])/2,x[2]-y[2]) };
Rule("TrigSimpCombineB",2,1,Type(x) = "FSin" And Type(y) = "FSin")
     { FCos(-(x[1]*y[1])/2,x[2]+y[2]) , FCos((x[1]*y[1])/2,x[2]-y[2]) };
Rule("TrigSimpCombineB",2,1,Type(x) = "FSin" And Type(y) = "FCos")
     { FSin((x[1]*y[1])/2,x[2]+y[2]) , FSin( (x[1]*y[1])/2,x[2]-y[2]) };
Rule("TrigSimpCombineB",2,1,Type(x) = "FCos" And Type(y) = "FSin")
     { FSin((x[1]*y[1])/2,x[2]+y[2]) , FSin(-(x[1]*y[1])/2,x[2]-y[2]) };


RuleBase("TrigSimpCombine",{f});
Rule("TrigSimpCombine",1,1,IsList(f))
  Map("TrigSimpCombine",{f});

Rule("TrigSimpCombine",1,10,True)
[
  Local(new,varlist);
  new:=f;

  /* varlist is used for normalizing the trig. arguments */
  varlist:=VarList(f);
  
/* Convert to internal format. */
  new:=FToInternal(new);
FLog("Internal",new);

  /* terms will contain FSin/FCos entries, the final result */

  /* rlist gathers the true final result */
  Local(terms);
  terms:=FSimpTerm(new,{{},{}});
  /* terms now contains two lists: terms[1] is the list of cosines,
     and terms[2] the list of sines.
   */
FLog("terms",terms);

  /* cassoc and sassoc will contain the assoc lists with the cos/sin
     arguments as key.
   */
  Local(cassoc,sassoc);
  cassoc:={};
  sassoc:={};
  ForEach(item,terms[1])
  [
    CosAdd(item);
  ];
  ForEach(item,terms[2])
  [
    SinAdd(item);
  ];
FLog("cassoc",cassoc);
FLog("sassoc",sassoc);

  /* Now rebuild the normal form */
  Local(result);
  result:=0;
  ForEach(item,cassoc)
  [
Log("item",item);
    result:=result+Expand(item[2])*Cos(item[1]);
  ];
  ForEach(item,sassoc)
  [
Log("item",item);
    result:=result+Expand(item[2])*Sin(item[1]);
  ];

  result;
];



CosAdd(t):=
[
  Local(look,arg);
  arg:=Expand(t[2],varlist);
  look:=Assoc(arg,cassoc);
  If(look = Empty,
     [
       arg:=Expand(-arg,varlist);
       look:=Assoc(arg,cassoc); 
       If(look = Empty,
         DestructiveInsert(cassoc,1,{arg,t[1]}),
         look[2]:=look[2]+t[1]
         );
     ]
     ,
     look[2]:=look[2]+t[1]
    );
];
UnFence("CosAdd",1);

SinAdd(t):=
[
  Local(look,arg);
  arg:=Expand(t[2],varlist);
  look:=Assoc(arg,sassoc);
  If(look = Empty,
     [
       arg:=Expand(-arg,varlist);
       look:=Assoc(arg,sassoc);
       If(look = Empty,
         DestructiveInsert(sassoc,1,{arg,-(t[1])}),
	 look[2]:=look[2]-(t[1])
         );
     ]
     ,
     look[2]:=look[2]+t[1]
    );
];
UnFence("SinAdd",1);


/*
In( 4 ) = Exp(I*a)*Exp(I*a)      
Out( 4 ) = Complex(Cos(a)^2-Sin(a)^2,Cos(a)*Sin(a)+Sin(a)*Cos(a));
In( 5 ) = Exp(I*a)*Exp(-I*a)     
Out( 5 ) = Complex(Cos(a)^2+Sin(a)^2,Sin(a)*Cos(a)-Cos(a)*Sin(a));

In( 5 ) = Exp(I*a)*Exp(I*b) 
Out( 5 ) = Complex(Cos(a)*Cos(b)-Sin(a)*Sin(b),Cos(a)*Sin(b)+Sin(a)*Cos(b));
In( 6 ) = Exp(I*a)*Exp(-I*b) 
Out( 6 ) = Complex(Cos(a)*Cos(b)+Sin(a)*Sin(b),Sin(a)*Cos(b)-Cos(a)*Sin(b));


*/

