Skip to content

Commit

Permalink
feat: derivative speed hack for no dependence on variable
Browse files Browse the repository at this point in the history
  • Loading branch information
MilesCranmer committed Dec 7, 2024
1 parent 3db5f99 commit 39da124
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/ComposableExpression.jl
Original file line number Diff line number Diff line change
Expand Up @@ -283,12 +283,17 @@ function _symbolic_derivative(
tree::N, ctx::SymbolicDerivativeContext
) where {T,N<:AbstractExpressionNode{T}}
# NOTE: We cannot mutate the tree here! Since we use it twice.
if tree.degree == 0
if !tree.constant && tree.feature == ctx.feature
return constructorof(N)(; val=one(T))
else
return constructorof(N)(; val=zero(T))
end

# Quick test to see if we have any dependence on the feature, so
# we can return 0 for the branch
any_dependence = any(tree) do node
node.degree == 0 && !node.constant && node.feature == ctx.feature
end

if !any_dependence
return constructorof(N)(; val=zero(T))
elseif tree.degree == 0
return constructorof(N)(; val=one(T))
elseif tree.degree == 1
# f(g(x)) => f'(g(x)) * g'(x)
f_prime = constructorof(N)(; op=tree.op + ctx.nuna, l=tree.l)
Expand Down
9 changes: 9 additions & 0 deletions test/test_composable_expression.jl
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,15 @@ end
@test D(cos(x1), 1)([1.0]) [-sin(1.0)]
@test D(sin(x1) * cos(x2), 1)([1.0], [2.0]) [cos(1.0) * cos(2.0)]
@test D(D(sin(x1) * cos(x2), 1), 2)([1.0], [2.0]) [cos(1.0) * -sin(2.0)]

# Printing should also be nice:
@test repr(D(x1 * x2, 1)) == "(∂₁*(x1, x2) * 1.0) + (∂₂*(x1, x2) * 0.0)"

# We also have special behavior when there is no dependence:
@test repr(D(sin(x2), 1)) == "0.0"
@test repr(D(x2 + sin(x2), 1)) == "0.0"
@test repr(D(x2 + sin(x2) - x1, 1)) ==
"(∂₁-(x2 + sin(x2), x1) * 0.0) + (∂₂-(x2 + sin(x2), x1) * 1.0)"
end

@testitem "Test template structure with derivatives" tags = [:part2] begin
Expand Down

0 comments on commit 39da124

Please sign in to comment.