Differentiation method for element-wise "abs"-function applied on "Operation"-types in ModelingToolKit.jl?

Hi,

I am trying to apply ModelingToolkit.sparsejacobian() to my differential function including element-wise calls of the absolute function abs(). How can I appropriately define the derivative of abs() to be used with the Operation type in ModelingToolKit.jl? Simply using the standard method provided by DiffRules.jl leads to an error due to the signbit() function stating

ERROR: TypeError: non-boolean (Operation) used in boolean context
Stacktrace:
 [1] signbit at ./REPL[49959]:3 [inlined]
 [2] _abs_deriv at .julia/packages/DiffRules/5QwtC/src/rules.jl:72 [inlined]

Any help is much appreciated!

@shashi is there a reason this derivative isn’t already defined?

Hi @ChrisRackauckas,

Thank you for the (always prompt) reply. Just to clarify, this minimal example works (also for less trivial cases as this one):

function func!(du,u)
    du = abs.(u)
end
@variables du[1:2] u[1:2]
func!(du,u)
sjac= ModelingToolkit.sparsejacobian(vec(du),vec(u));

while the element-wise approach (similar to my case) does not:

function func!(du,u)
    for j = 1:2
        du[j] = abs(u[j])
    end
 end
@variables du[1:2] u[1:2]
func!(du,u)
sjac= ModelingToolkit.sparsejacobian(vec(du),vec(u));

and leads to the error message ERROR: MethodError: no method matching signbit(::Operation) where the signbit function is used for the differentiation in DiffRules.jl.

This just means ModelingToolkit needs to register signbit. signbit is the derivative.

Let’s continue this here: https://github.com/SciML/ModelingToolkit.jl/pull/568