Skip to content

Commit 14cd42b

Browse files
committed
careful with state-space basis in interpolation
1 parent d45c0b4 commit 14cd42b

File tree

1 file changed

+71
-11
lines changed

1 file changed

+71
-11
lines changed

docs/src/batch_linearization.md

Lines changed: 71 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ eqs = [D(x) ~ v
3131
## Batch linearization
3232
To perform batch linearization, we create a vector of operating points, and then linearize the model around each of these points. The function [`batch_ss`](@ref) does this for us, and returns a vector of `StateSpace` models, one for each operating point. An operating point is a `Dict` that maps variables in the MTK model to numerical values. In the example below, we simply sample the variables uniformly within their bounds specified when we created the variables (normally, we might want to linearize on stationary points)
3333
```@example BATCHLIN
34-
N = 16 # Number of samples
34+
N = 5 # Number of samples
3535
xs = range(getbounds(x)[1], getbounds(x)[2], length=N)
3636
ops = Dict.(u.u => 0, x .=> xs)
3737
```
@@ -61,14 +61,19 @@ bodeplot(P, w, legend=:bottomright, adaptive=false) # Should look similar to the
6161

6262
## Controller tuning
6363
Let's also do some controller tuning for the linearized models above. The function `batch_tune` is not really required here, but it shows how we might go about building more sophisticated tools for batch tuning. In this example, we will tune a PID controller using the function [`loopshapingPID`](@ref). Note, this procedure is not limited to tuning a gain-scheduled PID controller, it should work for gain-scheduling of any LTI controller.
64+
65+
!!! "note" Interpolating between controllers
66+
There are multiple ways in which one could interpolate between different controllers. The two most common approaches are to interpolate their outputs, and interpolating their coefficients. When interpolating the coefficients, it is important to ensure that all controllers have the same structure for the interpolation to be meaningful. One may for example interpolate between PID coefficients, or between the coefficients of a state-space model. When interpolating state-space matrices, the systems must all share the same basis, i.e., the state variables must all have the same meaning among the interpolated systems. When converting a transfer function to state-space form, a numerical balancing is performed, this alters the meaning of the state variables and may introduce artificial dynamics to the interpolated system. We thus pass `balance=false` to the function `ss` to avoid this, or pick a form explicitly, e.g., `modal_form`.
67+
6468
```@example BATCHLIN
6569
function batch_tune(f, Ps)
6670
f.(Ps)
6771
end
6872
6973
Cs = batch_tune(Ps) do P
7074
C, kp, ki, kd, fig, CF = loopshapingPID(P, 7; Mt=1.2, Tf = 1/100)
71-
ss(CF)
75+
ss(CF, balance=false)
76+
modal_form(ss(CF, balance=true))[1]
7277
end
7378
7479
P = RobustAndOptimalControl.ss2particles(Ps)
@@ -103,7 +108,7 @@ using DataInterpolations # Required to interpolate between the controllers
103108
connect = ModelingToolkit.connect
104109
105110
closed_loop_eqs = [
106-
connect(ref.output, F.input)
111+
connect(ref.output, :r0, F.input)
107112
connect(F.output, :r, fb.input1) # Add an analysis point :r
108113
connect(duffing.y, :y, fb.input2) # Add an analysis point :y
109114
]
@@ -118,7 +123,7 @@ for C in Cs
118123
connect(Ci.output, duffing.u)
119124
]
120125
@named closed_loop = System(eqs, t, systems=[duffing, Ci, fb, ref, F])
121-
prob = ODEProblem(structural_simplify(closed_loop), [F.xd => 0], (0.0, 8.0))
126+
prob = ODEProblem(structural_simplify(closed_loop), [F.x => 0, F.xd => 0], (0.0, 8.0))
122127
sol = solve(prob, Rodas5P(), abstol=1e-8, reltol=1e-8)
123128
plot!(sol, idxs=[duffing.y.u, duffing.u.u], layout=2, lab="")
124129
end
@@ -128,39 +133,94 @@ end
128133
eqs = [
129134
closed_loop_eqs
130135
connect(fb.output, Cgs.input)
131-
connect(Cgs.output, duffing.u)
132-
connect(duffing.y, Cgs.scheduling_input) # Don't forget to connect the scheduling variable!
136+
connect(Cgs.output, :u, duffing.u)
137+
connect(duffing.y, :v, Cgs.scheduling_input) # Don't forget to connect the scheduling variable!
133138
]
134139
@named closed_loop = System(eqs, t, systems=[duffing, Cgs, fb, ref, F])
135140
prob = ODEProblem(structural_simplify(closed_loop), [F.xd => 0], (0.0, 8.0))
136-
sol = solve(prob, Rodas5P(), abstol=1e-8, reltol=1e-8, initializealg=SciMLBase.NoInit())
141+
sol = solve(prob, Rodas5P(), abstol=1e-8, reltol=1e-8, initializealg=SciMLBase.NoInit(), dtmax=0.01)
137142
plot!(sol, idxs=[duffing.y.u, duffing.u.u], l=(2, :red), lab="Gain scheduled")
138143
plot!(sol, idxs=F.output.u, l=(1, :black, :dash, 0.5), lab="Ref")
139144
```
140145

141-
If everything worked as expected, the gain-scheduled controller should perform better than each of the included controllers individually.
146+
If everything worked as expected, the gain-scheduled controller should perform reasonably well across the entire scheduling range.
142147

143148

144149
## C-Code generation
145-
We can generate C-code to interpolate our controller using the function [`SymbolicControlSystems.print_c_array`](@ref) from [SymbolicControlSystems.jl](https://github.com/JuliaControl/SymbolicControlSystems.jl). If the controller is a standard [`ControlSystemsBase.StateSpace`](@ref) object, a function that filters the input through the controller can be generated by calling [`SymbolicControlSystems.ccode`](@ref). But if the controller is a vector of controllers representing a gain-scheduled controller, a function that creates the interpolated dynamics is written. In the code below, we shorten the vector of controllers to make the generated C-code easier to read by passing `Cs[1:7:end]` and `xs[1:7:end]`
150+
We can generate C-code to interpolate our controller using the function [`SymbolicControlSystems.print_c_array`](@ref) from [SymbolicControlSystems.jl](https://github.com/JuliaControl/SymbolicControlSystems.jl). If the controller is a standard [`ControlSystemsBase.StateSpace`](@ref) object, a function that filters the input through the controller can be generated by calling [`SymbolicControlSystems.ccode`](@ref). But if the controller is a vector of controllers representing a gain-scheduled controller, a function that creates the interpolated dynamics is written. In the code below, we shorten the vector of controllers to make the generated C-code easier to read by passing `Cs[1:3:end]` and `xs[1:3:end]`
146151
```@example BATCHLIN
147152
using SymbolicControlSystems, ControlSystemsBase
148153
Cs_disc = c2d.(Cs, 0.05, :tustin) # Discretize the controller before generating code
149-
code = SymbolicControlSystems.print_c_array(stdout, Cs_disc[1:7:end], xs[1:7:end], "Cs")
154+
code = SymbolicControlSystems.print_c_array(stdout, Cs_disc[1:3:end], xs[1:3:end], "Cs")
150155
```
151156
The generated code starts by defining the interpolation vector `xs`, this variable is called `Cs_interp_vect` in the generated code. The code then defines all the ``A`` matrices as a 3-dimensional array, followed by a function that performs the interpolation `interpolate_Cs_A`. This function takes the output array as the first argument, a pointer to the 3D array with interpolation matrices, the interpolation vector as well as the interpolation variable `t`, in this document called ``v``. The same code is then repeated for the matrices ``B,C,D`` as well if they require interpolation (if they are all the same, no interpolation code is written).
152157

153158
## Linearize around a trajectory
154159
We can linearize around a trajectory obtained from `solve` using the function [`trajectory_ss`](@ref). We provide it with a vector of time points along the trajectory at which to linearize, and in this case we specify the inputs and outputs to linearize between as analysis points `r` and `y`.
155160
```@example BATCHLIN
156161
timepoints = 0:0.01:8
157-
Ps2, ssys = trajectory_ss(closed_loop, closed_loop.r, closed_loop.y, sol; t=timepoints, verbose=true)
162+
Ps2, ssys, ops2, resolved_ops = trajectory_ss(closed_loop, closed_loop.r, closed_loop.y, sol; t=timepoints, verbose=true);
158163
bodeplot(Ps2, w, legend=false)
159164
```
160165

161166
Internally, [`trajectory_ss`](@ref) works very much the same as [`batch_ss`](@ref), but constructs operating points automatically along the trajectory. This requires that the solution contains the states of the simplified system, accessible through the `idxs` argument like `sol(t, idxs=x)`. By linearizing the same system as we simulated, we ensure that this condition holds, doing so requires that we specify the inputs and outputs as analysis points rather than as variables.
162167

163168

169+
Notice how the peak of the transfer function changes along the trajectory. We can replicate the figure above by linearizing the plant and the controller individually, by providing the `loop_openings` argument. When linearizing the plant, we disconnect the controller input by passing `loop_openings=[closed_loop.u]`, and when linearizing the controller, we have various options for disconnecting the the plant:
170+
- Break the connection from plant output to controller input by passing `loop_openings=[closed_loop.y]`
171+
- Break the connection between the controller and the plant input by passing `loop_openings=[closed_loop.u]`
172+
- Break the connection `y` as well as the scheduling variable `v` (which is another form of feedback) by passing `loop_openings=[closed_loop.y, closed_loop.v]`
173+
174+
We will explore these options below, starting with the first option, breaking the connection `y`:
175+
```@example BATCHLIN
176+
kwargs = (; adaptive=false, legend=false)
177+
plants, _ = trajectory_ss(closed_loop, closed_loop.u, closed_loop.y, sol; t=timepoints, verbose=true, loop_openings=[closed_loop.u]);
178+
controllersy, ssy = trajectory_ss(closed_loop, closed_loop.r, closed_loop.u, sol; t=timepoints, verbose=true, loop_openings=[closed_loop.y]);
179+
180+
closed_loopsy = feedback.(plants .* controllersy)
181+
bodeplot(closed_loopsy, w; title="Loop open at y", kwargs...)
182+
```
183+
When we open the loop at `u`, we get a slightly different result:
184+
```@example BATCHLIN
185+
controllersu, ssu = trajectory_ss(closed_loop, closed_loop.r, closed_loop.u, sol; t=timepoints, verbose=true, loop_openings=[closed_loop.u]);
186+
187+
closed_loopsu = feedback.(plants .* controllersu)
188+
bodeplot(closed_loopsu, w; title="Loop open at u", kwargs...)
189+
```
190+
In this case, all static gains are 1. A similar result is obtained by explicitly breaking the scheduling feedback `v` in addition to an opening of `y`:
191+
```@example BATCHLIN
192+
controllersv, ssv = trajectory_ss(closed_loop, closed_loop.r, closed_loop.u, sol; t=timepoints, verbose=true, loop_openings=[closed_loop.y, closed_loop.v]);
193+
194+
closed_loopsv = feedback.(plants .* controllersv)
195+
bodeplot(closed_loopsv, w; title="Loop open at v and y", kwargs...)
196+
```
197+
198+
We have thus far treated the controller as a SISO system, but we could also view it as a system with two inputs, the measurement feedback and the scheduling feedback. For completeness, we show below how to derive the corresponding MIMO systems
199+
200+
```@example BATCHLIN
201+
plants_mimo, _ = trajectory_ss(closed_loop, closed_loop.u, [closed_loop.y, closed_loop.v], sol; t=timepoints, verbose=true, loop_openings=[closed_loop.u]);
202+
controllers_mimo, ssm = trajectory_ss(closed_loop, [closed_loop.r, closed_loop.v], closed_loop.u, sol; t=timepoints, verbose=true, loop_openings=[closed_loop.u]);
203+
204+
closed_loops_mimo = feedback.(controllers_mimo .* plants_mimo) # Look at complementary sensitivity function in the input, since this is a SISO system
205+
bodeplot(closed_loops_mimo, w; title="Loop open at MIMO", kwargs...)
206+
```
207+
208+
209+
210+
Why the discrepancy? We can understand the difference by comparing the Bode plots of the controllers.
211+
212+
```@example BATCHLIN
213+
plot(
214+
bodeplot(Cs, w, legend=false, plotphase=false, title="Designed controllers"),
215+
bodeplot(controllersy, w, legend=false, plotphase=false, title="Loop open at y"),
216+
bodeplot(controllersu, w, legend=false, plotphase=false, title="Loop open at u"),
217+
bodeplot(controllersv, w, legend=false, plotphase=false, title="Loop open at v and y"),
218+
)
219+
```
220+
if we open at both `y` and `v`, we only get the controller designed for the origin. If we open at `u`, we get controllers for the different values of the scheduling variable, and the corresponding measurement feedback (which is the same as the scheduling variable in this case).
221+
222+
However, if we only open at `y` we get controller linearizations that contains the closed loop through the scheduling connection `v`. The easiest way to ensure that the controller is properly disconnected from the plant while taking into account the different scheduling along the trajectory is thus to break at `u`.
223+
164224
## Summary
165225
We have seen how to
166226
- Perform linearization of a nonlinear ModelingToolkit model in multiple different operating points

0 commit comments

Comments
 (0)