JuliaSymbolics / SymbolicUtils.jl

Symbolic expressions, rewriting and simplification
https://docs.sciml.ai/SymbolicUtils/stable/
Other
523 stars 99 forks source link

Rewrite-Rules with new Variables? #431

Open Zer0112 opened 2 years ago

Zer0112 commented 2 years ago

I like the straight forward rule-based rewriting approach. But I found no way to introduce new variables in the rewrite rules, which could be quite useful in some cases.

Something like:

x[1]x[2]x[3] = x[1]*(y_2_3)+Term(y_2_3,x[2],x[3])

In words: Replace all cubic polynomials with a quadratic one by introducing a new variable y and an additional Term. Preferably, the new variable name should reflect the variables it did replace.

Other examples: x[1]^2+x[2]^2 = (r_1_2)^2 x[1] = t^2

Is it somehow possible, or can it be added as a feature?

bowenszhu commented 1 year ago

Try something like the following

using SymbolicUtils, Symbolics
@syms x y z
dict = Dict()
quadratic_var(a, b) = get!(dict, a * b, Symbolics.variable(Symbol(nameof(a), nameof(b))))
quadratic = @rule (~a) * (~b) * (~c) => quadratic_var(~a, ~b) * (~c)
expr = x * y * z
res = quadratic(expr)

results:

julia> res
xy*z

julia> dict
Dict{Any, Any} with 1 entry:
  x*y => xy