Symbolics.jl rewrite rule

I defined the following rule:

rlogexp = @rule log(exp(~x)) => ~x

This seems to work for simple expressions:

> simplify(log(exp(x+3)), rewriter=rlogexp) 
3+x

However, this doesn’t seem to simplify

> simplify(log(exp(x))+3, rewriter=rlogexp)
log(exp(x))+3

What am I doing wrong?

Hi, in the example you provided, the simplify function attempts to apply the rule once to the entire expression. If the entire expression doesn’t match the rule, it won’t be simplified.

To apply the rule from the bottom of the expression to the top, you can use the SymbolicUtils package and construct a custom rewriter. For instance:

using Symbolics
using SymbolicUtils.Rewriters

# Define the rule
rlogexp = @rule log(exp(~x)) => ~x

# Create a rewriter chain and use Postwalk
rewriter = [rlogexp] |> Chain |> Postwalk

@variables x

# Apply the rewriter to the expression
simplified_expr = simplify(log(exp(x)) + 3, rewriter)

The output is

3 + x

1 Like