-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathstatesp.py
More file actions
2578 lines (2106 loc) · 90.4 KB
/
statesp.py
File metadata and controls
2578 lines (2106 loc) · 90.4 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 class and related functions
#
# Initial author: Richard M. Murray
# Creation date: 24 May 2009
# Pre-2014 revisions: Kevin K. Chen, Dec 2010
# Use `git shortlog -n -s statesp.py` for full list of contributors
"""State space class and related functions.
This module contains the `StateSpace class`, which is used to
represent linear systems in state space.
"""
import math
import sys
from collections.abc import Iterable
from warnings import warn
import numpy as np
import scipy as sp
import scipy.linalg
from numpy import array # noqa: F401
from numpy import any, asarray, concatenate, cos, delete, empty, exp, eye, \
isinf, pad, sin, squeeze, zeros
from numpy.linalg import LinAlgError, eigvals, matrix_rank, solve
from numpy.random import rand, randn
from scipy.signal import StateSpace as signalStateSpace
from scipy.signal import cont2discrete
import control
from . import bdalg, config
from .exception import ControlDimension, ControlMIMONotImplemented, \
ControlSlycot, slycot_check
from .frdata import FrequencyResponseData
from .iosys import InputOutputSystem, NamedSignal, _process_iosys_keywords, \
_process_signal_list, _process_subsys_index, common_timebase, issiso
from .lti import LTI, _process_frequency_response
from .mateqn import _check_shape
from .nlsys import InterconnectedSystem, NonlinearIOSystem
try:
from slycot import ab13dd
except ImportError:
ab13dd = None
__all__ = ['StateSpace', 'LinearICSystem', 'ss2io', 'tf2io', 'tf2ss',
'ssdata', 'linfnorm', 'ss', 'rss', 'drss', 'summing_junction']
# Define module default parameter values
_statesp_defaults = {
'statesp.remove_useless_states': False,
'statesp.latex_num_format': '.3g',
'statesp.latex_repr_type': 'partitioned',
'statesp.latex_maxsize': 10,
}
class StateSpace(NonlinearIOSystem, LTI):
r"""StateSpace(A, B, C, D[, dt])
State space representation for LTI input/output systems.
The StateSpace class is used to represent state-space realizations of
linear time-invariant (LTI) systems:
.. math::
dx/dt &= A x + B u \\
y &= C x + D u
where :math:`u` is the input, :math:`y` is the output, and
:math:`x` is the state. State space systems are usually created
with the `ss` factory function.
Parameters
----------
A, B, C, D : array_like
System matrices of the appropriate dimensions.
dt : None, True or float, optional
System timebase. 0 (default) indicates continuous time, True
indicates discrete time with unspecified sampling time, positive
number is discrete time with specified sampling time, None
indicates unspecified timebase (either continuous or discrete time).
Attributes
----------
ninputs, noutputs, nstates : int
Number of input, output and state variables.
shape : tuple
2-tuple of I/O system dimension, (noutputs, ninputs).
input_labels, output_labels, state_labels : list of str
Names for the input, output, and state variables.
name : string, optional
System name.
See Also
--------
ss, InputOutputSystem, NonlinearIOSystem
Notes
-----
The main data members in the `StateSpace` class are the A, B, C, and D
matrices. The class also keeps track of the number of states (i.e.,
the size of A).
A discrete-time system is created by specifying a nonzero 'timebase', dt
when the system is constructed:
* `dt` = 0: continuous-time system (default)
* `dt` > 0: discrete-time system with sampling period `dt`
* `dt` = True: discrete time with unspecified sampling period
* `dt` = None: no timebase specified
Systems must have compatible timebases in order to be combined. A
discrete-time system with unspecified sampling time (`dt` = True) can
be combined with a system having a specified sampling time; the result
will be a discrete-time system with the sample time of the other
system. Similarly, a system with timebase None can be combined with a
system having any timebase; the result will have the timebase of the
other system. The default value of dt can be changed by changing the
value of `config.defaults['control.default_dt']`.
A state space system is callable and returns the value of the transfer
function evaluated at a point in the complex plane. See
`StateSpace.__call__` for a more detailed description.
Subsystems corresponding to selected input/output pairs can be
created by indexing the state space system::
subsys = sys[output_spec, input_spec]
The input and output specifications can be single integers, lists of
integers, or slices. In addition, the strings representing the names
of the signals can be used and will be replaced with the equivalent
signal offsets. The subsystem is created by truncating the inputs and
outputs, but leaving the full set of system states.
StateSpace instances have support for IPython HTML/LaTeX output, intended
for pretty-printing in Jupyter notebooks. The HTML/LaTeX output can be
configured using `config.defaults['statesp.latex_num_format']`
and `config.defaults['statesp.latex_repr_type']`. The
HTML/LaTeX output is tailored for MathJax, as used in Jupyter, and
may look odd when typeset by non-MathJax LaTeX systems.
`config.defaults['statesp.latex_num_format']` is a format string
fragment, specifically the part of the format string after '{:'
used to convert floating-point numbers to strings. By default it
is '.3g'.
`config.defaults['statesp.latex_repr_type']` must either be
'partitioned' or 'separate'. If 'partitioned', the A, B, C, D
matrices are shown as a single, partitioned matrix; if
'separate', the matrices are shown separately.
"""
def __init__(self, *args, **kwargs):
"""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.
See `StateSpace` and `ss` for more information.
"""
#
# Process positional arguments
#
if len(args) == 4:
# The user provided A, B, C, and D matrices.
A, B, C, D = args
elif len(args) == 5:
# Discrete time system
A, B, C, D, dt = args
if 'dt' in kwargs:
warn("received multiple dt arguments, "
"using positional arg dt = %s" % dt)
kwargs['dt'] = dt
args = args[:-1]
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
if 'dt' not in kwargs:
kwargs['dt'] = args[0].dt
else:
raise TypeError(
"Expected 1, 4, or 5 arguments; received %i." % len(args))
# Convert all matrices to standard form (sizes checked later)
A = _ssmatrix(A, square=True, name="A")
B = _ssmatrix(
B, axis=0 if np.asarray(B).ndim == 1 and len(B) == A.shape[0]
else 1, name="B")
C = _ssmatrix(
C, axis=1 if np.asarray(C).ndim == 1 and len(C) == A.shape[0]
else 0, name="C")
if np.isscalar(D) and D == 0 and B.shape[1] > 0 and C.shape[0] > 0:
# If D is a scalar zero, broadcast it to the proper size
D = np.zeros((C.shape[0], B.shape[1]))
D = _ssmatrix(D, name="D")
# If only direct term is present, adjust sizes of C and D if needed
if D.size > 0 and B.size == 0:
B = np.zeros((0, D.shape[1]))
if D.size > 0 and C.size == 0:
C = np.zeros((D.shape[0], 0))
# Matrices defining the linear system
self.A = A
self.B = B
self.C = C
self.D = D
# Determine if the system is static (memoryless)
static = (A.size == 0)
#
# Process keyword arguments
#
remove_useless_states = kwargs.pop(
'remove_useless_states',
config.defaults['statesp.remove_useless_states'])
# Process iosys keywords
defaults = args[0] if len(args) == 1 else \
{'inputs': B.shape[1], 'outputs': C.shape[0],
'states': A.shape[0]}
name, inputs, outputs, states, dt = _process_iosys_keywords(
kwargs, defaults, static=static)
# Create updfcn and outfcn
updfcn = lambda t, x, u, params: \
self.A @ np.atleast_1d(x) + self.B @ np.atleast_1d(u)
outfcn = lambda t, x, u, params: \
self.C @ np.atleast_1d(x) + self.D @ np.atleast_1d(u)
# Initialize NonlinearIOSystem object
super().__init__(
updfcn, outfcn,
name=name, inputs=inputs, outputs=outputs,
states=states, dt=dt, **kwargs)
# Reset shapes if the system is static
if static:
A.shape = (0, 0)
B.shape = (0, self.ninputs)
C.shape = (self.noutputs, 0)
# Check to make sure everything is consistent
_check_shape(A, self.nstates, self.nstates, name="A")
_check_shape(B, self.nstates, self.ninputs, name="B")
_check_shape(C, self.noutputs, self.nstates, name="C")
_check_shape(D, self.noutputs, self.ninputs, name="D")
#
# Final processing
#
# Check for states that don't do anything, and remove them
if remove_useless_states:
self._remove_useless_states()
#
# Class attributes
#
# These attributes are defined as class attributes so that they are
# documented properly. They are "overwritten" in __init__.
#
#: Number of system inputs.
#:
#: :meta hide-value:
ninputs = 0
#: Number of system outputs.
#:
#: :meta hide-value:
noutputs = 0
#: Number of system states.
#:
#: :meta hide-value:
nstates = 0
#: Dynamics matrix.
#:
#: :meta hide-value:
A = []
#: Input matrix.
#:
#: :meta hide-value:
B = []
#: Output matrix.
#:
#: :meta hide-value:
C = []
#: Direct term.
#:
#: :meta hide-value:
D = []
#
# Getter and setter functions for legacy state attributes
#
# For this iteration, generate a deprecation warning whenever the
# getter/setter is called. For a future iteration, turn it into a
# future warning, so that users will see it.
#
def _get_states(self):
warn("The StateSpace `states` attribute will be deprecated in a "
"future release. Use `nstates` instead.",
FutureWarning, stacklevel=2)
return self.nstates
def _set_states(self, value):
warn("The StateSpace `states` attribute will be deprecated in a "
"future release. Use `nstates` instead.",
FutureWarning, stacklevel=2)
self.nstates = value
#: Deprecated attribute; use `nstates` instead.
#:
#: The `state` attribute was used to store the number of states for : a
#: state space system. It is no longer used. If you need to access the
#: number of states, use `nstates`.
states = property(_get_states, _set_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 indices of these states.
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)
# Remove any state names that we don't need
self.set_states(
[self.state_labels[i] for i in range(self.nstates)
if i not in useless])
def __str__(self):
"""Return string representation of the state space system."""
string = f"{InputOutputSystem.__str__(self)}\n\n"
string += "\n\n".join([
"{} = {}".format(Mvar,
"\n ".join(str(M).splitlines()))
for Mvar, M in zip(["A", "B", "C", "D"],
[self.A, self.B, self.C, self.D])])
return string
def _repr_eval_(self):
# Loadable format
out = "StateSpace(\n{A},\n{B},\n{C},\n{D}".format(
A=self.A.__repr__(), B=self.B.__repr__(),
C=self.C.__repr__(), D=self.D.__repr__())
out += super()._dt_repr(separator=",\n", space="")
if len(labels := super()._label_repr()) > 0:
out += ",\n" + labels
out += ")"
return out
def _repr_html_(self):
"""HTML representation of state-space model.
Output is controlled by config options statesp.latex_repr_type,
statesp.latex_num_format, and statesp.latex_maxsize.
The output is primarily intended for Jupyter notebooks, which
use MathJax to render the LaTeX, and the results may look odd
when processed by a 'conventional' LaTeX system.
Returns
-------
s : str
HTML/LaTeX representation of model, or None if either matrix
dimension is greater than statesp.latex_maxsize.
"""
syssize = self.nstates + max(self.noutputs, self.ninputs)
if syssize > config.defaults['statesp.latex_maxsize']:
return None
elif config.defaults['statesp.latex_repr_type'] == 'partitioned':
return super()._repr_info_(html=True) + \
"\n" + self._latex_partitioned()
elif config.defaults['statesp.latex_repr_type'] == 'separate':
return super()._repr_info_(html=True) + \
"\n" + self._latex_separate()
else:
raise ValueError(
"Unknown statesp.latex_repr_type '{cfg}'".format(
cfg=config.defaults['statesp.latex_repr_type']))
def _latex_partitioned_stateless(self):
"""`Partitioned` matrix LaTeX representation for stateless systems
Model is presented as a matrix, D. No partition lines are shown.
Returns
-------
s : str
LaTeX representation of model.
"""
# Apply NumPy formatting
with np.printoptions(threshold=sys.maxsize):
D = eval(repr(self.D))
lines = [
r'$$',
(r'\left['
+ r'\begin{array}'
+ r'{' + 'rll' * self.ninputs + '}')
]
for Di in asarray(D):
lines.append('&'.join(_f2s(Dij) for Dij in Di)
+ '\\\\')
lines.extend([
r'\end{array}'
r'\right]',
r'$$'])
return '\n'.join(lines)
def _latex_partitioned(self):
"""Partitioned matrix LaTeX representation of state-space model
Model is presented as a matrix partitioned into A, B, C, and D
parts.
Returns
-------
s : str
LaTeX representation of model.
"""
if self.nstates == 0:
return self._latex_partitioned_stateless()
# Apply NumPy formatting
with np.printoptions(threshold=sys.maxsize):
A, B, C, D = (
eval(repr(getattr(self, M))) for M in ['A', 'B', 'C', 'D'])
lines = [
r'$$',
(r'\left['
+ r'\begin{array}'
+ r'{' + 'rll' * self.nstates + '|' + 'rll' * self.ninputs + '}')
]
for Ai, Bi in zip(asarray(A), asarray(B)):
lines.append('&'.join([_f2s(Aij) for Aij in Ai]
+ [_f2s(Bij) for Bij in Bi])
+ '\\\\')
lines.append(r'\hline')
for Ci, Di in zip(asarray(C), asarray(D)):
lines.append('&'.join([_f2s(Cij) for Cij in Ci]
+ [_f2s(Dij) for Dij in Di])
+ '\\\\')
lines.extend([
r'\end{array}'
+ r'\right]',
r'$$'])
return '\n'.join(lines)
def _latex_separate(self):
"""Separate matrices LaTeX representation of state-space model
Model is presented as separate, named, A, B, C, and D matrices.
Returns
-------
s : str
LaTeX representation of model.
"""
lines = [
r'$$',
r'\begin{array}{ll}',
]
def fmt_matrix(matrix, name):
matlines = [name
+ r' = \left[\begin{array}{'
+ 'rll' * matrix.shape[1]
+ '}']
for row in asarray(matrix):
matlines.append('&'.join(_f2s(entry) for entry in row)
+ '\\\\')
matlines.extend([
r'\end{array}'
r'\right]'])
return matlines
if self.nstates > 0:
lines.extend(fmt_matrix(self.A, 'A'))
lines.append('&')
lines.extend(fmt_matrix(self.B, 'B'))
lines.append('\\\\')
lines.extend(fmt_matrix(self.C, 'C'))
lines.append('&')
lines.extend(fmt_matrix(self.D, 'D'))
lines.extend([
r'\end{array}',
r'$$'])
return '\n'.join(lines)
# 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)."""
from .xferfcn import TransferFunction
# Convert transfer functions to state space
if isinstance(other, TransferFunction):
# Convert the other argument to state space
other = _convert_to_statespace(other)
# 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
elif isinstance(other, np.ndarray):
other = np.atleast_2d(other)
# Special case for SISO
if self.issiso():
self = np.ones_like(other) * self
if self.ninputs != other.shape[0]:
raise ValueError("array has incompatible shape")
A, B, C = self.A, self.B, self.C
D = self.D + other
dt = self.dt
elif not isinstance(other, StateSpace):
return NotImplemented # let other.__rmul__ handle it
else:
# Promote SISO object to compatible dimension
if self.issiso() and not other.issiso():
self = np.ones((other.noutputs, other.ninputs)) * self
elif not self.issiso() and other.issiso():
other = np.ones((self.noutputs, self.ninputs)) * other
# Check to make sure the dimensions are OK
if ((self.ninputs != other.ninputs) or
(self.noutputs != other.noutputs)):
raise ValueError(
"can't add systems with incompatible inputs and outputs")
dt = common_timebase(self.dt, other.dt)
# 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)."""
from .xferfcn import TransferFunction
# Convert transfer functions to state space
if isinstance(other, TransferFunction):
# Convert the other argument to state space
other = _convert_to_statespace(other)
# Check for a couple of special cases
if isinstance(other, (int, float, complex, np.number)):
# Just multiplying by a scalar; change the output
A, C = self.A, self.C
B = self.B * other
D = self.D * other
dt = self.dt
elif isinstance(other, np.ndarray):
other = np.atleast_2d(other)
# Special case for SISO
if self.issiso():
self = bdalg.append(*([self] * other.shape[0]))
# Dimension check after broadcasting
if self.ninputs != other.shape[0]:
raise ValueError("array has incompatible shape")
A, C = self.A, self.C
B = self.B @ other
D = self.D @ other
dt = self.dt
elif not isinstance(other, StateSpace):
return NotImplemented # let other.__rmul__ handle it
else:
# Promote SISO object to compatible dimension
if self.issiso() and not other.issiso():
self = bdalg.append(*([self] * other.noutputs))
elif not self.issiso() and other.issiso():
other = bdalg.append(*([other] * self.ninputs))
# Check to make sure the dimensions are OK
if self.ninputs != other.noutputs:
raise ValueError(
"can't multiply systems with incompatible"
" inputs and outputs")
dt = common_timebase(self.dt, other.dt)
# 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
def __rmul__(self, other):
"""Right multiply two LTI objects (serial connection)."""
from .xferfcn import TransferFunction
# Convert transfer functions to state space
if isinstance(other, TransferFunction):
# Convert the other argument to state space
other = _convert_to_statespace(other)
# Check for a couple of special cases
if isinstance(other, (int, float, complex, np.number)):
# Just multiplying by a scalar; change the input
B = other * self.B
D = other * self.D
return StateSpace(self.A, B, self.C, D, self.dt)
elif isinstance(other, np.ndarray):
other = np.atleast_2d(other)
# Special case for SISO transfer function
if self.issiso():
self = bdalg.append(*([self] * other.shape[1]))
# Dimension check after broadcasting
if self.noutputs != other.shape[1]:
raise ValueError("array has incompatible shape")
C = other @ self.C
D = other @ self.D
return StateSpace(self.A, self.B, C, D, self.dt)
if not isinstance(other, StateSpace):
return NotImplemented
# Promote SISO object to compatible dimension
if self.issiso() and not other.issiso():
self = bdalg.append(*([self] * other.ninputs))
elif not self.issiso() and other.issiso():
other = bdalg.append(*([other] * self.noutputs))
return other * self
# TODO: general __truediv__ requires descriptor system support
def __truediv__(self, other):
"""Division of state space systems by TFs, FRDs, scalars, and arrays"""
# Let ``other.__rtruediv__`` handle it
try:
return self * (1 / other)
except ValueError:
return NotImplemented
def __rtruediv__(self, other):
"""Division by state space system"""
return other * self**-1
def __pow__(self, other):
"""Power of a state space system"""
if not type(other) == int:
raise ValueError("Exponent must be an integer")
if self.ninputs != self.noutputs:
# System must have same number of inputs and outputs
return NotImplemented
if other < -1:
return (self**-1)**(-other)
elif other == -1:
try:
Di = scipy.linalg.inv(self.D)
except scipy.linalg.LinAlgError:
# D matrix must be nonsingular
return NotImplemented
Ai = self.A - self.B @ Di @ self.C
Bi = self.B @ Di
Ci = -Di @ self.C
return StateSpace(Ai, Bi, Ci, Di, self.dt)
elif other == 0:
return StateSpace([], [], [], np.eye(self.ninputs), self.dt)
elif other == 1:
return self
elif other > 1:
return self * (self**(other - 1))
def __call__(self, x, squeeze=None, warn_infinite=True):
"""Evaluate system transfer function at point in complex plane.
Returns the value of the system's transfer function at a point `x`
in the complex plane, where `x` is `s` for continuous-time systems
and `z` for discrete-time systems.
See `LTI.__call__` for details.
Examples
--------
>>> G = ct.ss([[-1, -2], [3, -4]], [[5], [7]], [[6, 8]], [[9]])
>>> fresp = G(1j) # evaluate at s = 1j
"""
# Use Slycot if available
out = self.horner(x, warn_infinite=warn_infinite)
return _process_frequency_response(self, x, out, squeeze=squeeze)
def slycot_laub(self, x):
"""Laub's method to evaluate response at complex frequency.
Evaluate transfer function at complex frequency using Laub's
method from Slycot. Expects inputs and outputs to be
formatted correctly. Use ``sys(x)`` for a more user-friendly
interface.
Parameters
----------
x : complex array_like or complex
Complex frequency.
Returns
-------
output : (number_outputs, number_inputs, len(x)) complex ndarray
Frequency response.
"""
from slycot import tb05ad
# Make sure the argument is a 1D array of complex numbers
x_arr = np.atleast_1d(x).astype(complex, copy=False)
# Make sure that we are operating on a simple list
if len(x_arr.shape) > 1:
raise ValueError("input list must be 1D")
# preallocate
n = self.nstates
m = self.ninputs
p = self.noutputs
out = np.empty((p, m, len(x_arr)), dtype=complex)
# The first call both evaluates C(sI-A)^-1 B and also returns
# Hessenberg transformed matrices at, bt, ct.
result = tb05ad(n, m, p, x_arr[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.
out[:, :, 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, x_kk in enumerate(x_arr[1:]):
result = tb05ad(n, m, p, x_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.
out[:, :, kk+1] = result[0] + self.D
return out
def horner(self, x, warn_infinite=True):
"""Evaluate value of transfer function using Horner's method.
Evaluates ``sys(x)`` where `x` is a complex number `s` for
continuous-time systems and `z` for discrete-time systems. Expects
inputs and outputs to be formatted correctly. Use ``sys(x)`` for a
more user-friendly interface.
Parameters
----------
x : complex
Complex frequency at which the transfer function is evaluated.
warn_infinite : bool, optional
If True (default), generate a warning if `x` is a pole.
Returns
-------
complex
Notes
-----
Attempts to use Laub's method from Slycot library, with a fall-back
to Python code.
"""
# Make sure the argument is a 1D array of complex numbers
x_arr = np.atleast_1d(x).astype(complex, copy=False)
# return fast on systems with 0 or 1 state
if self.nstates == 0:
return self.D[:, :, np.newaxis] \
* np.ones_like(x_arr, dtype=complex)
elif self.nstates == 1:
with np.errstate(divide='ignore', invalid='ignore'):
out = self.C[:, :, np.newaxis] \
/ (x_arr - self.A[0, 0]) \
* self.B[:, :, np.newaxis] \
+ self.D[:, :, np.newaxis]
out[np.isnan(out)] = complex(np.inf, np.nan)
return out
try:
out = self.slycot_laub(x_arr)
except (ImportError, Exception):
# Fall back because either Slycot unavailable or cannot handle
# certain cases.
# Make sure that we are operating on a simple list
if len(x_arr.shape) > 1:
raise ValueError("input list must be 1D")
# Preallocate
out = empty((self.noutputs, self.ninputs, len(x_arr)),
dtype=complex)
# TODO: can this be vectorized?
for idx, x_idx in enumerate(x_arr):
try:
xr = solve(x_idx * eye(self.nstates) - self.A, self.B)
out[:, :, idx] = self.C @ xr + self.D
except LinAlgError:
# Issue a warning message, for consistency with xferfcn
if warn_infinite:
warn("singular matrix in frequency response",
RuntimeWarning)
# Evaluating at a pole. Return value depends if there
# is a zero at the same point or not.
if x_idx in self.zeros():
out[:, :, idx] = complex(np.nan, np.nan)
else:
out[:, :, idx] = complex(np.inf, np.nan)
return out
def freqresp(self, omega):
"""(deprecated) Evaluate transfer function at complex frequencies.
.. deprecated::0.9.0
Method has been given the more Pythonic name
`StateSpace.frequency_response`. Or use
`freqresp` in the MATLAB compatibility module.
"""
warn("StateSpace.freqresp(omega) will be removed in a "
"future release of python-control; use "
"sys.frequency_response(omega), or freqresp(sys, omega) in the "
"MATLAB compatibility module instead", FutureWarning)
return self.frequency_response(omega)
# Compute poles and zeros
def poles(self):
"""Compute the poles of a state space system."""
return eigvals(self.A).astype(complex) if self.nstates \
else np.array([])
def zeros(self):
"""Compute the zeros of a state space system."""
if not self.nstates:
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:
# Use SciPy generalized eigenvalue function
return sp.linalg.eigvals(out[8][0:nu, 0:nu],
out[9][0:nu, 0:nu]).astype(complex)
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)], dtype=complex)
# Feedback around a state space system
def feedback(self, other=1, sign=-1):
"""Feedback interconnection between two LTI objects.
Parameters
----------
other : `InputOutputSystem`
System in the feedback path.
sign : float, optional