I am trying to use SymbollicUtils.jl
s rewriting functionality to bring trigonometric expressions into a canonical form. Namely, I want to expand sin/cos of sums into products of sins/coss. The rules that I define work as expected when applied to simple terms, but fail to expand e.g. individual factors in a product. I also tried Rewriters.Prewalk
and Rewriters.Postwalk
to traverse the expression tree and try to rewrite all nodes of the tree, but this also failed. See the following MWE for what I am trying to achieve:
using Symbolics, SymbolicUtils
x, y = @syms x::Real y::Real
sinrule = @acrule sin(~x + ~y) => (sin(~x) * cox(~y) + cos(~x) * sin(~y))
sinsignrule = @acrule sin(-1*(~x)) => -sin(~x)
cossignrule = @acrule cos(-1*(~x)) => cos(~x)
ex0 = sin(x - y)
ex1 = sinrule(ex0)
# sin(x) * cos(y) + cos(x) * sin(-y), so this works
ex2 = cossignrule(ex1)
# nothing, so this fails
ex2 = sinsignrule(ex1)
# nothing, this fails too
sinsignrule(sin(-x))
# -sin(x), the rule works in isolation
Rewriters.Prewalk(sinsignrule)(ex1)
# nothing, this also fails. Same with Postwalk
Ideally I would like to create a list of all trig expnansion rules and then do something along the lines of
myrules = [sinrule, cosrule, sinsignrule, cossignrule]
ex = sin(x-y+c) * cos(a+b) + ...
ex_expanded = Rewriters.Fixpoint(
Rewriters.Prewalk(
Rewriters.Chain(myrules)
)
)(ex)
and then get a fully expanded sum of products of trigonometric functions of only one variable.