Error creating a Dict with symbols as indices

I am trying to emulate some code I have been given, which returns a Dict that has model states from a ModelingToolkit model as indices. But the below code gives an error. Here’s the MWE:

using ModelingToolkit

function main()
	@parameters a
	@variables t x1(t)
	D = Differential(t)
	states = [x1]
	parameters = [a]

	@named model = ODESystem([
			D(x1) ~ a * x1,
		], t, states, parameters)

	state_vec = ModelingToolkit.states(model)
	state_dict = Dict[]
	state_dict[state_vec[1]] = "test"

and here is the error:

ERROR: LoadError: ArgumentError: invalid index: x1(t) of type SymbolicUtils.BasicSymbolic{Real}
  [1] to_index(i::SymbolicUtils.BasicSymbolic{Real})
    @ Base ./indices.jl:300
  [2] to_index(A::Vector{Dict}, i::SymbolicUtils.BasicSymbolic{Real})
    @ Base ./indices.jl:277
  [3] _to_indices1(A::Vector{Dict}, inds::Tuple{Base.OneTo{Int64}}, I1::SymbolicUtils.BasicSymbolic{Real})
    @ Base ./indices.jl:359
  [4] to_indices
    @ Base ./indices.jl:354 [inlined]
  [5] to_indices
    @ Base ./indices.jl:345 [inlined]
  [6] setindex!(A::Vector{Dict}, v::String, I::SymbolicUtils.BasicSymbolic{Real})
    @ Base ./abstractarray.jl:1393
  [7] main()
    @ Main ~/learning/ODETests/error.jl:16
  [8] top-level scope
    @ ~/learning/ODETests/error.jl:18
  [9] include(fname::String)
    @ Base.MainInclude ./client.jl:489
 [10] top-level scope
    @ REPL[1]:1
in expression starting at /home/orebas/learning/ODETests/error.jl:18
state_dict = Dict[]

This is a Vector{Dict}.
What you want is:

julia> state_dict = Dict()
Dict{Any, Any}()

Or you give the types, e.g.:

julia> state_dict = Dict{SymbolicUtils.BasicSymbolic{Real},String}()

Can’t test this right now, but perhaps you get what I mean and find the proper type.


Thank you, this solved my problem.

A slightly shorter version:

    state_dict = Dict{typeof(state_vec[]),String}()
1 Like

Or even shorter and clearer :slight_smile: