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

TermInterface Version 2 #609

Merged
merged 30 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +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"
TermInterface = "1.0.1"
TimerOutputs = "0.5"
Unityper = "0.1.2"
julia = "1.3"
Expand Down
14 changes: 13 additions & 1 deletion docs/src/manual/interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ You can read the documentation of [TermInterface.jl](https://github.com/JuliaSym

## SymbolicUtils.jl only methods

`promote_symtype(f, arg_symtypes...)`
### `symtype(x)`

Returns the symbolic type of `x`. By default this is just `typeof(x)`.
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
Define this for your symbolic types if you want `SymbolicUtils.simplify` to apply rules
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
specific to numbers (such as commutativity of multiplication). Or such
rules that may be implemented in the future.

### `issym(x)`

Returns `true` if `x` is a symbol. If true, `nameof` must be defined
on `x` and must return a Symbol.
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved

### `promote_symtype(f, arg_symtypes...)`

Returns the appropriate output type of applying `f` on arguments of type `arg_symtypes`.
2 changes: 1 addition & 1 deletion docs/src/manual/representation.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Performance of symbolic simplification depends on the datastructures used to rep

The most basic term representation simply holds a function call and stores the function and the arguments it is called with. This is done by the `Term` type in SymbolicUtils. Functions that aren't commutative or associative, such as `sin` or `hypot` are stored as `Term`s. Commutative and associative operations like `+`, `*`, and their supporting operations like `-`, `/` and `^`, when used on terms of type `<:Number`, stand to gain from the use of more efficient datastrucutres.

All term representations must support `operation` and `arguments` functions. And they must define `istree` to return `true` when called with an instance of the type. Generic term-manipulation programs such as the rule-based rewriter make use of this interface to inspect expressions. In this way, the interface wins back the generality lost by having a zoo of term representations instead of one. (see [interface](/interface/) section for more on this.)
All term representations must support `operation` and `arguments` functions. And they must define `iscall` and `isexpr` to return `true` when called with an instance of the type. Generic term-manipulation programs such as the rule-based rewriter make use of this interface to inspect expressions. In this way, the interface wins back the generality lost by having a zoo of term representations instead of one. (see [interface](/interface/) section for more on this.)


### Preliminary representation of arithmetic
Expand Down
6 changes: 2 additions & 4 deletions src/SymbolicUtils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ using SymbolicIndexingInterface
import Base: +, -, *, /, //, \, ^, ImmutableDict
using ConstructionBase
using TermInterface
import TermInterface: iscall, isexpr, issym, symtype, head, children,
import TermInterface: iscall, isexpr, head, children,
operation, arguments, metadata, maketerm

const istree = iscall
Base.@deprecate_binding istree iscall
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
export istree, operation, arguments, unsorted_arguments, similarterm, iscall
export operation, arguments, unsorted_arguments, iscall
# Sym, Term,
# Add, Mul and Pow
include("types.jl")
Expand Down
8 changes: 3 additions & 5 deletions src/code.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export toexpr, Assignment, (←), Let, Func, DestructuredArgs, LiteralExpr,
import ..SymbolicUtils
import ..SymbolicUtils.Rewriters
import SymbolicUtils: @matchable, BasicSymbolic, Sym, Term, iscall, operation, arguments, issym,
symtype, similarterm, unsorted_arguments, metadata, isterm, term
symtype, unsorted_arguments, metadata, isterm, term

##== state management ==##

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

v, dict = mem
update! = let v=v, t=t
Expand Down Expand Up @@ -763,9 +763,7 @@ function cse_block!(assignments, counter, names, name, state, x)
if isterm(x)
return term(operation(x), args...)
else
return maketerm(typeof(x), operation(x),
args, symtype(x),
metadata(x))
return maketerm(typeof(x), operation(x), args, metadata(x))
end
else
return x
Expand Down
84 changes: 0 additions & 84 deletions src/interface.jl

This file was deleted.

15 changes: 7 additions & 8 deletions src/polyform.jl
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ function polyize(x, pvar2sym, sym2term, vtype, pow, Fs, recurse)
maketerm(typeof(x),
op,
map(a->PolyForm(a, pvar2sym, sym2term, vtype; Fs, recurse), args),
symtype(x),
metadata(x))
else
x
Expand Down Expand Up @@ -176,11 +175,10 @@ isexpr(x::PolyForm) = true
iscall(x::Type{<:PolyForm}) = true
iscall(x::PolyForm) = true

function maketerm(::Type{<:PolyForm}, f, args, symtype, metadata)
basicsymbolic(t, f, args, symtype, metadata)
function maketerm(t::Type{<:PolyForm}, f, args, metadata)
basicsymbolic(t, f, args, metadata)
end
function maketerm(::Type{<:PolyForm}, f::Union{typeof(*), typeof(+), typeof(^)},
args, symtype, metadata)
function maketerm(::Type{<:PolyForm}, f::Union{typeof(*), typeof(+), typeof(^)}, args, metadata)
f(args...)
end

Expand Down Expand Up @@ -252,7 +250,7 @@ function unpolyize(x)
# we need a special makterm here because the default one used in Postwalk will call
# promote_symtype to get the new type, but we just want to forward that in case
# promote_symtype is not defined for some of the expressions here.
Postwalk(identity, maketerm=(T,f,args,sT,m) -> maketerm(T, f, args, symtype(x), m))(x)
Postwalk(identity, maketerm=(T,f,args,m) -> maketerm(T, f, args, m))(x)
end

function toterm(x::PolyForm)
Expand Down Expand Up @@ -304,7 +302,8 @@ function add_divs(x, y)
end
end

function frac_maketerm(T, f, args, stype, metadata)
function frac_maketerm(T, f, args, metadata)
# TODO add stype to T?
if f in (*, /, \, +, -)
f(args...)
elseif f == (^)
Expand All @@ -314,7 +313,7 @@ function frac_maketerm(T, f, args, stype, metadata)
args[1]^args[2]
end
else
maketerm(T, f, args, stype, metadata)
maketerm(T, f, args, metadata)
end
end

Expand Down
34 changes: 9 additions & 25 deletions src/rewriters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,7 @@ end
struct Walk{ord, C, F, threaded}
rw::C
thread_cutoff::Int
maketerm::F # XXX: for the 2.0 deprecation cycle, we actually store a function
# that behaves like `similarterm` here, we use `compatmaker` to wrap
# maketerm-like input to do this, with a warning if similarterm provided
# we need this workaround to deprecate because similarterm takes value
# but maketerm only knows the type.
maketerm::F
end

function instrument(x::Walk{ord, C,F,threaded}, f) where {ord,C,F,threaded}
Expand All @@ -183,25 +179,13 @@ end

using .Threads

function compatmaker(similarterm, maketerm)
# XXX: delete this and only use maketerm in a future release.
if similarterm isa Nothing
function (x, f, args, type=_promote_symtype(f, args); metadata)
maketerm(typeof(x), f, args, type, metadata)
end
else
Base.depwarn("Prewalk and Postwalk now take maketerm instead of similarterm keyword argument. similarterm(x, f, args, type; metadata) is now maketerm(typeof(x), f, args, type, metadata)", :similarterm)
similarterm
end
end
function Postwalk(rw; threaded::Bool=false, thread_cutoff=100, maketerm=maketerm, similarterm=nothing)
maker = compatmaker(similarterm, maketerm)
Walk{:post, typeof(rw), typeof(maker), threaded}(rw, thread_cutoff, maker)

function Postwalk(rw; threaded::Bool=false, thread_cutoff=100, maketerm=maketerm)
Walk{:post, typeof(rw), typeof(maketerm), threaded}(rw, thread_cutoff, maketerm)
end

function Prewalk(rw; threaded::Bool=false, thread_cutoff=100, maketerm=maketerm, similarterm=nothing)
maker = compatmaker(similarterm, maketerm)
Walk{:pre, typeof(rw), typeof(maker), threaded}(rw, thread_cutoff, maker)
function Prewalk(rw; threaded::Bool=false, thread_cutoff=100, maketerm=maketerm)
Walk{:pre, typeof(rw), typeof(maketerm), threaded}(rw, thread_cutoff, maketerm)
end

struct PassThrough{C}
Expand All @@ -220,8 +204,8 @@ function (p::Walk{ord, C, F, false})(x) where {ord, C, F}
end

if iscall(x)
x = p.maketerm(x, operation(x), map(PassThrough(p),
unsorted_arguments(x)), metadata=metadata(x))
x = p.maketerm(typeof(x), operation(x), map(PassThrough(p),
unsorted_arguments(x)), metadata(x))
end

return ord === :post ? p.rw(x) : x
Expand All @@ -245,7 +229,7 @@ function (p::Walk{ord, C, F, true})(x) where {ord, C, F}
end
end
args = map((t,a) -> passthrough(t isa Task ? fetch(t) : t, a), _args, arguments(x))
t = p.maketerm(x, operation(x), args, metadata=metadata(x))
t = p.maketerm(typeof(x), operation(x), args, metadata(x))
end
return ord === :post ? p.rw(t) : t
else
Expand Down
2 changes: 1 addition & 1 deletion src/rule.jl
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ function (acr::ACRule)(term)
if result !== nothing
# Assumption: inds are unique
length(args) == length(inds) && return result
return maketerm(typeof(term), f, [result, (args[i] for i in eachindex(args) if i ∉ inds)...], symtype(term), metadata(term))
return maketerm(typeof(term), f, [result, (args[i] for i in eachindex(args) if i ∉ inds)...], metadata(term))
end
end
end
Expand Down
1 change: 0 additions & 1 deletion src/substitute.jl
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ function substitute(expr, dict; fold=true)
maketerm(typeof(expr),
op,
args,
symtype(expr),
metadata(expr))
else
expr
Expand Down
49 changes: 24 additions & 25 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,16 @@ end
###
### Term interface
###

"""
symtype(x)
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved

Returns the symbolic type of `x`. By default this is just `typeof(x)`.
Define this for your symbolic types if you want `SymbolicUtils.simplify` to apply rules
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
specific to numbers (such as commutativity of multiplication). Or such
rules that may be implemented in the future.
"""
symtype(x) = typeof(x)
symtype(x::Number) = typeof(x)
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
@inline symtype(::Symbolic{T}) where T = T

Expand Down Expand Up @@ -162,7 +172,7 @@ function unsorted_arguments(x::BasicSymbolic)
if isadd(x)
for (k, v) in x.dict
push!(args, applicable(*,k,v) ? k*v :
maketerm(k, *, [k, v]))
maketerm(k, *, [k, v], nothing))
end
else # MUL
for (k, v) in x.dict
Expand Down Expand Up @@ -192,7 +202,16 @@ isexpr(s::BasicSymbolic) = !issym(s)
iscall(s::BasicSymbolic) = isexpr(s)

