Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bring back TermInterface #598

Merged
merged 7 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "SymbolicUtils"
uuid = "d1185830-fcd6-423d-90d6-eec64667417b"
authors = ["Shashi Gowda"]
version = "1.7.0"
version = "1.8.0"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Version 2.0?


[deps]
AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
Expand All @@ -22,6 +22,7 @@ SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
SymbolicIndexingInterface = "2efcf032-c050-4f8e-a9bb-153293bab1f5"
TermInterface = "8ea1fca8-c5ef-4a55-8b96-4e9afe9c9a3c"
TimerOutputs = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f"
Unityper = "a7c27f48-0311-42f6-a7f8-2c11e75eb415"

Expand All @@ -42,6 +43,7 @@ Setfield = "0.7, 0.8, 1"
SpecialFunctions = "0.10, 1.0, 2"
StaticArrays = "0.12, 1.0"
SymbolicIndexingInterface = "0.3"
TermInterface = "0.4"
TimerOutputs = "0.5"
Unityper = "0.1.2"
julia = "1.3"
Expand Down
9 changes: 0 additions & 9 deletions docs/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@ SymbolicUtils.Pow
SymbolicUtils.promote_symtype
```

## Interfacing

```@docs
SymbolicUtils.istree
SymbolicUtils.operation
SymbolicUtils.arguments
SymbolicUtils.similarterm
```

## Rewriters

```@docs
Expand Down
11 changes: 2 additions & 9 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,8 @@ g(2//5, g(1, β))

Symbolic expressions are of type `Term{T}`, `Add{T}`, `Mul{T}`, `Pow{T}` or `Div{T}` and denote some function call where one or more arguments are themselves such expressions or `Sym`s. See more about the representation [here](/representation/).

All the expression types support the following:

- `istree(x)` -- always returns `true` denoting, `x` is not a leaf node like Sym or a literal.
- `operation(x)` -- the function being called
- `arguments(x)` -- a vector of arguments
- `symtype(x)` -- the "inferred" type (`T`)

See more on the interface [here](/interface)

All the expression types support the [TermInterface.jl](https://github.com/0x0f0f0f/TermInterface.jl) interface.
Please refer to the package for the complete reference of the interface.

## Term rewriting

Expand Down
15 changes: 10 additions & 5 deletions src/SymbolicUtils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,26 @@ $(DocStringExtensions.README)
module SymbolicUtils

using DocStringExtensions

export @syms, term, showraw, hasmetadata, getmetadata, setmetadata

using Unityper

# Sym, Term,
# Add, Mul and Pow
using TermInterface
using DataStructures
using Setfield
import Setfield: PropertyLens
using SymbolicIndexingInterface
import Base: +, -, *, /, //, \, ^, ImmutableDict
using ConstructionBase
include("interface.jl")
using TermInterface
import TermInterface: iscall, isexpr, issym, symtype, head, children,
operation, arguments, metadata, maketerm

const istree = iscall
export istree, operation, arguments, unsorted_arguments, similarterm, iscall
# Sym, Term,
# Add, Mul and Pow
include("types.jl")
export istree, operation, arguments, similarterm

# Methods on symbolic objects
using SpecialFunctions, NaNMath
Expand Down
16 changes: 8 additions & 8 deletions src/code.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export toexpr, Assignment, (←), Let, Func, DestructuredArgs, LiteralExpr,

import ..SymbolicUtils
import ..SymbolicUtils.Rewriters
import SymbolicUtils: @matchable, BasicSymbolic, Sym, Term, istree, operation, arguments, issym,
import SymbolicUtils: @matchable, BasicSymbolic, Sym, Term, iscall, operation, arguments, issym,
symtype, similarterm, unsorted_arguments, metadata, isterm, term

##== state management ==##
Expand Down Expand Up @@ -162,7 +162,7 @@ end
toexpr(O::Expr, st) = O

function substitute_name(O, st)
if (issym(O) || istree(O)) && haskey(st.rewrites, O)
if (issym(O) || iscall(O)) && haskey(st.rewrites, O)
st.rewrites[O]
else
O
Expand All @@ -176,13 +176,13 @@ function toexpr(O, st)
end
O = substitute_name(O, st)

!istree(O) && return O
!iscall(O) && return O
op = operation(O)
expr′ = function_to_expr(op, O, st)
if expr′ !== nothing
return expr′
else
!istree(O) && return O
!iscall(O) && return O
args = arguments(O)
return Expr(:call, toexpr(op, st), map(x->toexpr(x, st), args)...)
end
Expand Down Expand Up @@ -221,7 +221,7 @@ get_rewrites(args::DestructuredArgs) = ()
function get_rewrites(args::Union{AbstractArray, Tuple})
cflatten(map(get_rewrites, args))
end
get_rewrites(x) = istree(x) ? (x,) : ()
get_rewrites(x) = iscall(x) ? (x,) : ()
cflatten(x) = Iterators.flatten(x) |> collect

# Used in Symbolics
Expand Down Expand Up @@ -691,7 +691,7 @@ end
@inline newsym(::Type{T}) where T = Sym{T}(gensym("cse"))

function _cse!(mem, expr)
istree(expr) || return expr
iscall(expr) || return expr
op = _cse!(mem, operation(expr))
args = map(Base.Fix1(_cse!, mem), arguments(expr))
t = similarterm(expr, op, args)
Expand Down Expand Up @@ -742,7 +742,7 @@ end


function cse_state!(state, t)
!istree(t) && return t
!iscall(t) && return t
state[t] = Base.get(state, t, 0) + 1
foreach(x->cse_state!(state, x), unsorted_arguments(t))
end
Expand All @@ -758,7 +758,7 @@ function cse_block!(assignments, counter, names, name, state, x)
counter[] += 1
return sym
end
elseif istree(x)
elseif iscall(x)
args = map(a->cse_block!(assignments, counter, names, name, state,a), unsorted_arguments(x))
if isterm(x)
return term(operation(x), args...)
Expand Down
6 changes: 3 additions & 3 deletions src/inspect.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import AbstractTrees

const inspect_metadata = Ref{Bool}(false)
function AbstractTrees.nodevalue(x::Symbolic)
istree(x) ? operation(x) : x
iscall(x) ? operation(x) : isexpr(x) ? head(x) : x
end

function AbstractTrees.nodevalue(x::BasicSymbolic)
str = if !istree(x)
str = if !iscall(x)
string(exprtype(x), "(", x, ")")
elseif isadd(x)
string(exprtype(x),
Expand All @@ -27,7 +27,7 @@ function AbstractTrees.nodevalue(x::BasicSymbolic)
end

function AbstractTrees.children(x::Symbolic)
istree(x) ? arguments(x) : ()
iscall(x) ? arguments(x) : isexpr(x) ? children(x) : ()
end

"""
Expand Down
10 changes: 5 additions & 5 deletions src/interface.jl
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""
istree(x)
iscall(x)

Returns `true` if `x` is a term. If true, `operation`, `arguments`
must also be defined for `x` appropriately.
"""
istree(x) = false
iscall(x) = false

"""
symtype(x)
Expand All @@ -29,7 +29,7 @@ issym(x) = false
"""
operation(x)

If `x` is a term as defined by `istree(x)`, `operation(x)` returns the
If `x` is a term as defined by `iscall(x)`, `operation(x)` returns the
head of the term if `x` represents a function call, for example, the head
is the function being called.
"""
Expand All @@ -38,14 +38,14 @@ function operation end
"""
arguments(x)

Get the arguments of `x`, must be defined if `istree(x)` is `true`.
Get the arguments of `x`, must be defined if `iscall(x)` is `true`.
"""
function arguments end

"""
unsorted_arguments(x::T)

If x is a term satisfying `istree(x)` and your term type `T` provides
If x is a term satisfying `iscall(x)` and your term type `T` provides
an optimized implementation for storing the arguments, this function can
be used to retrieve the arguments when the order of arguments does not matter
but the speed of the operation does.
Expand Down
4 changes: 2 additions & 2 deletions src/matchers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
# 3. Callback: takes arguments Dictionary × Number of elements matched
#
function matcher(val::Any)
istree(val) && return term_matcher(val)
iscall(val) && return term_matcher(val)
function literal_matcher(next, data, bindings)
islist(data) && isequal(car(data), val) ? next(bindings, 1) : nothing
end
Expand Down Expand Up @@ -89,7 +89,7 @@ function term_matcher(term)
function term_matcher(success, data, bindings)

!islist(data) && return nothing
!istree(car(data)) && return nothing
!iscall(car(data)) && return nothing

function loop(term, bindings′, matchers′) # Get it to compile faster
if !islist(matchers′)
Expand Down
4 changes: 2 additions & 2 deletions src/ordering.jl
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
function get_degrees(expr)
if issym(expr)
((Symbol(expr),) => 1,)
elseif istree(expr)
elseif iscall(expr)
op = operation(expr)
args = arguments(expr)
if operation(expr) == (^) && args[2] isa Number
Expand Down Expand Up @@ -62,7 +62,7 @@ function lexlt(degs1, degs2)
return false # they are equal
end

_arglen(a) = istree(a) ? length(unsorted_arguments(a)) : 0
_arglen(a) = iscall(a) ? length(unsorted_arguments(a)) : 0

function <(a::Tuple, b::Tuple)
for (x, y) in zip(a, b)
Expand Down
24 changes: 14 additions & 10 deletions src/polyform.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ using Bijections
Abstracts a [MultivariatePolynomials.jl](https://juliaalgebra.github.io/MultivariatePolynomials.jl/stable/) as a SymbolicUtils expression and vice-versa.
The SymbolicUtils term interface (`istree`, `operation, and `arguments`) works on PolyForm lazily:
The SymbolicUtils term interface (`isexpr`/`iscall`, `operation, and `arguments`) works on PolyForm lazily:
the `operation` and `arguments` are created by converting one level of arguments into SymbolicUtils expressions. They may further contain PolyForm within them.
We use this to hold polynomials in memory while doing `simplify_fractions`.
Expand Down Expand Up @@ -97,7 +97,7 @@ _isone(p::PolyForm) = isone(p.p)
function polyize(x, pvar2sym, sym2term, vtype, pow, Fs, recurse)
if x isa Number
return x
elseif istree(x)
elseif iscall(x)
if !(symtype(x) <: Number)
error("Cannot convert $x of symtype $(symtype(x)) into a PolyForm")
end
Expand Down Expand Up @@ -170,8 +170,10 @@ function PolyForm(x,
PolyForm{symtype(x)}(p, pvar2sym, sym2term, metadata)
end

istree(x::Type{<:PolyForm}) = true
istree(x::PolyForm) = true
isexpr(x::Type{<:PolyForm}) = true
isexpr(x::PolyForm) = true
iscall(x::Type{<:PolyForm}) = true
iscall(x::PolyForm) = true

function similarterm(t::PolyForm, f, args, symtype; metadata=nothing)
basic_similarterm(t, f, args, symtype; metadata=metadata)
Expand All @@ -181,6 +183,7 @@ function similarterm(::PolyForm, f::Union{typeof(*), typeof(+), typeof(^)},
f(args...)
end

head(::PolyForm) = PolyForm
operation(x::PolyForm) = MP.nterms(x.p) == 1 ? (*) : (+)

function arguments(x::PolyForm{T}) where {T}
Expand Down Expand Up @@ -227,6 +230,7 @@ function arguments(x::PolyForm{T}) where {T}
PolyForm{T}(t, x.pvar2sym, x.sym2term, nothing)) for t in ts]
end
end
children(x::PolyForm) = [operation(x); arguments(x)]

Base.show(io::IO, x::PolyForm) = show_term(io, x)

Expand Down Expand Up @@ -336,7 +340,7 @@ function simplify_fractions(x; polyform=false)
end

function add_with_div(x, flatten=true)
(!istree(x) || operation(x) != (+)) && return x
(!iscall(x) || operation(x) != (+)) && return x
aa = unsorted_arguments(x)
!any(a->isdiv(a), aa) && return x # no rewrite necessary

Expand All @@ -361,26 +365,26 @@ function flatten_fractions(x)
end

function fraction_iszero(x)
!istree(x) && return _iszero(x)
!iscall(x) && return _iszero(x)
ff = flatten_fractions(x)
# fast path and then slow path
any(_iszero, numerators(ff)) ||
any(_iszeroexpand, numerators(ff))
end

function fraction_isone(x)
!istree(x) && return _isone(x)
!iscall(x) && return _isone(x)
_isone(simplify_fractions(flatten_fractions(x)))
end

function needs_div_rules(x)
(isdiv(x) && !(x.num isa Number) && !(x.den isa Number)) ||
(istree(x) && operation(x) === (+) && count(has_div, unsorted_arguments(x)) > 1) ||
(istree(x) && any(needs_div_rules, unsorted_arguments(x)))
(iscall(x) && operation(x) === (+) && count(has_div, unsorted_arguments(x)) > 1) ||
(iscall(x) && any(needs_div_rules, unsorted_arguments(x)))
end

function has_div(x)
return isdiv(x) || (istree(x) && any(has_div, unsorted_arguments(x)))
return isdiv(x) || (iscall(x) && any(has_div, unsorted_arguments(x)))
end

flatten_pows(xs) = map(xs) do x
Expand Down
7 changes: 4 additions & 3 deletions src/rewriters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ rewriters.
"""
module Rewriters
using SymbolicUtils: @timer
using TermInterface

import SymbolicUtils: similarterm, istree, operation, arguments, unsorted_arguments, metadata, node_count
export Empty, IfElse, If, Chain, RestartedChain, Fixpoint, Postwalk, Prewalk, PassThrough
Expand Down Expand Up @@ -196,7 +197,7 @@ instrument(x::PassThrough, f) = PassThrough(instrument(x.rw, f))
passthrough(x, default) = x === nothing ? default : x
function (p::Walk{ord, C, F, false})(x) where {ord, C, F}
@assert ord === :pre || ord === :post
if istree(x)
if iscall(x)
if ord === :pre
x = p.rw(x)
end
Expand All @@ -214,11 +215,11 @@ end

function (p::Walk{ord, C, F, true})(x) where {ord, C, F}
@assert ord === :pre || ord === :post
if istree(x)
if iscall(x)
if ord === :pre
x = p.rw(x)
end
if istree(x)
if iscall(x)
_args = map(arguments(x)) do arg
if node_count(arg) > p.thread_cutoff
Threads.@spawn p(arg)
Expand Down
4 changes: 2 additions & 2 deletions src/rule.jl
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ end
getdepth(r::Rule) = r.depth

function rule_depth(rule, d=0, maxdepth=0)
if istree(rule)
if iscall(rule)
maxdepth = reduce(max, (rule_depth(r, d+1, maxdepth) for r in arguments(rule)), init=1)
elseif rule isa Slot || rule isa Segment
maxdepth = max(d, maxdepth)
Expand Down Expand Up @@ -389,7 +389,7 @@ Base.show(io::IO, acr::ACRule) = print(io, "ACRule(", acr.rule, ")")

function (acr::ACRule)(term)
r = Rule(acr)
if !istree(term)
if !iscall(term)
r(term)
else
f = operation(term)
Expand Down
Loading
Loading