SciML / ModelingToolkit.jl

An acausal modeling framework for automatically parallelized scientific machine learning (SciML) in Julia. A computer algebra system for integrated symbolics for physics-informed machine learning and automated transformations of differential equations
https://mtk.sciml.ai/dev/
Other
1.38k stars 196 forks source link

Custom independent variable leads to underdetermined initialization system #2818

Open hersle opened 1 week ago

hersle commented 1 week ago

This trivial example works as it should, where the independent parameter t is imported as ModelingToolkit.t_nounits:

using ModelingToolkit
using DifferentialEquations
using ModelingToolkit: t_nounits as t, D_nounits as d
@variables x(t)
@named sys1 = ODESystem([d(x) ~ 0], t; initialization_eqs = [x ~ t], guesses = [x => 0.0])
prob1 = ODEProblem(structural_simplify(sys1), [], (1.0, 2.0), [])
sol1 = solve(prob1)

Now run the same example, but using our own independent parameter (T instead of t) and differential (Dinstead of d):

using ModelingToolkit
using DifferentialEquations
@variables T; D = Differential(T) # only difference from first example
@variables x(T)
@named sys2 = ODESystem([D(x) ~ 0], T; initialization_eqs = [x ~ T], guesses = [x => 0.0])
prob2 = ODEProblem(structural_simplify(sys2), [], (1.0, 2.0), [])
sol2 = solve(prob2)

In the second example (and not the first), the initialization system becomes underdetermined, as reported by the warning

┌ Warning: Initialization system is underdetermined. 1 equations for 2 unknowns. Initialization will default to using least squares. To suppress this warning pass warn_initialize_determined = false.
└ @ ModelingToolkit ~/.julia/packages/ModelingToolkit/353ne/src/systems/diffeqs/abstractodesystem.jl:1564

By inspecting structural_simplify(generate_initializesystem(sys2); fully_determined = false), I see that the bug is caused by the independent parameter appearing twice, as both a parameter and unknown:

Model sys2 with 1 equations
Unknowns (2):
  T
  x(T) [defaults to 0.0]
Parameters (1):
  T

I expected the second example to behave like the first. This is with ModelingToolkit v9.19.0.

ChrisRackauckas commented 4 days ago

Yeah that's an odd bug. I'll see if I can look during JuliaCon.

AayushSabharwal commented 1 day ago

The problem (I'm fairly certain) is structural_simplify uses metadata to identify variables vs parameters. Since T is an @variable, it doesn't have the metadata and structural_simplify gets confused. The default indepvar works because it's an @parameter.