JuliaSymbolics / Symbolics.jl

Symbolic programming for the next generation of numerical software
https://symbolics.juliasymbolics.org/stable/
Other
1.33k stars 147 forks source link

derivative of a function returning a boolean #877

Open brunorigal opened 1 year ago

brunorigal commented 1 year ago

Hi, Thanks for this awesome library!

I tried to compute the derivative of a comparison between a variable and a float. I would expect the derivative is zero everywhere (except 0 in this case), But the differential of a boolean does not seem to work:

using Symbolics
@variables x
fun = build_function(Symbolics.derivative(x>0.0, x), x, expression=false)

The result is:

julia> fun(1.0)
Differential(x)(true)

Is there a way to make it work?

My goal is to compute the derivative of a more complex function involving conditions, ideally without having to modify the code of the function I want to differentiate.

xtalax commented 1 year ago

The spatial derivative of a boolean is zero everywhere it isn't undefined, are you sure you need this? Perhaps elaborate on what you are trying to do

brunorigal commented 1 year ago

Yes of course, I was trying to compute the derivative of the Zernike polynomials from this library:

using ZernikePolynomials
using Symbolics
@variables ρ, θ
Symbolics.derivative(Zernike(2,2)(ρ, θ), ρ)

The result is:

4.898979485566356ρ*cos(2θ)*(abs(ρ) <= 1.0) + 2.449489742783178(ρ^2)*cos(2θ)*Differential(ρ)(abs(ρ) <= 1.0)*ifelse(signbit(ρ), -1, 1)

The problem comes from the condition at the beginning abs(ρ) <= 1.0. Of course as the Zernike polynomials are defined only on the unit disk, I could just have copy pasted the code and replaced this condition with an assert. But I still felt this could be useful in a more general case where functions are defined by parts.

I read a bit more your documentation, it seems like the correct way to do this is using the IfElse package. I liked the idea of being able to use any function from any julia package on symbolic variables, but maybe I was a bit too optimistic.