Creating an array of equations in ModelingToolkit

I am trying to model a set of differential equations in ModelingToolkit. And I want to formulate it using vector variables. Namely, I will have a variable vector z = [z₁, z₂, z₃] (just a minimal example):

julia> using ModelingToolkit, OrdinaryDiffEq

julia> @parameters t
(t,)

julia> @variables z[1:3](t)
(Operation[z₁(t), z₂(t), z₃(t)],)

julia> @derivatives D'~t
((D'~t),)

julia> eqs = [D(z[i]) + z[i] ~ 0 for i in 1:3]
3-element Array{Equation,1}:
 Equation(derivative(z₁(t), t) + z₁(t), ModelingToolkit.Constant(0))
 Equation(derivative(z₂(t), t) + z₂(t), ModelingToolkit.Constant(0))
 Equation(derivative(z₃(t), t) + z₃(t), ModelingToolkit.Constant(0))

However, I am failing to create an ODESystem from the equations:

julia> sys = ODESystem(eqs)
ERROR: MethodError: Cannot `convert` an object of type 
  typeof(+) to an object of type 
  Variable
Closest candidates are:
  convert(::Type{Variable}, ::Operation) at /home/hurak/.julia/packages/ModelingToolkit/kfLoQ/src/ModelingToolkit.jl:77
  convert(::Type{T}, ::T) where T at essentials.jl:171
  Variable(::Any) at /home/hurak/.julia/packages/ModelingToolkit/kfLoQ/src/variables.jl:50
  ...
Stacktrace:
 [1] setindex!(::OrderedCollections.OrderedDict{Variable,Nothing}, ::Nothing, ::Function) at /home/hurak/.julia/packages/OrderedCollections/b4td4/src/ordered_dict.jl:292
 [2] push!(::OrderedCollections.OrderedSet{Variable}, ::Function) at /home/hurak/.julia/packages/OrderedCollections/b4td4/src/ordered_set.jl:25
 [3] ODESystem(::Array{Equation,1}, ::Nothing; kwargs::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}) at /home/hurak/.julia/packages/ModelingToolkit/kfLoQ/src/systems/diffeqs/odesystem.jl:122
 [4] ODESystem at /home/hurak/.julia/packages/ModelingToolkit/kfLoQ/src/systems/diffeqs/odesystem.jl:89 [inlined] (repeats 2 times)
 [5] top-level scope at none:1

Obviously the culprit is the addition on the left hand sides (if I leave just one of the two terms, things are fine) but I do want to have the sum there? What am I doing wrong? Thanks.

Probably a bug or a limitation of the parser, since this works:

eqs = [D(z[i]) ~ -z[i] for i in 1:3]

As a side note, this doesn’t work either:

eqs = [0 ~ D(z[i]) + z[i] for i in 1:3]
2 Likes

Open an issue

2 Likes