@@ -60,39 +60,61 @@ function generate_f_h(model, inputs, outputs)
6060 if any(ModelingToolkit.is_alg_equation, equations(io_sys))
6161 error("Systems with algebraic equations are not supported")
6262 end
63- h_ = ModelingToolkit.build_explicit_observed_function(io_sys, outputs; inputs = inputs)
64- nx = length(dvs)
63+ nu, nx, ny = length(inputs), length(dvs), length(outputs)
6564 vx = string.(dvs)
66- par = varmap_to_vars(defaults(io_sys), psym)
67- function f!(ẋ, x, u, _ , _ )
68- f_ip(ẋ, x, u, par, 1)
69- nothing
65+ p = varmap_to_vars(defaults(io_sys), psym)
66+ function f!(ẋ, x, u, _ , p)
67+ try
68+ f_ip(ẋ, x, u, p, nothing)
69+ catch err
70+ if err isa MethodError
71+ error("NonLinModel does not support a time argument t in the f function, "*
72+ "see the constructor docstring for a workaround.")
73+ else
74+ rethrow()
75+ end
76+ end
77+ return nothing
7078 end
71- function h!(y, x, _ , _ )
72- y .= h_(x, 1, par, 1)
73- nothing
79+ h_ = ModelingToolkit.build_explicit_observed_function(io_sys, outputs; inputs)
80+ u_nothing = fill(nothing, nu)
81+ function h!(y, x, _ , p)
82+ y .= try
83+ # MTK.jl supports a `u` argument in `h_` function but not this package. We set
84+ # `u` as a vector of nothing and `h_` function will presumably throw an
85+ # MethodError it this argument is used inside the function
86+ h_(x, u_nothing, p, nothing)
87+ catch err
88+ if err isa MethodError
89+ error("NonLinModel only support strictly proper systems (no manipulated "*
90+ "input argument u in the output function h)")
91+ else
92+ rethrow()
93+ end
94+ end
95+ return nothing
7496 end
75- return f!, h!, nx , vx
97+ return f!, h!, p, nu, nx, ny , vx
7698end
7799inputs, outputs = [mtk_model.τ], [mtk_model.y]
78- f!, h!, nx , vx = generate_f_h(mtk_model, inputs, outputs)
79- nu, ny, Ts = length(inputs), length(outputs), 0.1
100+ f!, h!, p, nu, nx, ny , vx = generate_f_h(mtk_model, inputs, outputs)
101+ Ts = 0.1
80102vu, vy = ["\$τ\$ (Nm)"], ["\$θ\$ (°)"]
81103nothing # hide
82104```
83105
84106A [ ` NonLinModel ` ] ( @ref ) can now be constructed:
85107
86108``` @example 1
87- model = setname!(NonLinModel(f!, h!, Ts, nu, nx, ny); u=vu, x=vx, y=vy)
109+ model = setname!(NonLinModel(f!, h!, Ts, nu, nx, ny; p ); u=vu, x=vx, y=vy)
88110```
89111
90112We also instantiate a plant model with a 25 % larger friction coefficient `` K `` :
91113
92114``` @example 1
93115mtk_model.K = defaults(mtk_model)[mtk_model.K] * 1.25
94- f_plant, h_plant, _, _ = generate_f_h(mtk_model, inputs, outputs)
95- plant = setname!(NonLinModel(f_plant, h_plant, Ts, nu, nx, ny); u=vu, x=vx, y=vy)
116+ f_plant, h_plant, p = generate_f_h(mtk_model, inputs, outputs)
117+ plant = setname!(NonLinModel(f_plant, h_plant, Ts, nu, nx, ny; p ); u=vu, x=vx, y=vy)
96118```
97119
98120## Controller Design
0 commit comments