-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathlti.py
More file actions
337 lines (249 loc) · 9.94 KB
/
lti.py
File metadata and controls
337 lines (249 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#########################################################################################
##
## LINEAR TIME INVARIANT DYNAMICAL BLOCKS (blocks/lti.py)
##
## This module defines linear time invariant dynamical blocks
##
## Milan Rother 2024
##
#########################################################################################
# IMPORTS ===============================================================================
import numpy as np
from scipy.signal import ZerosPolesGain
from scipy.signal import TransferFunction as _TransferFunction
from ._block import Block
from ..utils.register import Register
from ..utils.gilbert import gilbert_realization
from ..utils.deprecation import deprecated
from ..optim.operator import DynamicOperator
from ..utils.mutable import mutable
# LTI BLOCKS ============================================================================
class StateSpace(Block):
"""Linear time invariant (LTI) multi input multi output (MIMO) state space model.
.. math::
\\begin{align}
\\dot{x} &= \\mathbf{A} x + \\mathbf{B} u \\\\
y &= \\mathbf{C} x + \\mathbf{D} u
\\end{align}
where `A`, `B`, `C` and `D` are the state space matrices, `x` is the state,
`u` the input and `y` the output vector.
Example
-------
A SISO state space block with two internal states can be initialized
like this:
.. code-block:: python
S = StateSpace(
A=-np.eye(2),
B=np.ones((2, 1)),
C=np.ones((1, 2)),
D=1.0
)
and a MIMO (2 in, 2 out) state space block with three internal states
can be initialized like this:
.. code-block:: python
S = StateSpace(
A=-np.eye(3),
B=np.ones((3, 2)),
C=np.ones((2, 3)),
D=np.ones((2, 2))
)
Parameters
----------
A, B, C, D : array_like
real valued state space matrices
initial_value : array_like, None
initial state / initial condition
Attributes
----------
op_dyn : DynamicOperator
internal dynamic operator for state equation
op_alg : DynamicOperator
internal algebraic operator for mapping to outputs
"""
def __init__(self,
A=-1.0, B=1.0, C=-1.0, D=1.0,
initial_value=None):
super().__init__()
#statespace matrices with input shape validation
self.A = np.atleast_2d(A)
self.B = np.atleast_1d(B)
self.C = np.atleast_1d(C)
self.D = np.atleast_1d(D)
#get statespace dimensions
n, _ = self.A.shape
if self.B.ndim == 1: n_in = 1
else: _, n_in = self.B.shape
if self.C.ndim == 1: n_out = 1
else: n_out, _ = self.C.shape
#set io channels
self.inputs = Register(n_in)
self.outputs = Register(n_out)
#initial condition and shape validation
if initial_value is None:
self.initial_value = np.zeros(n)
else:
self.initial_value = np.atleast_1d(initial_value)
#operators
self.op_dyn = DynamicOperator(
func=lambda x, u, t: np.dot(self.A, x) + np.dot(self.B, u),
jac_x=lambda x, u, t: self.A,
jac_u=lambda x, u, t: self.B
)
self.op_alg = DynamicOperator(
func=lambda x, u, t: np.dot(self.C, x) + np.dot(self.D, u),
jac_x=lambda x, u, t: self.C,
jac_u=lambda x, u, t: self.D
)
def __len__(self):
#check if direct passthrough exists
return int(np.any(self.D)) if self._active else 0
def solve(self, t, dt):
"""advance solution of implicit update equation of the solver
Parameters
----------
t : float
evaluation time
dt : float
integration timestep
Returns
-------
error : float
solver residual norm
"""
x, u = self.engine.state, self.inputs.to_array()
f, J = self.op_dyn(x, u, t), self.op_dyn.jac_x(x, u, t)
return self.engine.solve(f, J, dt)
def step(self, t, dt):
"""compute timestep update with integration engine
Parameters
----------
t : float
evaluation time
dt : float
integration timestep
Returns
-------
success : bool
step was successful
error : float
local truncation error from adaptive integrators
scale : float
timestep rescale from adaptive integrators
"""
x, u = self.engine.state, self.inputs.to_array()
f = self.op_dyn(x, u, t)
return self.engine.step(f, dt)
@mutable
class TransferFunctionPRC(StateSpace):
"""This block defines a LTI (MIMO for pole residue) transfer function.
The transfer function is defined in pole-residue-constant (PRC) form
.. math::
\\mathbf{H}(s) = \\mathbf{C} + \\sum_n^N \\frac{\\mathbf{R}_n}{s - p_n}
where 'Poles' are the scalar (possibly complex conjugate) poles of the
transfer function and 'Residues' are the possibly matrix valued (in MIMO case)
and complex conjugate residues of the transfer function. 'Const' has same
shape as 'Residues'.
Upon initialization, the state space realization of the transfer
function is computed using a minimal gilbert realization.
The resulting state space model of the form
.. math::
\\begin{align}
\\dot{x} &= \\mathbf{A} x + \\mathbf{B} u \\\\
y &= \\mathbf{C} x + \\mathbf{D} u
\\end{align}
is handled the same as the 'StateSpace' block, where `A`, `B`, `C` and `D`
are the state space matrices, `x` is the internal state, `u` the input and
`y` the output vector.
Parameters
----------
Poles : array
transfer function poles
Residues : array
transfer function residues
Const : array, float
constant term of transfer function
"""
def __init__(self, Poles=[], Residues=[], Const=0.0):
#parameters of transfer function in pole-residue-const form
self.Const, self.Poles, self.Residues = Const, Poles, Residues
#Statespace realization of transfer function
A, B, C, D = gilbert_realization(Poles, Residues, Const)
#initialize statespace model
super().__init__(A, B, C, D)
@deprecated(version="1.0.0", replacement="TransferFunctionPRC")
class TransferFunction(TransferFunctionPRC):
"""Alias for TransferFunctionPRC."""
pass
@mutable
class TransferFunctionZPG(StateSpace):
"""This block defines a LTI (SISO) transfer function.
The transfer function is defined in zeros-poles-gain (ZPG) form
.. math::
\\mathbf{H}(s) = k \\frac{(s - z_1)(s - z_2)\\cdots(s - z_m)}{(s - p_1)(s - p_2)\\cdots(s - p_n)}
where `Zeros` are the scalar (possibly complex conjugate) zeros of the
transfer function, and `Poles` are the poles (denominator zeros) of the
transfer function. `Gain` is the scalar factor `k`.
Upon initialization, the state space realization of the transfer function is
computed using `scipy.signal.ZerosPolesGain(Zeros, Poles, Gain).to_ss()`.
The resulting state space model of the form
.. math::
\\begin{align}
\\dot{x} &= \\mathbf{A} x + \\mathbf{B} u \\\\
y &= \\mathbf{C} x + \\mathbf{D} u
\\end{align}
is handled the same as the 'StateSpace' block, where `A`, `B`, `C` and `D`
are the state space matrices, `x` is the internal state, `u` the input and
`y` the output vector.
Parameters
----------
Poles : array_like
transfer function poles
Zeros : array_like
transfer function zeros
Gain : float
gain term of transfer function
"""
input_port_labels = {"in": 0}
output_port_labels = {"out":0}
def __init__(self, Zeros=[], Poles=[-1], Gain=1.0):
#parameters of transfer function in zeros-poles-gain form
self.Zeros, self.Poles, self.Gain = Zeros, Poles, Gain
#build scipy object -> convert to statespace
sp_SS = ZerosPolesGain(Zeros, Poles, Gain).to_ss()
#initialize statespace model
super().__init__(sp_SS.A, sp_SS.B, sp_SS.C, sp_SS.D)
@mutable
class TransferFunctionNumDen(StateSpace):
"""This block defines a LTI (SISO) transfer function.
The transfer function is defined in polynomial (numerator-denominator) form
.. math::
\\mathbf{H}(s) = \\frac{b_n + b_{n-1} s + \\dots + b_{0} s^n}{a_m + a_{m-1} s + \\dots + a_{0} s^m}
where `Num` is the list of numerator polynomial coefficients and `Den` the
list of denominator coefficients.
Upon initialization, the state space realization of the transfer function is
computed using `scipy.signal.TransferFunction(Num, Den).to_ss()`.
The resulting state space model of the form
.. math::
\\begin{align}
\\dot{x} &= \\mathbf{A} x + \\mathbf{B} u \\\\
y &= \\mathbf{C} x + \\mathbf{D} u
\\end{align}
is handled the same as the 'StateSpace' block, where `A`, `B`, `C` and `D`
are the state space matrices, `x` is the internal state, `u` the input and
`y` the output vector.
Parameters
----------
Num : array_like
numerator polynomial coefficients
Den : array_like
denominator polynomial coefficients
"""
input_port_labels = {"in": 0}
output_port_labels = {"out":0}
def __init__(self, Num=[1], Den=[1, 1]):
#parameters of transfer function in numerator-denominator
self.Num, self.Den = Num, Den
#build scipy object -> convert to statespace
sp_SS = _TransferFunction(Num, Den).to_ss()
#initialize statespace model
super().__init__(sp_SS.A, sp_SS.B, sp_SS.C, sp_SS.D)