Skip to content

Bad error reporting when guess is missing #3185

@bradcarman

Description

@bradcarman

The following example is missing a guess value for the connector definition HydraulicPortMKR. Because of this when generating the ODEProblem I get a nasty StackOverFlow error. Adding a guess value of 0 for p(t) and m_dot(t) solves the issue. However, I only discovered this after a deep 1hr long dive into the model. It would be good to have the following features:

  1. better error reproting to identify the problem directly
  2. a feature that simply provides guess=0 for all variables missing a guess. Maybe a warning is issued if guess values are assumed, but in general it seems silly to put guess=0 next to 90% of the defined variables, and is a very easy thing to forget.

MWE:

using ModelingToolkit
using ModelingToolkit: t_nounits as t

rho0 = 1000
p0 = 0
beta = 1e9

rhof(p) = rho0 * (1 + (p -p0) / beta)

@connector function HydraulicPortMKR(; name)
    vars = @variables begin
      p(t), []
      m_dot(t), [connect = Flow]
    end
    return ODESystem(Equation[], t, vars, []; name)
end

@component function PressureSource(; name, p::Union{Float64,Int64,Nothing}=nothing)
    systems = @named begin
      port = HydraulicPortMKR()
    end
    params = @parameters begin
      (p::Float64 = p)
    end
    eqs = Equation[
      port.p ~ p
    ]
    return ODESystem(eqs, t, [], params; systems, name)
end

@component function LaminarOrifice(; name, k::Union{Float64,Int64,Nothing}=nothing)
    systems = @named begin
      a = HydraulicPortMKR()
      b = HydraulicPortMKR()
    end
    vars = @variables begin
      rho(t), [guess = 0.]
    end
    params = @parameters begin
      (k::Float64 = k)
    end
    eqs = Equation[
      rho ~ rhof(a.p)
      a.m_dot + b.m_dot ~ 0
      a.m_dot ~ k * (a.p - b.p)
    ]
    return ODESystem(eqs, t, vars, params; systems, name)
end

@component function System(; name)
    systems = @named begin
      pressSource1 = PressureSource(p=105325)
      pressSource2 = PressureSource(p=101325)
      res1 = LaminarOrifice(k=0.001)
      res2 = LaminarOrifice(k=0.001)
    end
    initialization_eqs = [
      # res1.a.m_dot ~ 0
    ]
    eqs = Equation[
      connect(pressSource1.port, res1.a)
      connect(res1.b, res2.a)
      connect(res2.b, pressSource2.port)
    ]
    return ODESystem(eqs, t, [], []; systems, name, initialization_eqs)
end

@mtkbuild model = System()
u0 = []
prob = ODEProblem(model, u0, (0, 5))  # ERROR: StackOverflowError

This is using ModelingToolkit v9.49.0

Metadata

Metadata

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