Skip to content

Commit

Permalink
Merge pull request #265 from jverzani/symbolic-utils-extension
Browse files Browse the repository at this point in the history
Symbolic utils extension
  • Loading branch information
isuruf authored Sep 14, 2023
2 parents dde2542 + c9a219c commit 71c1e71
Show file tree
Hide file tree
Showing 4 changed files with 167 additions and 1 deletion.
9 changes: 8 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b"
SymEngine_jll = "3428059b-622b-5399-b16f-d347a77089a4"

[weakdeps]
SymbolicUtils = "d1185830-fcd6-423d-90d6-eec64667417b"

[extensions]
SymEngineSymbolicUtilsExt = "SymbolicUtils"

[compat]
Compat = "0.63.0, 1, 2, 3, 4"
RecipesBase = "0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0"
Expand All @@ -20,6 +26,7 @@ julia = "1.6"

[extras]
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
SymbolicUtils = "d1185830-fcd6-423d-90d6-eec64667417b"

[targets]
test = ["Test"]
test = ["SymbolicUtils", "Test"]
104 changes: 104 additions & 0 deletions ext/SymEngineSymbolicUtilsExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
module SymEngineSymbolicUtilsExt

using SymEngine
using SymbolicUtils
import SymEngine: SymbolicType

#
function is_number(a::SymEngine.Basic)
cls = SymEngine.get_symengine_class(a)
any(==(cls), SymEngine.number_types) && return true
false
end


λ(x::SymEngine.SymbolicType) = λ(Val(SymEngine.get_symengine_class(x)))
λ(::Val{T}) where {T} = getfield(Main, Symbol(lowercase(string(T))))

λ(::Val{:Add}) = +; λ(::Val{:Sub}) = -
λ(::Val{:Mul}) = *; λ(::Val{:Div}) = /
λ(::Val{:Pow}) = ^
λ(::Val{:re}) = real; λ(::Val{:im}) = imag
λ(::Val{:Abs}) = abs
λ(::Val{:Log}) = log
λ(::Val{:Sin}) = sin; λ(::Val{:Cos}) = cos; λ(::Val{:Tan}) = tan
λ(::Val{:Csc}) = csc; λ(::Val{:Sec}) = sec; λ(::Val{:Cot}) = cot
λ(::Val{:Asin}) = asin; λ(::Val{:Acos}) = acos; λ(::Val{:Atan}) = atan
λ(::Val{:Acsc}) = acsc; λ(::Val{:Asec}) = asec; λ(::Val{:Acot}) = acot
λ(::Val{:Sinh}) = sinh; λ(::Val{:Cosh}) = cosh; λ(::Val{:Tanh}) = tanh
λ(::Val{:Csch}) = csch; λ(::Val{:Sech}) = sech; λ(::Val{:Coth}) = coth
λ(::Val{:Asinh}) = asinh; λ(::Val{:Acosh}) = acosh; λ(::Val{:Atanh}) = atanh
λ(::Val{:Acsch}) = acsch; λ(::Val{:Asech}) = asech; λ(::Val{:Acoth}) = acoth
λ(::Val{:Gamma}) = gamma; λ(::Val{:Zeta}) = zeta; λ(::Val{:LambertW}) = lambertw

#==
Check if x represents an expression tree. If returns true, it will be assumed that operation(::T) and arguments(::T) methods are defined. Definining these three should allow use of SymbolicUtils.simplify on custom types. Optionally symtype(x) can be defined to return the expected type of the symbolic expression.
==#
function SymbolicUtils.istree(x::SymEngine.SymbolicType)
cls = SymEngine.get_symengine_class(x)
cls == :Symbol && return false
any(==(cls), SymEngine.number_types) && return false
return true
end

SymbolicUtils.issym(x::SymEngine.SymbolicType) = SymEngine.get_symengine_class(x) == :Symbol
Base.nameof(x::SymEngine.SymbolicType) = Symbol(x)

# no metadata(x), metadata(x, data)

#==
Returns the head (a function object) performed by an expression tree. Called only if istree(::T) is true. Part of the API required for simplify to work. Other required methods are arguments and istree
==#
function SymbolicUtils.operation(x::SymEngine.SymbolicType)
istree(x) || error("$(typeof(x)) doesn't have an operation!")
return λ(x)
end


#==
Returns the arguments (a Vector) for an expression tree. Called only if istree(x) is true. Part of the API required for simplify to work. Other required methods are operation and istree
==#
function SymbolicUtils.arguments(x::SymEngine.SymbolicType)
get_args(x)
end

