Skip to content

Cannot differentiate through kalman with explicit kwargs and ForwardDiff.jl #1105

Open

Description

@franckgaga

Using ControlSystemsBase.jl v1.25.4, I'm able to differentiate through kalman method, but not when I explicitly set the direct keyword argument. Here's a MRE:

using ControlSystemsBase
using ImplicitDifferentiation   # needed to support AD through `kalman` according to doc
using ComponentArrays           # needed to support AD through `kalman` according to doc
using ForwardDiff
using LinearAlgebra

function cost(p::T) where T <: Real
    A = [
        0.0  0.0
        0.0  p
    ]
    C = [1.0  0.0]
    R1 = Matrix{T}(undef, 2, 2)
    R1 .= [
        1.0 0.0
        0.0 1.0
    ]
    R2  = Matrix{T}(undef, 1, 1)
    R2 .= [1.0]
    
    #K    = kalman(Discrete, A, C, R1, R2, direct=true)            # fail
    #K    = kalman(Discrete, A, C, R1, R2, direct=false)           # fail
    #K, P = kalman(Discrete, A, C, R1, R2, extra=Val(false))       # fail
    #K, P = kalman(Discrete, A, C, R1, R2, extra=Val(true))        # fail
    K    = kalman(Discrete, A, C, R1, R2)                         # work
    
    @show size(K)

    return sum(K)
end

cost(0.1)
dcost_dp = ForwardDiff.derivative(cost, 0.1)

Context: this is required to support the SteadyKalmanFilter in the new feature introduced by this PR: JuliaControl/ModelPredictiveControl.jl#524. Now only the time-varying KalmanFilter is supported.

Thanks!

Activity

  1. franckgaga commented on Nov 18, 2026

    @franckgaga
    MemberAuthor

    The same issue with the extra keyword argument, by the way. I've modified the MRE above.

  2. changed the title [-]Cannot differentiate through `kalman` with `direct` kwarg and `ForwardDiff.jl`[/-] [+]Cannot differentiate through `kalman` with explicit kwargs and `ForwardDiff.jl`[/+] on Nov 18, 2026
  3. franckgaga commented on Nov 18, 2026

    @franckgaga
    MemberAuthor

    There is another issue. The returned K matrix has the incorrect size with autodiff. I've modified the MRE above once more. Here's what it prints:

    size(K) = (2, 1)
    size(K) = (1, 2)
    0.0
    

    You can see the the size is (2, 1) for Float64 and (1, 2) with ForwardDiff.Dual. A transpose is probably missing somewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions