Skip to content

Commit 2f5a796

Browse files
author
Alessandro
committed
custom similarterm for egraphs, update metatheory, fix preprocessing
1 parent afae1a4 commit 2f5a796

File tree

3 files changed

+23
-9
lines changed

3 files changed

+23
-9
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ DocStringExtensions = "0.8"
3636
DynamicPolynomials = "0.3"
3737
IfElse = "0.1"
3838
LabelledArrays = "1.5"
39-
Metatheory = "1.1"
39+
Metatheory = "1.2"
4040
MultivariatePolynomials = "0.3"
4141
NaNMath = "0.3"
4242
Setfield = "0.7, 0.8"

src/egraph.jl

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using Metatheory.Rewriters
22

3-
function EGraphs.preprocess(t)
4-
Chain([Postwalk(toterm), Postwalk(unflatten)])(t)
3+
function EGraphs.preprocess(t::Symbolic)
4+
toterm(unflatten(t))
55
end
66

77
function symbolicegraph(ex)
@@ -76,12 +76,26 @@ function costfun(n::ENodeTerm, g::EGraph, an)
7676
cost
7777
end
7878

79-
costfun(n::ENodeLiteral, g::EGraph, an) = 1
79+
costfun(n::ENodeLiteral, g::EGraph, an) = 0
8080

81+
egraph_simterm(x, head, args, symtype=nothing; metadata=nothing, exprhead=exprhead(x)) =
82+
TermInterface.similarterm(typeof(x), head, args, symtype; metadata=metadata, exprhead=exprhead)
83+
84+
85+
# Custom similarterm to use in EGraphs on <:Symbolic types that treats everything as a Term
86+
function egraph_simterm(x::Type{<:Term}, f, args, symtype=nothing; metadata=nothing, exprhead=:call)
87+
T = symtype
88+
if T === nothing
89+
T = _promote_symtype(f, args)
90+
end
91+
res = Term{T}(f isa Symbol ? eval(f) : f, args; metadata=metadata);
92+
return res
93+
end
8194

8295
function optimize(ex; params=SaturationParams(timeout=20))
8396
# @show ex
8497
g = symbolicegraph(ex)
98+
params.simterm = egraph_simterm
8599
saturate!(g, opt_theory, params)
86100
return extract!(g, costfun)
87101
end

test/egraph.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
using SymbolicUtils
2+
using Metatheory
23

34
sym_eq(x, y) = simplify(x == y)
4-
()(x, y) = sym_eq(x,y)
55

6-
@syms a b c x
76
@testset "Basic optimization" begin
87
ex = 2a + 2b - (a*(a + b))
98
res = optimize(ex)
10-
@test res (a+b)*(2-a)
9+
@test sym_eq(res, (a+b)*(2-a))
1110

1211
ex = sin(a^2)/cos(a^2)
1312
res = optimize(ex)
14-
@test isequal(res, tan(a^2)) # sym_eq does not work
13+
@test isequal(res, tan(a^2)) # sym_eq does not work
14+
# TODO report issue
1515

1616
ex = sin(1/x * (a * b + a * c))^2 + cos((a*(b+c))/x)^2
1717
res = optimize(ex)
1818
@test res == 1
19-
end
19+
end

0 commit comments

Comments
 (0)