Skip to content

fix: fix observed function generation for systems with inputs #2795

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

Merged
merged 2 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/systems/diffeqs/odesystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -473,14 +473,18 @@ function build_explicit_observed_function(sys, ts;
ps = DestructuredArgs.(ps, inbounds = !checkbounds)
elseif has_index_cache(sys) && get_index_cache(sys) !== nothing
ps = DestructuredArgs.(reorder_parameters(get_index_cache(sys), ps))
if isempty(ps) && inputs !== nothing
ps = (:EMPTY,)
end
else
ps = (DestructuredArgs(ps, inbounds = !checkbounds),)
end
dvs = DestructuredArgs(unknowns(sys), inbounds = !checkbounds)
if inputs === nothing
args = [dvs, ps..., ivs...]
else
ipts = DestructuredArgs(unwrap.(inputs), inbounds = !checkbounds)
inputs = unwrap.(inputs)
ipts = DestructuredArgs(inputs, inbounds = !checkbounds)
args = [dvs, ipts, ps..., ivs...]
end
pre = get_postprocess_fbody(sys)
Expand Down
13 changes: 1 addition & 12 deletions src/systems/nonlinear/nonlinearsystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -306,18 +306,7 @@ function SciMLBase.NonlinearFunction{iip}(sys::NonlinearSystem, dvs = unknowns(s
_jac = nothing
end

observedfun = let sys = sys, dict = Dict()
function generated_observed(obsvar, u, p)
obs = get!(dict, value(obsvar)) do
build_explicit_observed_function(sys, obsvar)
end
if p isa MTKParameters
obs(u, p...)
else
obs(u, p)
end
end
end
observedfun = ObservedFunctionCache(sys)

NonlinearFunction{iip}(f,
sys = sys,
Expand Down
13 changes: 13 additions & 0 deletions test/input_output_handling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,16 @@ matrices, ssys = linearize(augmented_sys,
# P = ss(A,B,C,0)
# G = ss(matrices...)
# @test sminreal(G[1, 3]) ≈ sminreal(P[1,1])*dist

@testset "Observed functions with inputs" begin
@variables x(t)=0 u(t)=0 [input = true]
eqs = [
D(x) ~ -x + u
]

@named sys = ODESystem(eqs, t)
(; io_sys,) = ModelingToolkit.generate_control_function(sys, simplify = true)
obsfn = ModelingToolkit.build_explicit_observed_function(
io_sys, [x + u * t]; inputs = [u])
@test obsfn([1.0], [2.0], nothing, 3.0) == [7.0]
end
Loading