Skip to content

build_function needs vector of independent variables #588

@baggepinnen

Description

@baggepinnen

When building a function with a CTarget I noticed that

MethodError: no method matching get_varnumber(::Operation, ::Variable{ModelingToolkit.Parameter{Number}})
Closest candidates are:
  get_varnumber(::Operation, !Matched::Array{Operation,1}) at /home/fredrikb/.julia/dev/ModelingToolkit/src/build_function.jl:463
  get_varnumber(::Operation, !Matched::Array{var"#s254",1} where var"#s254"<:Variable) at /home/fredrikb/.julia/dev/ModelingToolkit/src/build_function.jl:464
in include_string at base/loading.jl:1088

It works if I provide a vector of independent variables, but it would be nice if I could provide just time.

Example:

using OrdinaryDiffEq, ModelingToolkit
controller(t) = cos((t+5)^2)
function dynamics(dx, x, p, t)
      k, k₃, Jₘ, Jₐ, c, fa, tx = p
      q, θ, q̇, θ̇ = x

      u     = controller(t)
      Δq    = q - θ
      Δv    =- θ̇
      dx[1] = q̇
      dx[2] = θ̇
      dx[3] = -(k * Δq + k₃ * Δq^3 + c * Δv) + tx*u
      dx[4] =   k * Δq + k₃ * Δq^3 + c * Δv - fa*tanh(1000θ̇)

      dx[3] /= Jₘ
      dx[4] /= Jₐ
end


x0 = Float64[0, 0, 0, 0]
tspan = (0.0, 70)
p = [18e3, 10, 10, 3, 9, 100, 1000]
prob = ODEProblem(dynamics, x0, tspan, p)

@register controller(t)

sys = modelingtoolkitize(prob)
rhs = getfield.(sys.eqs, :rhs)


ccode = build_function(
      sys.eqs,
      states(sys),
      parameters(sys),
      [independent_variable(sys)], # I had to wrap this in a vector <------------------------------------------------------
      target = ModelingToolkit.CTarget(),
      lhsname = :dx,
      rhsnames = [:x, :params, :t],
)

Metadata

Metadata

Assignees

No one assigned

    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