@inline isa_SymType(T::Val{S}, x) where {S} = x isa BasicSymbolic ? Unityper.isa_type_fun(Val(SymbolicUtils.BasicSymbolic), T, x) : false

"""
issym(x)

Returns `true` if `x` is a symbol. If true, `nameof` must be defined
on `x` and must return a Symbol.
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
"""
issym(x) = false
issym(x::BasicSymbolic) = isa_SymType(Val(:Sym), x)

0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
isterm(x) = isa_SymType(Val(:Term), x)
ismul(x) = isa_SymType(Val(:Mul), x)
isadd(x) = isa_SymType(Val(:Add), x)
Expand Down Expand Up @@ -535,10 +554,12 @@ end

unflatten(t) = t

function TermInterface.maketerm(::Type{<:BasicSymbolic}, head, args, type, metadata)
basicsymbolic(head, args, type, metadata)
function TermInterface.maketerm(T::Type{<:BasicSymbolic}, head, args, metadata)
basicsymbolic(head, args, symtype(T), metadata)
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved
end

symtype(::Type{<:Symbolic{T}}) where T = T
0x0f0f0f marked this conversation as resolved.
Show resolved Hide resolved


function basicsymbolic(f, args, stype, metadata)
if f isa Symbol
Expand Down Expand Up @@ -635,28 +656,6 @@ function to_symbolic(x)
x
end

"""
similarterm(x, op, args, symtype=nothing; metadata=nothing)

"""
function similarterm(x, op, args, symtype=nothing; metadata=nothing)
Base.depwarn("""`similarterm` is deprecated, use `maketerm` instead.
`similarterm(x, op, args, symtype; metadata)` is now
`maketerm(typeof(x), op, args, symtype, metadata)`""", :similarterm)
TermInterface.maketerm(typeof(x), op, args, symtype, metadata)
end

# Old fallback
function similarterm(T::Type, op, args, symtype=nothing; metadata=nothing)

Base.depwarn("`similarterm` is deprecated, use `maketerm` instead." *
"See https://github.com/JuliaSymbolics/TermInterface.jl for details.", :similarterm)
op(args...)
end

export similarterm


###
### Pretty printing
###
Expand Down
Loading
Loading