Take a derivative with respect to an expression in Symbolics

The Symbolics documentation says (bold italic emphasis added)

struct Differential <: Symbolics.Operator

Represents a differential operator.

Fields

  • x

: The variable or expression to differentiate with respect to.

This implies that one can take a derivative wrt an expression rather than a variable, although the documentation does not show such an example.

For a simple expression this works as expected:

Derivative wrt a simple expression rather than a variable
julia> using Symbolics

julia> @variables x
1-element Vector{Num}:
 x

julia> a = cos(x)
cos(x)

julia> b = cos(x)
cos(x)

julia> f = x*a
x*cos(x)

julia> a === b
false

julia> Da = Differential(a)
(::Differential) (generic function with 2 methods)

julia> Db = Differential(b)
(::Differential) (generic function with 2 methods)

julia> expand_derivatives(Da(f))
x

julia> expand_derivatives(Db(f))
x

For a more complicated expression it doesn’t work as expected:

Derivative wrt a more complex expression
julia> a1 = cos(x)sin(x)
cos(x)*sin(x)

julia> b1 = cos(x)sin(x)
cos(x)*sin(x)

julia> a1 === b1
false

julia> a1 == b1
(cos(x)*sin(x)) == (cos(x)*sin(x))

julia> f1 = x*a1
x*cos(x)*sin(x)

julia> Da1 = Differential(a1)
(::Differential) (generic function with 2 methods)

julia> Db1 = Differential(b1)
(::Differential) (generic function with 2 methods)

julia> expand_derivatives(Da1(f1))
0

julia> expand_derivatives(Db1(f1))
0

Can you only take derivatives wrt simple expressions f(x) where f is one of the math functions defined in Base, and x is a variable? Or are you not supposed to take derivatives wrt expressions at all?