#==
Construct a new term with the operation f and arguments args, the term should be similar to t in type. if t is a SymbolicUtils.Term object a new Term is created with the same symtype as t. If not, the result is computed as f(args...). Defining this method for your term type will reduce any performance loss in performing f(args...) (esp. the splatting, and redundant type computation). T is the symtype of the output term. You can use SymbolicUtils.promote_symtype to infer this type. The exprhead keyword argument is useful when creating Exprs.
==#
function SymbolicUtils.similarterm(t::SymEngine.SymbolicType, f, args, symtype=nothing;
metadata=nothing, exprhead=:call)
f(args...) # default
end

# Needed for some simplification routines
# a total order <ₑ
import SymbolicUtils: <ₑ, isterm, isadd, ismul, issym, cmp_mul_adds, cmp_term_term
function SymbolicUtils.:<(a::SymEngine.Basic, b::SymEngine.Basic)
if isterm(a) && !isterm(b)
return false
elseif isterm(b) && !isterm(a)
return true
elseif (isadd(a) || ismul(a)) && (isadd(b) || ismul(b))
return cmp_mul_adds(a, b)
elseif issym(a) && issym(b)
nameof(a) < nameof(b)
elseif !istree(a) && !istree(b)
T = typeof(a)
S = typeof(b)
if T == S
is_number(a) && is_number(b) && return N(a) < N(b)
return hash(a) < hash(b)
else
return name(T) < nameof(S)
end
#return T===S ? (T <: Number ? isless(a, b) : hash(a) < hash(b)) : nameof(T) < nameof(S)
elseif istree(b) && !istree(a)
return true
elseif istree(a) && istree(b)
return cmp_term_term(a,b)
else
return !(b <ₑ a)
end
end

end
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ using Test
using Serialization
import Base: MathConstants.γ, MathConstants.e, MathConstants.φ, MathConstants.catalan

VERSION >= v"1.9" && include("test-SymbolicUtils.jl")
include("test-dense-matrix.jl")

x = symbols("x")
Expand Down
54 changes: 54 additions & 0 deletions test/test-SymbolicUtils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Test
using SymEngine
import SymbolicUtils: simplify, @rule, @acrule, Chain, Fixpoint


@testset "SymbolicUtils" begin
# from SymbolicUtils.jl docs
# https://symbolicutils.juliasymbolics.org/rewrite/#rule-based_rewriting
@vars w x y z
@vars α β
@vars a b c d

@test simplify(cos(x)^2 + sin(x)^2) == 1

r1 = @rule sin(2(~x)) => 2sin(~x)*cos(~x)
@test r1(sin(2z)) == 2*cos(z)*sin(z)
@test r1(sin(3z)) === nothing
@test r1(sin(2*(w-z))) == 2cos(w - z)*sin(w - z)
@test r1(sin(2*(w+z)*+β))) === nothing

r2 = @rule sin(~x + ~y) => sin(~x)*cos(~y) + cos(~x)*sin(~y);
@test r2(sin+β)) == sin(α)*cos(β) + cos(α)*sin(β)

xs = @rule(+(~~xs) => ~~xs)(x + y + z) # segment variable
@test Set(xs) == Set([x,y,z])

r3 = @rule ~x * +(~~ys) => sum(map(y-> ~x * y, ~~ys));
@test r3(2 * (w+w+α+β)) == 4w + 2α + 2β

r4 = @rule ~x + ~~y::(ys->iseven(length(ys))) => "odd terms"; # Predicates for matching

@test r4(a + b + c + d) == nothing
@test r4(b + c + d) == "odd terms"
@test r4(b + c + b) == nothing
@test r4(a + b) == nothing

sqexpand = @rule (~x + ~y)^2 => (~x)^2 + (~y)^2 + 2 * ~x * ~y
@test sqexpand((cos(x) + sin(x))^2) == cos(x)^2 + sin(x)^2 + 2cos(x)*sin(x)

pyid = @rule sin(~x)^2 + cos(~x)^2 => 1
@test_broken pyid(cos(x)^2 + sin(x)^2) === nothing # order should matter, but this works

acpyid = @acrule sin(~x)^2 + cos(~x)^2 => 1 # acrule is commutative
@test acpyid(cos(x)^2 + sin(x)^2 + 2cos(x)*sin(x)) == 1 + 2cos(x)*sin(x)

csa = Chain([sqexpand, acpyid]) # chain composes rules
@test csa((cos(x) + sin(x))^2) == 1 + 2cos(x)*sin(x)

cas = Chain([acpyid, sqexpand]) # order matters
@test cas((cos(x) + sin(x))^2) == cos(x)^2 + sin(x)^2 + 2cos(x)*sin(x)

@test Fixpoint(cas)((cos(x) + sin(x))^2) == 1 + 2cos(x)*sin(x)

end

0 comments on commit 71c1e71

Please sign in to comment.