forked from python-control/python-control
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatesp.py
More file actions
1429 lines (1164 loc) · 49.2 KB
/
Copy pathstatesp.py
File metadata and controls
1429 lines (1164 loc) · 49.2 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""statesp.py
State space representation and functions.
This file contains the StateSpace class, which is used to represent linear
systems in state space. This is the primary representation for the
python-control library.
"""
# Python 3 compatibility (needs to go here)
from __future__ import print_function
from __future__ import division # for _convertToStateSpace
"""Copyright (c) 2010 by California Institute of Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the California Institute of Technology nor
the names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALTECH
OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Author: Richard M. Murray
Date: 24 May 09
Revised: Kevin K. Chen, Dec 10
$Id$
"""
import math
import numpy as np
from numpy import all, angle, any, array, asarray, concatenate, cos, delete, \
dot, empty, exp, eye, isinf, matrix, ones, pad, shape, sin, zeros, squeeze
from numpy.random import rand, randn
from numpy.linalg import solve, eigvals, matrix_rank
from numpy.linalg.linalg import LinAlgError
import scipy as sp
from scipy.signal import lti, cont2discrete
from warnings import warn
from .lti import LTI, timebase, timebaseEqual, isdtime
from .xferfcn import _convert_to_transfer_function
from copy import deepcopy
__all__ = ['StateSpace', 'ss', 'rss', 'drss', 'tf2ss', 'ssdata']
def _matrix(a):
"""Wrapper around numpy.matrix that reshapes empty matrices to be 0x0
Parameters
----------
a: sequence passed to numpy.matrix
Returns
-------
am: result of numpy.matrix(a), except if a is empty, am will be 0x0.
numpy.matrix([]) has size 1x0; for empty StateSpace objects, we
need 0x0 matrices, so use this instead of numpy.matrix in this
module.
"""
from numpy import matrix
am = matrix(a, dtype=float)
if (1, 0) == am.shape:
am.shape = (0, 0)
return am
class StateSpace(LTI):
"""StateSpace(A, B, C, D[, dt])
A class for representing state-space models
The StateSpace class is used to represent state-space realizations of linear
time-invariant (LTI) systems:
dx/dt = A x + B u
y = C x + D u
where u is the input, y is the output, and x is the state.
The main data members are the A, B, C, and D matrices. The class also
keeps track of the number of states (i.e., the size of A).
Discrete-time state space system are implemented by using the 'dt' instance
variable and setting it to the sampling period. If 'dt' is not None,
then it must match whenever two state space systems are combined.
Setting dt = 0 specifies a continuous system, while leaving dt = None
means the system timebase is not specified. If 'dt' is set to True, the
system will be treated as a discrete time system with unspecified
sampling time.
"""
def __init__(self, *args):
"""
StateSpace(A, B, C, D[, dt])
Construct a state space object.
The default constructor is StateSpace(A, B, C, D), where A, B, C, D
are matrices or equivalent objects. To create a discrete time system,
use StateSpace(A, B, C, D, dt) where 'dt' is the sampling time (or
True for unspecified sampling time). To call the copy constructor,
call StateSpace(sys), where sys is a StateSpace object.
"""
if len(args) == 4:
# The user provided A, B, C, and D matrices.
(A, B, C, D) = args
dt = None
elif len(args) == 5:
# Discrete time system
(A, B, C, D, dt) = args
elif len(args) == 1:
# Use the copy constructor.
if not isinstance(args[0], StateSpace):
raise TypeError("The one-argument constructor can only take in a StateSpace "
"object. Received %s." % type(args[0]))
A = args[0].A
B = args[0].B
C = args[0].C
D = args[0].D
try:
dt = args[0].dt
except NameError:
dt = None
else:
raise ValueError("Needs 1 or 4 arguments; received %i." % len(args))
A, B, C, D = [_matrix(M) for M in (A, B, C, D)]
# TODO: use super here?
LTI.__init__(self, inputs=D.shape[1], outputs=D.shape[0], dt=dt)
self.A = A
self.B = B
self.C = C
self.D = D
self.states = A.shape[1]
if 0 == self.states:
# static gain
# matrix's default "empty" shape is 1x0
A.shape = (0,0)
B.shape = (0,self.inputs)
C.shape = (self.outputs,0)
# Check that the matrix sizes are consistent.
if self.states != A.shape[0]:
raise ValueError("A must be square.")
if self.states != B.shape[0]:
raise ValueError("A and B must have the same number of rows.")
if self.states != C.shape[1]:
raise ValueError("A and C must have the same number of columns.")
if self.inputs != B.shape[1]:
raise ValueError("B and D must have the same number of columns.")
if self.outputs != C.shape[0]:
raise ValueError("C and D must have the same number of rows.")
# Check for states that don't do anything, and remove them.
self._remove_useless_states()
def _remove_useless_states(self):
"""Check for states that don't do anything, and remove them.
Scan the A, B, and C matrices for rows or columns of zeros. If the
zeros are such that a particular state has no effect on the input-output
dynamics, then remove that state from the A, B, and C matrices.
"""
# Search for useless states and get the indices of these states
# as an array.
ax1_A = np.where(~self.A.any(axis=1))[0]
ax1_B = np.where(~self.B.any(axis=1))[0]
ax0_A = np.where(~self.A.any(axis=0))[1]
ax0_C = np.where(~self.C.any(axis=0))[1]
useless_1 = np.intersect1d(ax1_A, ax1_B, assume_unique=True)
useless_2 = np.intersect1d(ax0_A, ax0_C, assume_unique=True)
useless = np.union1d(useless_1, useless_2)
# Remove the useless states.
self.A = delete(self.A, useless, 0)
self.A = delete(self.A, useless, 1)
self.B = delete(self.B, useless, 0)
self.C = delete(self.C, useless, 1)
self.states = self.A.shape[0]
self.inputs = self.B.shape[1]
self.outputs = self.C.shape[0]
def __str__(self):
"""String representation of the state space."""
str = "A = " + self.A.__str__() + "\n\n"
str += "B = " + self.B.__str__() + "\n\n"
str += "C = " + self.C.__str__() + "\n\n"
str += "D = " + self.D.__str__() + "\n"
# TODO: replace with standard calls to lti functions
if (type(self.dt) == bool and self.dt is True):
str += "\ndt unspecified\n"
elif (not (self.dt is None) and type(self.dt) != bool and self.dt > 0):
str += "\ndt = " + self.dt.__str__() + "\n"
return str
# represent as string, makes display work for IPython
__repr__ = __str__
# Negation of a system
def __neg__(self):
"""Negate a state space system."""
return StateSpace(self.A, self.B, -self.C, -self.D, self.dt)
# Addition of two state space systems (parallel interconnection)
def __add__(self, other):
"""Add two LTI systems (parallel connection)."""
# Check for a couple of special cases
if isinstance(other, (int, float, complex, np.number)):
# Just adding a scalar; put it in the D matrix
A, B, C = self.A, self.B, self.C
D = self.D + other
dt = self.dt
else:
other = _convertToStateSpace(other)
# Check to make sure the dimensions are OK
if ((self.inputs != other.inputs) or
(self.outputs != other.outputs)):
raise ValueError("Systems have different shapes.")
# Figure out the sampling time to use
if self.dt is None and other.dt is not None:
dt = other.dt # use dt from second argument
elif (other.dt is None and self.dt is not None) or \
(timebaseEqual(self, other)):
dt = self.dt # use dt from first argument
else:
raise ValueError("Systems have different sampling times")
# Concatenate the various arrays
A = concatenate((
concatenate((self.A, zeros((self.A.shape[0],
other.A.shape[-1]))),axis=1),
concatenate((zeros((other.A.shape[0], self.A.shape[-1])),
other.A),axis=1)
),axis=0)
B = concatenate((self.B, other.B), axis=0)
C = concatenate((self.C, other.C), axis=1)
D = self.D + other.D
return StateSpace(A, B, C, D, dt)
# Right addition - just switch the arguments
def __radd__(self, other):
"""Right add two LTI systems (parallel connection)."""
return self + other
# Subtraction of two state space systems (parallel interconnection)
def __sub__(self, other):
"""Subtract two LTI systems."""
return self + (-other)
def __rsub__(self, other):
"""Right subtract two LTI systems."""
return other + (-self)
# Multiplication of two state space systems (series interconnection)
def __mul__(self, other):
"""Multiply two LTI objects (serial connection)."""
# Check for a couple of special cases
if isinstance(other, (int, float, complex, np.number)):
# Just multiplying by a scalar; change the output
A, B = self.A, self.B
C = self.C * other
D = self.D * other
dt = self.dt
else:
other = _convertToStateSpace(other)
# Check to make sure the dimensions are OK
if self.inputs != other.outputs:
raise ValueError("C = A * B: A has %i column(s) (input(s)), \
but B has %i row(s)\n(output(s))." % (self.inputs, other.outputs))
# Figure out the sampling time to use
if (self.dt == None and other.dt != None):
dt = other.dt # use dt from second argument
elif (other.dt == None and self.dt != None) or \
(timebaseEqual(self, other)):
dt = self.dt # use dt from first argument
else:
raise ValueError("Systems have different sampling times")
# Concatenate the various arrays
A = concatenate(
(concatenate((other.A, zeros((other.A.shape[0], self.A.shape[1]))),
axis=1),
concatenate((self.B * other.C, self.A), axis=1)), axis=0)
B = concatenate((other.B, self.B * other.D), axis=0)
C = concatenate((self.D * other.C, self.C),axis=1)
D = self.D * other.D
return StateSpace(A, B, C, D, dt)
# Right multiplication of two state space systems (series interconnection)
# Just need to convert LH argument to a state space object
# TODO: __rmul__ only works for special cases (??)
def __rmul__(self, other):
"""Right multiply two LTI objects (serial connection)."""
# Check for a couple of special cases
if isinstance(other, (int, float, complex, np.number)):
# Just multiplying by a scalar; change the input
A, C = self.A, self.C
B = self.B * other
D = self.D * other
return StateSpace(A, B, C, D, self.dt)
# is lti, and convertible?
if isinstance(other, LTI):
return _convertToStateSpace(other) * self
# try to treat this as a matrix
try:
X = _matrix(other)
C = X * self.C
D = X * self.D
return StateSpace(self.A, self.B, C, D, self.dt)
except Exception as e:
print(e)
pass
raise TypeError("can't interconnect systems")
# TODO: __div__ and __rdiv__ are not written yet.
def __div__(self, other):
"""Divide two LTI systems."""
raise NotImplementedError("StateSpace.__div__ is not implemented yet.")
def __rdiv__(self, other):
"""Right divide two LTI systems."""
raise NotImplementedError("StateSpace.__rdiv__ is not implemented yet.")
def evalfr(self, omega):
"""Evaluate a SS system's transfer function at a single frequency.
self._evalfr(omega) returns the value of the transfer function matrix
with input value s = i * omega.
"""
warn("StateSpace.evalfr(omega) will be deprecated in a future "
"release of python-control; use evalfr(sys, omega*1j) instead",
PendingDeprecationWarning)
return self._evalfr(omega)
def _evalfr(self, omega):
"""Evaluate a SS system's transfer function at a single frequency"""
# Figure out the point to evaluate the transfer function
if isdtime(self, strict=True):
dt = timebase(self)
s = exp(1.j * omega * dt)
if omega * dt > math.pi:
warn("_evalfr: frequency evaluation above Nyquist frequency")
else:
s = omega * 1.j
return self.horner(s)
def horner(self, s):
"""Evaluate the systems's transfer function for a complex variable
Returns a matrix of values evaluated at complex variable s.
"""
resp = self.C * solve(s * eye(self.states) - self.A,
self.B) + self.D
return array(resp)
# Method for generating the frequency response of the system
def freqresp(self, omega):
"""
Evaluate the system's transfer func. at a list of freqs, omega.
mag, phase, omega = self.freqresp(omega)
Reports the frequency response of the system,
G(j*omega) = mag*exp(j*phase)
for continuous time. For discrete time systems, the response is
evaluated around the unit circle such that
G(exp(j*omega*dt)) = mag*exp(j*phase).
Inputs
------
omega: A list of frequencies in radians/sec at which the system
should be evaluated. The list can be either a python list
or a numpy array and will be sorted before evaluation.
Returns
-------
mag: The magnitude (absolute value, not dB or log10) of the system
frequency response.
phase: The wrapped phase in radians of the system frequency
response.
omega: The list of sorted frequencies at which the response
was evaluated.
"""
# In case omega is passed in as a list, rather than a proper array.
omega = np.asarray(omega)
numFreqs = len(omega)
Gfrf = np.empty((self.outputs, self.inputs, numFreqs),
dtype=np.complex128)
# Sort frequency and calculate complex frequencies on either imaginary
# axis (continuous time) or unit circle (discrete time).
omega.sort()
if isdtime(self, strict=True):
dt = timebase(self)
cmplx_freqs = exp(1.j * omega * dt)
if max(np.abs(omega)) * dt > math.pi:
warn("freqresp: frequency evaluation above Nyquist frequency")
else:
cmplx_freqs = omega * 1.j
# Do the frequency response evaluation. Use TB05AD from Slycot
# if it's available, otherwise use the built-in horners function.
try:
from slycot import tb05ad
n = np.shape(self.A)[0]
m = self.inputs
p = self.outputs
# The first call both evaluates C(sI-A)^-1 B and also returns
# Hessenberg transformed matrices at, bt, ct.
result = tb05ad(n, m, p, cmplx_freqs[0], self.A,
self.B, self.C, job='NG')
# When job='NG', result = (at, bt, ct, g_i, hinvb, info)
at = result[0]
bt = result[1]
ct = result[2]
# TB05AD frequency evaluation does not include direct feedthrough.
Gfrf[:, :, 0] = result[3] + self.D
# Now, iterate through the remaining frequencies using the
# transformed state matrices, at, bt, ct.
# Start at the second frequency, already have the first.
for kk, cmplx_freqs_kk in enumerate(cmplx_freqs[1:numFreqs]):
result = tb05ad(n, m, p, cmplx_freqs_kk, at,
bt, ct, job='NH')
# When job='NH', result = (g_i, hinvb, info)
# kk+1 because enumerate starts at kk = 0.
# but zero-th spot is already filled.
Gfrf[:, :, kk+1] = result[0] + self.D
except ImportError: # Slycot unavailable. Fall back to horner.
for kk, cmplx_freqs_kk in enumerate(cmplx_freqs):
Gfrf[:, :, kk] = self.horner(cmplx_freqs_kk)
# mag phase omega
return np.abs(Gfrf), np.angle(Gfrf), omega
# Compute poles and zeros
def pole(self):
"""Compute the poles of a state space system."""
return eigvals(self.A) if self.states else np.array([])
def zero(self):
"""Compute the zeros of a state space system."""
if not self.states:
return np.array([])
# Use AB08ND from Slycot if it's available, otherwise use
# scipy.lingalg.eigvals().
try:
from slycot import ab08nd
out = ab08nd(self.A.shape[0], self.B.shape[1], self.C.shape[0],
self.A, self.B, self.C, self.D)
nu = out[0]
if nu == 0:
return np.array([])
else:
return sp.linalg.eigvals(out[8][0:nu, 0:nu], out[9][0:nu, 0:nu])
except ImportError: # Slycot unavailable. Fall back to scipy.
if self.C.shape[0] != self.D.shape[1]:
raise NotImplementedError("StateSpace.zero only supports "
"systems with the same number of "
"inputs as outputs.")
# This implements the QZ algorithm for finding transmission zeros
# from
# https://dspace.mit.edu/bitstream/handle/1721.1/841/P-0802-06587335.pdf.
# The QZ algorithm solves the generalized eigenvalue problem: given
# `L = [A, B; C, D]` and `M = [I_nxn 0]`, find all finite lambda
# for which there exist nontrivial solutions of the equation
# `Lz - lamba Mz`.
#
# The generalized eigenvalue problem is only solvable if its
# arguments are square matrices.
L = concatenate((concatenate((self.A, self.B), axis=1),
concatenate((self.C, self.D), axis=1)), axis=0)
M = pad(eye(self.A.shape[0]), ((0, self.C.shape[0]),
(0, self.B.shape[1])), "constant")
return np.array([x for x in sp.linalg.eigvals(L, M, overwrite_a=True)
if not isinf(x)])
# Feedback around a state space system
def feedback(self, other=1, sign=-1):
"""Feedback interconnection between two LTI systems."""
other = _convertToStateSpace(other)
# Check to make sure the dimensions are OK
if (self.inputs != other.outputs) or (self.outputs != other.inputs):
raise ValueError("State space systems don't have compatible inputs/outputs for "
"feedback.")
# Figure out the sampling time to use
if self.dt is None and other.dt is not None:
dt = other.dt # use dt from second argument
elif other.dt is None and self.dt is not None or timebaseEqual(self, other):
dt = self.dt # use dt from first argument
else:
raise ValueError("Systems have different sampling times")
A1 = self.A
B1 = self.B
C1 = self.C
D1 = self.D
A2 = other.A
B2 = other.B
C2 = other.C
D2 = other.D
F = eye(self.inputs) - sign * D2 * D1
if matrix_rank(F) != self.inputs:
raise ValueError("I - sign * D2 * D1 is singular to working precision.")
# Precompute F\D2 and F\C2 (E = inv(F))
# We can solve two linear systems in one pass, since the
# coefficients matrix F is the same. Thus, we perform the LU
# decomposition (cubic runtime complexity) of F only once!
# The remaining back substitutions are only quadratic in runtime.
E_D2_C2 = solve(F, concatenate((D2, C2), axis=1))
E_D2 = E_D2_C2[:, :other.inputs]
E_C2 = E_D2_C2[:, other.inputs:]
T1 = eye(self.outputs) + sign * D1 * E_D2
T2 = eye(self.inputs) + sign * E_D2 * D1
A = concatenate((concatenate((A1 + sign * B1 * E_D2 * C1, sign * B1 * E_C2), axis=1),
concatenate((B2 * T1 * C1, A2 + sign * B2 * D1 * E_C2), axis=1)),
axis=0)
B = concatenate((B1 * T2, B2 * D1 * T2), axis=0)
C = concatenate((T1 * C1, sign * D1 * E_C2), axis=1)
D = D1 * T2
return StateSpace(A, B, C, D, dt)
def lft(self, other, nu=-1, ny=-1):
"""Return the Linear Fractional Transformation.
A definition of the LFT operator can be found in Appendix A.7,
page 512 in the 2nd Edition, Multivariable Feedback Control by
Sigurd Skogestad.
An alternative definition can be found here:
https://www.mathworks.com/help/control/ref/lft.html
Parameters
----------
other: LTI
The lower LTI system
ny: int, optional
Dimension of (plant) measurement output.
nu: int, optional
Dimension of (plant) control input.
"""
other = _convertToStateSpace(other)
# maximal values for nu, ny
if ny == -1:
ny = min(other.inputs, self.outputs)
if nu == -1:
nu = min(other.outputs, self.inputs)
# dimension check
# TODO
# Figure out the sampling time to use
if (self.dt == None and other.dt != None):
dt = other.dt # use dt from second argument
elif (other.dt == None and self.dt != None) or \
timebaseEqual(self, other):
dt = self.dt # use dt from first argument
else:
raise ValueError("Systems have different time bases")
# submatrices
A = self.A
B1 = self.B[:, :self.inputs - nu]
B2 = self.B[:, self.inputs - nu:]
C1 = self.C[:self.outputs - ny, :]
C2 = self.C[self.outputs - ny:, :]
D11 = self.D[:self.outputs - ny, :self.inputs - nu]
D12 = self.D[:self.outputs - ny, self.inputs - nu:]
D21 = self.D[self.outputs - ny:, :self.inputs - nu]
D22 = self.D[self.outputs - ny:, self.inputs - nu:]
# submatrices
Abar = other.A
Bbar1 = other.B[:, :ny]
Bbar2 = other.B[:, ny:]
Cbar1 = other.C[:nu, :]
Cbar2 = other.C[nu:, :]
Dbar11 = other.D[:nu, :ny]
Dbar12 = other.D[:nu, ny:]
Dbar21 = other.D[nu:, :ny]
Dbar22 = other.D[nu:, ny:]
# well-posed check
F = np.block([[np.eye(ny), -D22], [-Dbar11, np.eye(nu)]])
if matrix_rank(F) != ny + nu:
raise ValueError("lft not well-posed to working precision.")
# solve for the resulting ss by solving for [y, u] using [x,
# xbar] and [w1, w2].
TH = np.linalg.solve(F, np.block(
[[C2, np.zeros((ny, other.states)), D21, np.zeros((ny, other.inputs - ny))],
[np.zeros((nu, self.states)), Cbar1, np.zeros((nu, self.inputs - nu)), Dbar12]]
))
T11 = TH[:ny, :self.states]
T12 = TH[:ny, self.states: self.states + other.states]
T21 = TH[ny:, :self.states]
T22 = TH[ny:, self.states: self.states + other.states]
H11 = TH[:ny, self.states + other.states: self.states + other.states + self.inputs - nu]
H12 = TH[:ny, self.states + other.states + self.inputs - nu:]
H21 = TH[ny:, self.states + other.states: self.states + other.states + self.inputs - nu]
H22 = TH[ny:, self.states + other.states + self.inputs - nu:]
Ares = np.block([
[A + B2.dot(T21), B2.dot(T22)],
[Bbar1.dot(T11), Abar + Bbar1.dot(T12)]
])
Bres = np.block([
[B1 + B2.dot(H21), B2.dot(H22)],
[Bbar1.dot(H11), Bbar2 + Bbar1.dot(H12)]
])
Cres = np.block([
[C1 + D12.dot(T21), D12.dot(T22)],
[Dbar21.dot(T11), Cbar2 + Dbar21.dot(T12)]
])
Dres = np.block([
[D11 + D12.dot(H21), D12.dot(H22)],
[Dbar21.dot(H11), Dbar22 + Dbar21.dot(H12)]
])
return StateSpace(Ares, Bres, Cres, Dres, dt)
def minreal(self, tol=0.0):
"""Calculate a minimal realization, removes unobservable and
uncontrollable states"""
if self.states:
try:
from slycot import tb01pd
B = empty((self.states, max(self.inputs, self.outputs)))
B[:,:self.inputs] = self.B
C = empty((max(self.outputs, self.inputs), self.states))
C[:self.outputs,:] = self.C
A, B, C, nr = tb01pd(self.states, self.inputs, self.outputs,
self.A, B, C, tol=tol)
return StateSpace(A[:nr,:nr], B[:nr,:self.inputs],
C[:self.outputs,:nr], self.D)
except ImportError:
raise TypeError("minreal requires slycot tb01pd")
else:
return StateSpace(self)
# TODO: add discrete time check
def returnScipySignalLTI(self):
"""Return a list of a list of scipy.signal.lti objects.
For instance,
>>> out = ssobject.returnScipySignalLTI()
>>> out[3][5]
is a signal.scipy.lti object corresponding to the transfer function from
the 6th input to the 4th output."""
# Preallocate the output.
out = [[[] for _ in range(self.inputs)] for _ in range(self.outputs)]
for i in range(self.outputs):
for j in range(self.inputs):
out[i][j] = lti(asarray(self.A), asarray(self.B[:, j]),
asarray(self.C[i, :]), asarray(self.D[i, j]))
return out
def append(self, other):
"""Append a second model to the present model. The second
model is converted to state-space if necessary, inputs and
outputs are appended and their order is preserved"""
if not isinstance(other, StateSpace):
other = _convertToStateSpace(other)
if self.dt != other.dt:
raise ValueError("Systems must have the same time step")
n = self.states + other.states
m = self.inputs + other.inputs
p = self.outputs + other.outputs
A = zeros((n, n))
B = zeros((n, m))
C = zeros((p, n))
D = zeros((p, m))
A[:self.states, :self.states] = self.A
A[self.states:, self.states:] = other.A
B[:self.states, :self.inputs] = self.B
B[self.states:, self.inputs:] = other.B
C[:self.outputs, :self.states] = self.C
C[self.outputs:, self.states:] = other.C
D[:self.outputs, :self.inputs] = self.D
D[self.outputs:, self.inputs:] = other.D
return StateSpace(A, B, C, D, self.dt)
def __getitem__(self, indices):
"""Array style access"""
if len(indices) != 2:
raise IOError('must provide indices of length 2 for state space')
i = indices[0]
j = indices[1]
return StateSpace(self.A, self.B[:, j], self.C[i, :], self.D[i, j], self.dt)
def sample(self, Ts, method='zoh', alpha=None):
"""Convert a continuous time system to discrete time
Creates a discrete-time system from a continuous-time system by
sampling. Multiple methods of conversion are supported.
Parameters
----------
Ts : float
Sampling period
method : {"gbt", "bilinear", "euler", "backward_diff", "zoh"}
Which method to use:
* gbt: generalized bilinear transformation
* bilinear: Tustin's approximation ("gbt" with alpha=0.5)
* euler: Euler (or forward differencing) method ("gbt" with alpha=0)
* backward_diff: Backwards differencing ("gbt" with alpha=1.0)
* zoh: zero-order hold (default)
alpha : float within [0, 1]
The generalized bilinear transformation weighting parameter, which
should only be specified with method="gbt", and is ignored otherwise
Returns
-------
sysd : StateSpace system
Discrete time system, with sampling rate Ts
Notes
-----
Uses the command 'cont2discrete' from scipy.signal
Examples
--------
>>> sys = StateSpace(0, 1, 1, 0)
>>> sysd = sys.sample(0.5, method='bilinear')
"""
if not self.isctime():
raise ValueError("System must be continuous time system")
sys = (self.A, self.B, self.C, self.D)
Ad, Bd, C, D, dt = cont2discrete(sys, Ts, method, alpha)
return StateSpace(Ad, Bd, C, D, dt)
def dcgain(self):
"""Return the zero-frequency gain
The zero-frequency gain of a continuous-time state-space
system is given by:
.. math: G(0) = - C A^{-1} B + D
and of a discrete-time state-space system by:
.. math: G(1) = C (I - A)^{-1} B + D
Returns
-------
gain : ndarray
An array of shape (outputs,inputs); the array will either
be the zero-frequency (or DC) gain, or, if the frequency
response is singular, the array will be filled with np.nan.
"""
try:
if self.isctime():
gain = np.asarray(self.D-self.C.dot(np.linalg.solve(self.A, self.B)))
else:
gain = self.horner(1)
except LinAlgError:
# eigenvalue at DC
gain = np.tile(np.nan, (self.outputs, self.inputs))
return np.squeeze(gain)
# TODO: add discrete time check
def _convertToStateSpace(sys, **kw):
"""Convert a system to state space form (if needed).
If sys is already a state space, then it is returned. If sys is a transfer
function object, then it is converted to a state space and returned. If sys
is a scalar, then the number of inputs and outputs can be specified
manually, as in:
>>> sys = _convertToStateSpace(3.) # Assumes inputs = outputs = 1
>>> sys = _convertToStateSpace(1., inputs=3, outputs=2)
In the latter example, A = B = C = 0 and D = [[1., 1., 1.]
[1., 1., 1.]].
"""
from .xferfcn import TransferFunction
import itertools
if isinstance(sys, StateSpace):
if len(kw):
raise TypeError("If sys is a StateSpace, _convertToStateSpace \
cannot take keywords.")
# Already a state space system; just return it
return sys
elif isinstance(sys, TransferFunction):
try:
from slycot import td04ad
if len(kw):
raise TypeError("If sys is a TransferFunction, "
"_convertToStateSpace cannot take keywords.")
# Change the numerator and denominator arrays so that the transfer
# function matrix has a common denominator.
# matrices are also sized/padded to fit td04ad
num, den, denorder = sys.minreal()._common_den()
# transfer function to state space conversion now should work!
ssout = td04ad('C', sys.inputs, sys.outputs,
denorder, den, num, tol=0)
states = ssout[0]
return StateSpace(ssout[1][:states, :states], ssout[2][:states, :sys.inputs],
ssout[3][:sys.outputs, :states], ssout[4], sys.dt)
except ImportError:
# No Slycot. Scipy tf->ss can't handle MIMO, but static
# MIMO is an easy special case we can check for here
maxn = max(max(len(n) for n in nrow)
for nrow in sys.num)
maxd = max(max(len(d) for d in drow)
for drow in sys.den)
if 1 == maxn and 1 == maxd:
D = empty((sys.outputs, sys.inputs), dtype=float)
for i, j in itertools.product(range(sys.outputs), range(sys.inputs)):
D[i, j] = sys.num[i][j][0] / sys.den[i][j][0]
return StateSpace([], [], [], D, sys.dt)
else:
if sys.inputs != 1 or sys.outputs != 1:
raise TypeError("No support for MIMO without slycot")
# TODO: do we want to squeeze first and check dimenations?
# I think this will fail if num and den aren't 1-D after
# the squeeze
A, B, C, D = sp.signal.tf2ss(squeeze(sys.num), squeeze(sys.den))
return StateSpace(A, B, C, D, sys.dt)
elif isinstance(sys, (int, float, complex, np.number)):
if "inputs" in kw:
inputs = kw["inputs"]
else:
inputs = 1
if "outputs" in kw:
outputs = kw["outputs"]
else:
outputs = 1
# Generate a simple state space system of the desired dimension
# The following Doesn't work due to inconsistencies in ltisys:
# return StateSpace([[]], [[]], [[]], eye(outputs, inputs))
return StateSpace(0., zeros((1, inputs)), zeros((outputs, 1)),
sys * ones((outputs, inputs)))
# If this is a matrix, try to create a constant feedthrough
try:
D = _matrix(sys)
return StateSpace([], [], [], D)
except Exception as e:
print("Failure to assume argument is matrix-like in" \
" _convertToStateSpace, result %s" % e)
raise TypeError("Can't convert given type to StateSpace system.")
# TODO: add discrete time option
def _rss_generate(states, inputs, outputs, type):
"""Generate a random state space.
This does the actual random state space generation expected from rss and
drss. type is 'c' for continuous systems and 'd' for discrete systems.
"""
# Probability of repeating a previous root.
pRepeat = 0.05
# Probability of choosing a real root. Note that when choosing a complex
# root, the conjugate gets chosen as well. So the expected proportion of
# real roots is pReal / (pReal + 2 * (1 - pReal)).
pReal = 0.6
# Probability that an element in B or C will not be masked out.
pBCmask = 0.8
# Probability that an element in D will not be masked out.
pDmask = 0.3
# Probability that D = 0.
pDzero = 0.5
# Check for valid input arguments.
if states < 1 or states % 1:
raise ValueError("states must be a positive integer. states = %g." %
states)
if inputs < 1 or inputs % 1:
raise ValueError("inputs must be a positive integer. inputs = %g." %
inputs)
if outputs < 1 or outputs % 1:
raise ValueError("outputs must be a positive integer. outputs = %g." %
outputs)
# Make some poles for A. Preallocate a complex array.
poles = zeros(states) + zeros(states) * 0.j
i = 0
while i < states:
if rand() < pRepeat and i != 0 and i != states - 1:
# Small chance of copying poles, if we're not at the first or last
# element.
if poles[i-1].imag == 0:
# Copy previous real pole.
poles[i] = poles[i-1]
i += 1
else:
# Copy previous complex conjugate pair of poles.
poles[i:i+2] = poles[i-2:i]
i += 2
elif rand() < pReal or i == states - 1:
# No-oscillation pole.