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

Incorrect code generated for Symbolics.build_function(Symbolics.derivative(mod(x), x), x) #1123

Open
lassepe opened this issue Apr 22, 2024 · 4 comments

Comments

@lassepe
Copy link

lassepe commented Apr 22, 2024

The following reproducer generates incorrect code:

using Symbolics
x = only(@variables(x))
f = mod(x, 1.0)
df = Symbolics.derivative(f, x)
dfc = Symbolics.build_function(df, x; expression=Val(false))
dfc(0.5) # returns `Differential(x)(0.5)::SymbolicsUtils.BasicSymbolic{Float64}`)

The generated function returns Differential(x)(0.5)::SymbolicsUtils.BasicSymbolic{Float64}. I would have expected it to return 1.0::Float64. I understand that mod is not differentiable everywhere so maybe this is intended. But then an informative error would be preferred.

@ChrisRackauckas
Copy link
Member

Note that this is not incorrect code construction. The issue is:

julia> df = Symbolics.derivative(f, x)
Differential(x)(mod(x, 1.0))

The derivative of mod is not defined, so it's left as a symbolic derivative. Since none of the arguments x are D(x), it does not find and replace that to an argument. So then it errors as an improper function definition that has symbolics left in the built function. We should add a rule where if the generated expression has a symbolic piece left it should error at build_function time, but at least right now if not all of the symbolic elements are lifted to arguments it will error at call time or return a symbolic expression, which is at least safe but an earlier error would be more helpful.

@lassepe
Copy link
Author

lassepe commented Apr 29, 2024

Would it make sense to define a rule for mod(x, y) that only throws a DomainError for mod(x, y)==0?

@ChrisRackauckas
Copy link
Member

Yes, we should probably define its derivative as something like ifelse(x==0,x,DomainError()), but that cannot be represented symbolically like that. Also, symbolic functions try to never error, they use NaNMath by default instead of erroring, so maybe ifelse(x==0,x,NaN) is the appropriate definition?

@ChrisRackauckas
Copy link
Member

ifelse(x==0,NaN,x)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants