Skip to content

Commit

Permalink
ustrip, trig rules for degrees
Browse files Browse the repository at this point in the history
  • Loading branch information
SBuercklin committed Jul 24, 2022
1 parent 0cf3fbe commit a42ab98
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/UnitfulChainRules.jl
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
module UnitfulChainRules

using Unitful
using Unitful: Quantity, Units
using ChainRulesCore: NoTangent
using Unitful: Quantity, Units, NoDims
using ChainRulesCore: NoTangent, @scalar_rule
import ChainRulesCore: rrule, frule, ProjectTo

include("./rrules.jl")
include("./frules.jl")
include("./projection.jl")


include("./extras.jl") # Unitful-specific rules

include("./trig.jl") # sin, cos, tan, etc for degrees

end # module
13 changes: 13 additions & 0 deletions src/extras.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Identity operation for non-Quantities
rrule(::typeof(ustrip), x::Number) = x, (Δ) -> (NoTangent(), Δ * one(x))

# Divide by the stripped units to backprop
function rrule(::typeof(ustrip), x::Quantity{T,D,U}) where {T,D,U}
ustripped = ustrip(x)
project_x = ProjectTo(x)
invU = inv(U())

ustrip_pb(Δ) = (NoTangent(), project_x* invU))

return ustripped, ustrip_pb
end
17 changes: 17 additions & 0 deletions src/trig.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
###########################
#=
Trigonometric Rules for Degrees
Let dx be differential in radians/dimensionless, dx° be in degrees
df/dx° = df/dx * dx/dx° = df/dx * π/180°
=#
###########################
const DEGREE_QUANTITY = Quantity{<:Number,NoDims,typeof(u"°")}
const TO_RAD = π/180u"°"

@scalar_rule sin(x::DEGREE_QUANTITY) cos(x) * TO_RAD
@scalar_rule cos(x::DEGREE_QUANTITY) -sin(x) * TO_RAD
@scalar_rule tan(x::DEGREE_QUANTITY) (1 + Ω^2) * TO_RAD
@scalar_rule csc(x::DEGREE_QUANTITY) -Ω * cot(x) * TO_RAD
@scalar_rule sec(x::DEGREE_QUANTITY) Ω * tan(x) * TO_RAD
@scalar_rule cot(x::DEGREE_QUANTITY) -(1 + Ω^2) * TO_RAD

0 comments on commit a42ab98

Please sign in to comment.