Skip to content

Commit

Permalink
Merge pull request #380 from sathvikbhagavan/sb/zygote_matrix
Browse files Browse the repository at this point in the history
refactor: zygote rules for matrix inputs
  • Loading branch information
ChrisRackauckas authored Jan 21, 2025
2 parents c4de75e + 977f085 commit 301f600
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
11 changes: 9 additions & 2 deletions ext/DataInterpolationsChainRulesCoreExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@ function u_tangent(A::LinearInterpolation, t, Δ)
out = zero.(A.u)
idx = get_idx(A, t, A.iguesser)
t_factor = (t - A.t[idx]) / (A.t[idx + 1] - A.t[idx])
if eltype(out) <: Number
if out isa AbstractVector{<:Number}
out[idx] = Δ * (one(eltype(out)) - t_factor)
out[idx + 1] = Δ * t_factor
elseif out isa AbstractMatrix
out[:, idx] = Δ * (one(eltype(out)) - t_factor)
out[:, idx + 1] = Δ * t_factor
else
@. out[idx] = Δ * (true - t_factor)
@. out[idx + 1] = Δ * t_factor
Expand All @@ -91,10 +94,14 @@ function u_tangent(A::QuadraticInterpolation, t, Δ)
Δt_rel₀ = t - A.t[i₀]
Δt_rel₁ = t - A.t[i₁]
Δt_rel₂ = t - A.t[i₂]
if eltype(out) <: Number
if out isa AbstractVector{<:Number}
out[i₀] = Δ * Δt_rel₁ * Δt_rel₂ / (Δt₀ * Δt₂)
out[i₁] = -Δ * Δt_rel₀ * Δt_rel₂ / (Δt₀ * Δt₁)
out[i₂] = Δ * Δt_rel₀ * Δt_rel₁ / (Δt₂ * Δt₁)
elseif out isa AbstractMatrix
out[:, i₀] = Δ * Δt_rel₁ * Δt_rel₂ / (Δt₀ * Δt₂)
out[:, i₁] = -Δ * Δt_rel₀ * Δt_rel₂ / (Δt₀ * Δt₁)
out[:, i₂] = Δ * Δt_rel₀ * Δt_rel₁ / (Δt₂ * Δt₁)
else
@. out[i₀] = Δ * Δt_rel₁ * Δt_rel₂ / (Δt₀ * Δt₂)
@. out[i₁] = -Δ * Δt_rel₀ * Δt_rel₂ / (Δt₀ * Δt₁)
Expand Down
6 changes: 6 additions & 0 deletions test/zygote_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,18 @@ end
t = collect(1.0:10.0)
test_zygote(
LinearInterpolation, u, t; name = "Linear Interpolation")
u2 = Matrix(hcat(u, u)')
test_zygote(
LinearInterpolation, u2, t; name = "Linear Interpolation with matrix input")
end

@testset "Quadratic Interpolation" begin
u = [1.0, 4.0, 9.0, 16.0]
t = [1.0, 2.0, 3.0, 4.0]
test_zygote(QuadraticInterpolation, u, t; name = "Quadratic Interpolation")
u2 = Matrix(hcat(u, u)')
test_zygote(
QuadraticInterpolation, u2, t; name = "Quadratic Interpolation with matrix input")
end

@testset "Constant Interpolation" begin
Expand Down

0 comments on commit 301f600

Please sign in to comment.