Skip to content

Commit

Permalink
Merge pull request #107 from SymbolicML/fix-safe-sqrt
Browse files Browse the repository at this point in the history
feat: allow expression algebra for safe aliases
  • Loading branch information
MilesCranmer authored Oct 28, 2024
2 parents da31b90 + 911a9f0 commit 3fb963d
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 5 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ jobs:
additional_tests:
name: test ${{ matrix.test_name }} - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 60
timeout-minutes: 120
strategy:
fail-fast: false
matrix:
Expand All @@ -71,7 +71,7 @@ jobs:
julia-version:
- "1"
test_name:
- "enzyme"
# - "enzyme" # flaky; seems to infinitely compile and fail the CI
- "jet"
steps:
- uses: actions/checkout@v2
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "DynamicExpressions"
uuid = "a40a106e-89c9-4ca8-8020-a735e8728b6b"
authors = ["MilesCranmer <[email protected]>"]
version = "1.3.0"
version = "1.4.0"

[deps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Expand Down
1 change: 1 addition & 0 deletions src/DynamicExpressions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import .StringsModule: get_op_name
import .ExpressionModule:
get_operators, get_variable_names, Metadata, default_node_type, node_type
@reexport import .ExpressionAlgebraModule: @declare_expression_operator
import .ExpressionAlgebraModule: declare_operator_alias
@reexport import .ParseModule: @parse_expression, parse_expression
import .ParseModule: parse_leaf
@reexport import .ParametricExpressionModule: ParametricExpression, ParametricNode
Expand Down
28 changes: 26 additions & 2 deletions src/ExpressionAlgebra.jl
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,31 @@ function Base.showerror(io::IO, e::MissingOperatorError)
return print(io, e.msg)
end

"""
declare_operator_alias(op::Function, ::Val{arity})::Function
Define how an internal operator should be matched against user-provided operators in expression trees.
By default, operators match themselves. Override this method to specify that an internal operator
should match a different operator when searching the operator lists in expressions.
For example, to make `safe_sqrt` match `sqrt` user-space:
```julia
DynamicExpressions.declare_operator_alias(safe_sqrt, Val(1)) = sqrt
```
Which would allow a user to write `sqrt(x::Expression)`
and have it match the operator `safe_sqrt` stored in the binary operators
of the expression.
"""
declare_operator_alias(op::F, _) where {F<:Function} = op

function apply_operator(op::F, l::AbstractExpression) where {F<:Function}
operators = get_operators(l, nothing)
op_idx = findfirst(==(op), operators.unaops)
op_idx = findfirst(
==(op), map(Base.Fix2(declare_operator_alias, Val(1)), operators.unaops)
)
if op_idx === nothing
throw(
MissingOperatorError(
Expand All @@ -56,7 +78,9 @@ function apply_operator(op::F, l, r) where {F<:Function}
r::AbstractExpression
(get_operators(r, nothing), r)
end
op_idx = findfirst(==(op), operators.binops)
op_idx = findfirst(
==(op), map(Base.Fix2(declare_operator_alias, Val(2)), operators.binops)
)
if op_idx === nothing
throw(
MissingOperatorError(
Expand Down
37 changes: 37 additions & 0 deletions test/test_expression_math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,40 @@ end
)
end
end
@testitem "Custom operators and aliases" begin
using DynamicExpressions

# Define a custom safe sqrt that avoids negative numbers
safe_sqrt(x) = x < 0 ? zero(x) : sqrt(x)
# And a custom function that squares its input
my_func(x) = x^2

# Define that safe_sqrt should match sqrt in expressions, with correct type!
DynamicExpressions.declare_operator_alias(::typeof(safe_sqrt), ::Val{1}) = sqrt

# Declare my_func as a new operator
@declare_expression_operator my_func 1

# Create an expression with just safe_sqrt:
ex = parse_expression(
:(x);
expression_type=Expression{Float64},
unary_operators=[safe_sqrt, my_func],
variable_names=["x"],
)

# Test that sqrt(ex) maps to safe_sqrt through the alias:
ex_sqrt = sqrt(ex)
ex_my = my_func(ex)

shower(ex) = sprint((io, e) -> show(io, MIME"text/plain"(), e), ex)

@test shower(ex_sqrt) == "safe_sqrt(x)"
@test shower(ex_my) == "my_func(x)"

# Test evaluation:
X = [4.0 -4.0]

@test ex_sqrt(X) [2.0; 0.0]
@test ex_my(X) [16.0; 16.0]
end

2 comments on commit 3fb963d

@MilesCranmer
Copy link
Member Author

Choose a reason for hiding this comment

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

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

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

Registration pull request created: JuliaRegistries/General/118188

Tip: Release Notes

Did you know you can add release notes too? Just add markdown formatted text underneath the comment after the text
"Release notes:" and it will be added to the registry PR, and if TagBot is installed it will also be added to the
release that TagBot creates. i.e.

@JuliaRegistrator register

Release notes:

## Breaking changes

- blah

To add them here just re-invoke and the PR will be updated.

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v1.4.0 -m "<description of version>" 3fb963d097f7b07223eebbd0c9832534fb0e15de
git push origin v1.4.0

Please sign in to comment.