Skip to content

Conversation

simenhu
Copy link

@simenhu simenhu commented Jul 24, 2025

Checklist

  • Appropriate tests were added
  • Any code changes were done in a way that does not break public API
  • All documentation related to code changes were updated
  • The new code follows the
    contributor guidelines, in particular the SciML Style Guide and
    COLPRAC.
  • Any new documentation only uses public API

Additional context

The backsolve_adjoint functionality did not work when I used a ComponentVector as a state vector since axes(::ComponentVector) returns (1:1:M, ) and not (Base.OneTo(M), ) as other array types does afaik.

Switched the axis(...) call with size(...) to get an integer instead of a range, which seems to do the trick.

MWE to reproduce:

using OrdinaryDiffEq
using ComponentArrays
using SciMLSensitivity
using Enzyme

# Mass-damper system
function mass_damper!(du, u, p, t)
    mass, spring_k, damping_c = p
    position, velocity = u.state[1], u.state[2] # BUG nr. 1
    # position, velocity = u[1], u[2]  # BUG nr. 2
    du[1] = velocity  # dx/dt = v
    du[2] = (-spring_k * position - damping_c * velocity) / mass  # dv/dt = a

    nothing
end

# System parameters
mass = 1.0      # kg
spring_k = 10.0 # N/m (spring constant)
damping_c = 2.0 # Ns/m (damping coefficient)
p = [mass, spring_k, damping_c]


u0 = ComponentArray(state = [1.0, 0.0]) # BUG nr. 1
# u0 = [1.0, 0.0]  # BUG nr. 2

# Time span
tspan = (0.0, 5.0)
dt = 0.01

# Create the ODE problem
prob = ODEProblem(mass_damper!, u0, tspan, p)

# Solve with ORK256
println("Solving mass-damper system with ORK256...")
sol = solve(prob, ORK256(), dt=dt, dense=false)

function g(u,p, t)
    # Dummy function to test the adjoint sensitivity
    return sum(u .^ 2) ./ 2
end

res = adjoint_sensitivities(sol, ORK256(); g=g, dt=dt, sensealg=BacksolveAdjoint(autojacvec=EnzymeVJP()))
@info "Adjoint sensitivity results: $(res)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant