JuliaSymbolics / SymbolicUtils.jl

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

Scope of `@rule` matcher #460

Open bowenszhu opened 1 year ago

bowenszhu commented 1 year ago

This is a simple script which tries to reverse the differential operators.

using Symbolics, SymbolicUtils.Rewriters
@variables x, t, f(x, t)
Dx = Differential(x)
Dt = Differential(t)
rule = @rule Dt(Dx(~g)) => Dx(Dt(~g))
rewriter = Chain([rule])
func = Symbolics.value(Dt(Dx(f)))
rewriter(func)

the result is good: Differential(x)(Differential(t)(f(x, t)))

However, if we place the entire code in a function,

using Symbolics, SymbolicUtils.Rewriters
function main()
    @variables x, t, f(x, t)
    Dx = Differential(x)
    Dt = Differential(t)
    rule = @rule Dt(Dx(~g)) => Dx(Dt(~g))
    rewriter = Chain([rule])
    func = Symbolics.value(Dt(Dx(f)))
    rewriter(func)
end

r = main()

the result is different and the rewritter fails to match the pattern: Differential(t)(Differential(x)(f(x, t)))

Then we put the construction of Dt and Dx out of the function, it works again.

using Symbolics, SymbolicUtils.Rewriters
@variables x, t, f(x, t)
Dx = Differential(x)
Dt = Differential(t)
function main()
    rule = @rule Dt(Dx(~g)) => Dx(Dt(~g))
    rewriter = Chain([rule])
    func = Symbolics.value(Dt(Dx(f)))
    rewriter(func)
end

r = main()

result: Differential(x)(Differential(t)(f(x, t)))

Version: julia v1.7.3 SymbolicUtils v0.19.11 Symbolics v4.10.3

willow-ahrens commented 1 year ago

This might be https://github.com/JuliaSymbolics/SymbolicUtils.jl/issues/394, which is really (https://github.com/JuliaSymbolics/Metatheory.jl/issues/87)

0x0f0f0f commented 1 year ago

Addressed by #486

bowenszhu commented 1 year ago

Great. I tested the following on Metatheory branch 2.0.0-DEV commit https://github.com/JuliaSymbolics/Metatheory.jl/commit/6cedf96d673b6702e308094b1e30173153729f14 and SymbolicUtils branch ale/mt2 commit https://github.com/JuliaSymbolics/SymbolicUtils.jl/commit/b103a9d63d8cfd9fd817b77d99fcb92fb2b69943.

using Symbolics, SymbolicUtils.Rewriters
function main()
    @variables x, t, f(x, t)
    Dx = Differential(x)
    Dt = Differential(t)
    rule = @rule Dt(Dx(~g)) => Dx(Dt(~g))
    rewriter = Chain([rule])
    func = Symbolics.value(Dt(Dx(f)))
    rewriter(func)
end

r = main()

it correctly returns Differential(x)(Differential(t)(f(x, t))).

I will close this issue once PR https://github.com/JuliaSymbolics/SymbolicUtils.jl/pull/486 is merged.

0x0f0f0f commented 1 year ago

@bowenszhu Note that Metatheory.jl is no longer used in SymbolicUtils.jl :(