diff --git a/src/systems/nonlinear/initializesystem.jl b/src/systems/nonlinear/initializesystem.jl index a79b44888e..becace8ec5 100644 --- a/src/systems/nonlinear/initializesystem.jl +++ b/src/systems/nonlinear/initializesystem.jl @@ -165,7 +165,16 @@ function generate_initializesystem(sys::ODESystem; [p for p in parameters(sys) if !haskey(paramsubs, p)] ) - eqs_ics = Symbolics.substitute.([eqs_ics; observed(sys)], (paramsubs,)) + # 7) use observed equations for guesses of observed variables if not provided + obseqs = observed(sys) + for eq in obseqs + haskey(defs, eq.lhs) && continue + any(x -> isequal(default_toterm(x), eq.lhs), keys(defs)) && continue + + defs[eq.lhs] = eq.rhs + end + + eqs_ics = Symbolics.substitute.([eqs_ics; obseqs], (paramsubs,)) vars = [vars; collect(values(paramsubs))] for k in keys(defs) defs[k] = substitute(defs[k], paramsubs) diff --git a/test/initializationsystem.jl b/test/initializationsystem.jl index f6ec724b14..de48821cff 100644 --- a/test/initializationsystem.jl +++ b/test/initializationsystem.jl @@ -836,3 +836,11 @@ end integ = init(prob, Rosenbrock23()) @test integ[y] ≈ -0.5 end + +@testset "Use observed equations for guesses of observed variables" begin + @variables x(t) y(t) [state_priority = 100] + @mtkbuild sys = ODESystem( + [D(x) ~ x + t, y ~ 2x + 1], t; initialization_eqs = [x^3 + y^3 ~ 1]) + isys = ModelingToolkit.generate_initializesystem(sys) + @test isequal(defaults(isys)[y], 2x + 1) +end