-
Notifications
You must be signed in to change notification settings - Fork 146
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
Support derivatives of functions with units via Unitful extension #680
base: master
Are you sure you want to change the base?
Conversation
Thank you for the contribution! Can I ask why you would prefer this code to be in ForwardDiff? |
@gdalle Sure enough. While the same code would also work as an extension for Alternative implementations of the extension that only extend the public API (e.g., adding a new method to EDIT: fix typo |
Soft bump to the maintainers; interested in knowing if you're able to take these changes. |
While I am a member of the JuliaDiff organization, I have never really maintained this repo so I probably won't be the one to merge this. |
This has unexpected results for some functions like For reference I am looking at "On the dimension of angles and their units" which provides a good meaning of Demonstration follows. Just loosening the using ForwardDiff, Unitful, DimensionfulAngles
# Define a cycle unit equal to 360 degrees.
@unit cyc "cyc" Cycle 360u"°ᵃ" false
ForwardDiff.can_dual(::Type{Quantity{Float64}}) = true
function deriv(f::F, x::R) where {F,R<:Number}
T = typeof(ForwardDiff.Tag(f, R))
return ForwardDiff.extract_derivative(T, f(ForwardDiff.Dual{T}(x, one(x))))
end
julia> deriv(sin, 2π)
1.0
julia> deriv(sin, 1.0cyc)
1.0
julia> deriv(sin, 2π*u"rad")
1.0
julia> deriv(sin, 360.0*u"°ᵃ")
1.0 Versus this PR: julia> ForwardDiff.derivative(sin, 0)
1.0
julia> ForwardDiff.derivative(sin, 1.0cyc)
6.283185307179586 cyc^-1
julia> ForwardDiff.derivative(sin, 2π*u"rad")
1.0 rad^-1
julia> ForwardDiff.derivative(sin, 360.0*u"°ᵃ")
0.017453292519943295 °^-1 |
@jariji My point with this PR was to support |
DimensionalAngles.jl just defines some more dimensions and units for Unitful.jl and their behavior in Base functions. It's possible I'm misunderstanding the correct behavior -- I'm not an expert in quantities or autodiff. However, imho a function that gives right answers for some units and wrong answers for some units is probably not safe to merge because that kind of decision is the source of Julia's many correctness problems. |
Adds support for taking derivatives of functions with
Unitful
units on their input and/or output by means of an extension (weakdep). The extension works by ensuring thatDual
always wraps aReal
number—asForwardDiff
expects—even whenUnitful.Quantity
s are involved, stripping and adding back the units as appropriate.Relevant issue is #328.
With this PR only
derivative
has support for units, yet the same behavior could be later applied to the other functions as well.