-
Notifications
You must be signed in to change notification settings - Fork 458
Expand file tree
/
Copy pathstatesp_test.py
More file actions
1660 lines (1456 loc) · 65.7 KB
/
Copy pathstatesp_test.py
File metadata and controls
1660 lines (1456 loc) · 65.7 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
"""Tests for the StateSpace class.
RMM, 30 Mar 2011 based on TestStateSp from v0.4a)
RMM, 14 Jun 2019 statesp_array_test.py coverted from statesp_test.py to test
with use_numpy_matrix(False)
BG, 26 Jul 2020 merge statesp_array_test.py differences into statesp_test.py
convert to pytest
"""
import operator
import numpy as np
import pytest
from numpy.linalg import solve
from numpy.testing import assert_array_almost_equal
from scipy.linalg import block_diag, eigvals
import control as ct
from control.config import defaults
from control.dtime import sample_system
from control.lti import LTI, evalfr
from control.statesp import StateSpace, _convert_to_statespace, \
_rss_generate, _statesp_defaults, drss, linfnorm, rss, ss, tf2ss
from control.xferfcn import TransferFunction, ss2tf
from .conftest import assert_tf_close_coeff
class TestStateSpace:
"""Tests for the StateSpace class."""
@pytest.fixture
def sys322ABCD(self):
"""Matrices for sys322"""
A322 = [[-3., 4., 2.],
[-1., -3., 0.],
[2., 5., 3.]]
B322 = [[1., 4.],
[-3., -3.],
[-2., 1.]]
C322 = [[4., 2., -3.],
[1., 4., 3.]]
D322 = [[-2., 4.],
[0., 1.]]
return (A322, B322, C322, D322)
@pytest.fixture
def sys322(self, sys322ABCD):
"""3-states square system (2 inputs x 2 outputs)"""
return StateSpace(*sys322ABCD, name='sys322')
@pytest.fixture
def sys121(self):
"""2 state, 1 input, 1 output (siso) system"""
A121 = [[4., 1.],
[2., -3]]
B121 = [[5.],
[-3.]]
C121 = [[2., -4]]
D121 = [[3.]]
return StateSpace(A121, B121, C121, D121)
@pytest.fixture
def sys222(self):
"""2-states square system (2 inputs x 2 outputs)"""
A222 = [[4., 1.],
[2., -3]]
B222 = [[5., 2.],
[-3., -3.]]
C222 = [[2., -4],
[0., 1.]]
D222 = [[3., 2.],
[1., -1.]]
return StateSpace(A222, B222, C222, D222)
@pytest.fixture
def sys623(self):
"""sys3: 6 states non square system (2 inputs x 3 outputs)"""
A623 = np.array([[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 3, 0, 0, 0],
[0, 0, 0, -4, 0, 0],
[0, 0, 0, 0, -1, 0],
[0, 0, 0, 0, 0, 3]])
B623 = np.array([[0, -1],
[-1, 0],
[1, -1],
[0, 0],
[0, 1],
[-1, -1]])
C623 = np.array([[1, 0, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1]])
D623 = np.zeros((3, 2))
return StateSpace(A623, B623, C623, D623)
@pytest.mark.parametrize(
"dt",
[(), (None, ), (0, ), (1, ), (0.1, ), (True, )],
ids=lambda i: "dt " + ("unspec" if len(i) == 0 else str(i[0])))
@pytest.mark.parametrize(
"argfun",
[pytest.param(
lambda ABCDdt: (ABCDdt, {}),
id="A, B, C, D[, dt]"),
pytest.param(
lambda ABCDdt: (ABCDdt[:4], {'dt': dt_ for dt_ in ABCDdt[4:]}),
id="A, B, C, D[, dt=dt]"),
pytest.param(
lambda ABCDdt: ((StateSpace(*ABCDdt), ), {}),
id="sys")
])
def test_constructor(self, sys322ABCD, dt, argfun):
"""Test different ways to call the StateSpace() constructor"""
args, kwargs = argfun(sys322ABCD + dt)
sys = StateSpace(*args, **kwargs)
dtref = defaults['control.default_dt'] if len(dt) == 0 else dt[0]
np.testing.assert_almost_equal(sys.A, sys322ABCD[0])
np.testing.assert_almost_equal(sys.B, sys322ABCD[1])
np.testing.assert_almost_equal(sys.C, sys322ABCD[2])
np.testing.assert_almost_equal(sys.D, sys322ABCD[3])
assert sys.dt == dtref
@pytest.mark.parametrize(
"args, exc, errmsg",
[((True, ), TypeError, "(can only take in|sys must be) a StateSpace"),
((1, 2), TypeError, "1, 4, or 5 arguments"),
((np.ones((3, 2)), np.ones((3, 2)),
np.ones((2, 2)), np.ones((2, 2))), ValueError,
r"A must be a square matrix"),
((np.ones((3, 3)), np.ones((2, 2)),
np.ones((2, 3)), np.ones((2, 2))), ValueError,
r"Incompatible dimensions of B matrix; expected \(3, 2\)"),
((np.ones((3, 3)), np.ones((3, 2)),
np.ones((2, 2)), np.ones((2, 2))), ValueError,
r"Incompatible dimensions of C matrix; expected \(2, 3\)"),
((np.ones((3, 3)), np.ones((3, 2)),
np.ones((2, 3)), np.ones((2, 3))), ValueError,
r"Incompatible dimensions of D matrix; expected \(2, 2\)"),
(([1j], 2, 3, 0), TypeError, "real number, not 'complex'"),
])
def test_constructor_invalid(self, args, exc, errmsg):
"""Test invalid input to StateSpace() constructor"""
with pytest.raises(exc, match=errmsg):
StateSpace(*args)
with pytest.raises(exc, match=errmsg):
ss(*args)
def test_constructor_warns(self, sys322ABCD):
"""Test ambiguos input to StateSpace() constructor"""
with pytest.warns(UserWarning, match="received multiple dt"):
sys = StateSpace(*(sys322ABCD + (0.1, )), dt=0.2)
np.testing.assert_almost_equal(sys.A, sys322ABCD[0])
np.testing.assert_almost_equal(sys.B, sys322ABCD[1])
np.testing.assert_almost_equal(sys.C, sys322ABCD[2])
np.testing.assert_almost_equal(sys.D, sys322ABCD[3])
assert sys.dt == 0.1
def test_copy_constructor(self):
"""Test the copy constructor"""
# Create a set of matrices for a simple linear system
A = np.array([[-1]])
B = np.array([[1]])
C = np.array([[1]])
D = np.array([[0]])
# Create the first linear system and a copy
linsys = StateSpace(A, B, C, D)
cpysys = StateSpace(linsys)
# Change the original A matrix
A[0, 0] = -2
np.testing.assert_allclose(linsys.A, [[-1]]) # original value
np.testing.assert_allclose(cpysys.A, [[-1]]) # original value
# Change the A matrix for the original system
linsys.A[0, 0] = -3
np.testing.assert_allclose(cpysys.A, [[-1]]) # original value
@pytest.mark.skip("obsolete test")
def test_copy_constructor_nodt(self, sys322):
"""Test the copy constructor when an object without dt is passed"""
sysin = sample_system(sys322, 1.)
del sysin.dt # this is a nonsensical thing to do
sys = StateSpace(sysin)
assert sys.dt == defaults['control.default_dt']
# test for static gain
sysin = StateSpace([], [], [], [[1, 2], [3, 4]], 1.)
del sysin.dt # this is a nonsensical thing to do
sys = StateSpace(sysin)
assert sys.dt is None
def test_D_broadcast(self, sys623):
"""Test broadcast of D=0 to the right shape"""
# Giving D as a scalar 0 should broadcast to the right shape
sys = StateSpace(sys623.A, sys623.B, sys623.C, 0)
np.testing.assert_allclose(sys623.D, sys.D)
# Giving D as a matrix of the wrong size should generate an error
with pytest.raises(ValueError):
sys = StateSpace(sys.A, sys.B, sys.C, np.array([[0]]))
# Make sure that empty systems still work
sys = StateSpace([], [], [], 1)
np.testing.assert_allclose(sys.D, [[1]])
sys = StateSpace([], [], [], [[0]])
np.testing.assert_allclose(sys.D, [[0]])
sys = StateSpace([], [], [], [0])
np.testing.assert_allclose(sys.D, [[0]])
sys = StateSpace([], [], [], 0)
np.testing.assert_allclose(sys.D, [[0]])
def test_pole(self, sys322):
"""Evaluate the poles of a MIMO system."""
p = np.sort(sys322.poles())
true_p = np.sort([3.34747678408874,
-3.17373839204437 + 1.47492908003839j,
-3.17373839204437 - 1.47492908003839j])
np.testing.assert_array_almost_equal(p, true_p)
def test_zero_empty(self):
"""Test to make sure zero() works with no zeros in system."""
sys = _convert_to_statespace(TransferFunction([1], [1, 2, 1]))
np.testing.assert_array_equal(sys.zeros(), np.array([]))
@pytest.mark.slycot
def test_zero_siso(self, sys222):
"""Evaluate the zeros of a SISO system."""
# extract only first input / first output system of sys222. This system is denoted sys111
# or tf111
tf111 = ss2tf(sys222)
sys111 = tf2ss(tf111[0, 0])
# compute zeros as root of the characteristic polynomial at the numerator of tf111
# this method is simple and assumed as valid in this test
true_z = np.sort(tf111[0, 0].zeros())
# Compute the zeros through ab08nd, which is tested here
z = np.sort(sys111.zeros())
np.testing.assert_almost_equal(true_z, z)
def test_zero_mimo_sys322_square(self, sys322):
"""Evaluate the zeros of a square MIMO system."""
z = np.sort(sys322.zeros())
true_z = np.sort([44.41465, -0.490252, -5.924398])
np.testing.assert_array_almost_equal(z, true_z)
def test_zero_mimo_sys222_square(self, sys222):
"""Evaluate the zeros of a square MIMO system."""
z = np.sort(sys222.zeros())
true_z = np.sort([-10.568501, 3.368501])
np.testing.assert_array_almost_equal(z, true_z)
@pytest.mark.slycot
def test_zero_mimo_sys623_non_square(self, sys623):
"""Evaluate the zeros of a non square MIMO system."""
z = np.sort(sys623.zeros())
true_z = np.sort([2., -1.])
np.testing.assert_array_almost_equal(z, true_z)
def test_add_ss(self, sys222, sys322):
"""Add two MIMO systems."""
A = [[-3., 4., 2., 0., 0.], [-1., -3., 0., 0., 0.],
[2., 5., 3., 0., 0.], [0., 0., 0., 4., 1.], [0., 0., 0., 2., -3.]]
B = [[1., 4.], [-3., -3.], [-2., 1.], [5., 2.], [-3., -3.]]
C = [[4., 2., -3., 2., -4.], [1., 4., 3., 0., 1.]]
D = [[1., 6.], [1., 0.]]
sys = sys322 + sys222
np.testing.assert_array_almost_equal(sys.A, A)
np.testing.assert_array_almost_equal(sys.B, B)
np.testing.assert_array_almost_equal(sys.C, C)
np.testing.assert_array_almost_equal(sys.D, D)
def test_subtract_ss(self, sys222, sys322):
"""Subtract two MIMO systems."""
A = [[-3., 4., 2., 0., 0.], [-1., -3., 0., 0., 0.],
[2., 5., 3., 0., 0.], [0., 0., 0., 4., 1.], [0., 0., 0., 2., -3.]]
B = [[1., 4.], [-3., -3.], [-2., 1.], [5., 2.], [-3., -3.]]
C = [[4., 2., -3., -2., 4.], [1., 4., 3., 0., -1.]]
D = [[-5., 2.], [-1., 2.]]
sys = sys322 - sys222
np.testing.assert_array_almost_equal(sys.A, A)
np.testing.assert_array_almost_equal(sys.B, B)
np.testing.assert_array_almost_equal(sys.C, C)
np.testing.assert_array_almost_equal(sys.D, D)
def test_multiply_ss(self, sys222, sys322):
"""Multiply two MIMO systems."""
A = [[4., 1., 0., 0., 0.], [2., -3., 0., 0., 0.], [2., 0., -3., 4., 2.],
[-6., 9., -1., -3., 0.], [-4., 9., 2., 5., 3.]]
B = [[5., 2.], [-3., -3.], [7., -2.], [-12., -3.], [-5., -5.]]
C = [[-4., 12., 4., 2., -3.], [0., 1., 1., 4., 3.]]
D = [[-2., -8.], [1., -1.]]
sys = sys322 * sys222
np.testing.assert_array_almost_equal(sys.A, A)
np.testing.assert_array_almost_equal(sys.B, B)
np.testing.assert_array_almost_equal(sys.C, C)
np.testing.assert_array_almost_equal(sys.D, D)
def test_add_sub_mimo_siso(self):
# Test SS with SS
ss_siso = StateSpace(
np.array([
[1, 2],
[3, 4],
]),
np.array([
[1],
[4],
]),
np.array([
[1, 1],
]),
np.array([
[0],
]),
)
ss_siso_1 = StateSpace(
np.array([
[1, 1],
[3, 1],
]),
np.array([
[3],
[-4],
]),
np.array([
[-1, 1],
]),
np.array([
[0.1],
]),
)
ss_siso_2 = StateSpace(
np.array([
[1, 0],
[0, 1],
]),
np.array([
[0],
[2],
]),
np.array([
[0, 1],
]),
np.array([
[0],
]),
)
ss_mimo = ss_siso_1.append(ss_siso_2)
expected_add = ct.combine_tf([
[ss2tf(ss_siso_1 + ss_siso), ss2tf(ss_siso)],
[ss2tf(ss_siso), ss2tf(ss_siso_2 + ss_siso)],
])
expected_sub = ct.combine_tf([
[ss2tf(ss_siso_1 - ss_siso), -ss2tf(ss_siso)],
[-ss2tf(ss_siso), ss2tf(ss_siso_2 - ss_siso)],
])
for op, expected in [
(StateSpace.__add__, expected_add),
(StateSpace.__radd__, expected_add),
(StateSpace.__sub__, expected_sub),
(StateSpace.__rsub__, -expected_sub),
]:
result = op(ss_mimo, ss_siso)
assert_tf_close_coeff(
expected.minreal(),
ss2tf(result).minreal(),
)
# Test SS with array
expected_add = ct.combine_tf([
[ss2tf(1 + ss_siso), ss2tf(ss_siso)],
[ss2tf(ss_siso), ss2tf(1 + ss_siso)],
])
expected_sub = ct.combine_tf([
[ss2tf(-1 + ss_siso), ss2tf(ss_siso)],
[ss2tf(ss_siso), ss2tf(-1 + ss_siso)],
])
for op, expected in [
(StateSpace.__add__, expected_add),
(StateSpace.__radd__, expected_add),
(StateSpace.__sub__, expected_sub),
(StateSpace.__rsub__, -expected_sub),
]:
result = op(ss_siso, np.eye(2))
assert_tf_close_coeff(
expected.minreal(),
ss2tf(result).minreal(),
)
@pytest.mark.slycot
@pytest.mark.parametrize(
"left, right, expected",
[
(
TransferFunction([2], [1, 0]),
TransferFunction(
[
[[2], [1]],
[[-1], [4]],
],
[
[[10, 1], [20, 1]],
[[20, 1], [30, 1]],
],
),
TransferFunction(
[
[[4], [2]],
[[-2], [8]],
],
[
[[10, 1, 0], [20, 1, 0]],
[[20, 1, 0], [30, 1, 0]],
],
),
),
(
TransferFunction(
[
[[2], [1]],
[[-1], [4]],
],
[
[[10, 1], [20, 1]],
[[20, 1], [30, 1]],
],
),
TransferFunction([2], [1, 0]),
TransferFunction(
[
[[4], [2]],
[[-2], [8]],
],
[
[[10, 1, 0], [20, 1, 0]],
[[20, 1, 0], [30, 1, 0]],
],
),
),
(
TransferFunction([2], [1, 0]),
np.eye(3),
TransferFunction(
[
[[2], [0], [0]],
[[0], [2], [0]],
[[0], [0], [2]],
],
[
[[1, 0], [1], [1]],
[[1], [1, 0], [1]],
[[1], [1], [1, 0]],
],
),
),
]
)
def test_mul_mimo_siso(self, left, right, expected):
result = tf2ss(left).__mul__(right)
assert_tf_close_coeff(
expected.minreal(),
ss2tf(result).minreal(),
)
@pytest.mark.slycot
@pytest.mark.parametrize(
"left, right, expected",
[
(
TransferFunction([2], [1, 0]),
TransferFunction(
[
[[2], [1]],
[[-1], [4]],
],
[
[[10, 1], [20, 1]],
[[20, 1], [30, 1]],
],
),
TransferFunction(
[
[[4], [2]],
[[-2], [8]],
],
[
[[10, 1, 0], [20, 1, 0]],
[[20, 1, 0], [30, 1, 0]],
],
),
),
(
TransferFunction(
[
[[2], [1]],
[[-1], [4]],
],
[
[[10, 1], [20, 1]],
[[20, 1], [30, 1]],
],
),
TransferFunction([2], [1, 0]),
TransferFunction(
[
[[4], [2]],
[[-2], [8]],
],
[
[[10, 1, 0], [20, 1, 0]],
[[20, 1, 0], [30, 1, 0]],
],
),
),
(
np.eye(3),
TransferFunction([2], [1, 0]),
TransferFunction(
[
[[2], [0], [0]],
[[0], [2], [0]],
[[0], [0], [2]],
],
[
[[1, 0], [1], [1]],
[[1], [1, 0], [1]],
[[1], [1], [1, 0]],
],
),
),
]
)
def test_rmul_mimo_siso(self, left, right, expected):
result = tf2ss(right).__rmul__(left)
assert_tf_close_coeff(
expected.minreal(),
ss2tf(result).minreal(),
)
@pytest.mark.slycot
@pytest.mark.parametrize("power", [0, 1, 3, -3])
@pytest.mark.parametrize("sysname", ["sys222", "sys322"])
def test_pow(self, request, sysname, power):
"""Test state space powers."""
sys = request.getfixturevalue(sysname)
result = sys**power
if power == 0:
expected = StateSpace([], [], [], np.eye(sys.ninputs), dt=0)
else:
sign = 1 if power > 0 else -1
expected = sys**sign
for i in range(1,abs(power)):
expected *= sys**sign
np.testing.assert_allclose(expected.A, result.A)
np.testing.assert_allclose(expected.B, result.B)
np.testing.assert_allclose(expected.C, result.C)
np.testing.assert_allclose(expected.D, result.D)
@pytest.mark.slycot
@pytest.mark.parametrize("order", ["left", "right"])
@pytest.mark.parametrize("sysname", ["sys121", "sys222", "sys322"])
def test_pow_inv(self, request, sysname, order):
"""Check for identity when multiplying by inverse.
This holds approximately true for a few steps but is very
unstable due to numerical precision. Don't assume this in
real life. For testing purposes only!
"""
sys = request.getfixturevalue(sysname)
if order == "left":
combined = sys**-1 * sys
else:
combined = sys * sys**-1
combined = combined.minreal()
np.testing.assert_allclose(combined.dcgain(), np.eye(sys.ninputs),
atol=1e-7)
T = np.linspace(0., 0.3, 100)
U = np.random.rand(sys.ninputs, len(T))
R = combined.forced_response(T=T, U=U, squeeze=False)
# Check that the output is the same as the input
np.testing.assert_allclose(R.outputs, U)
@pytest.mark.slycot
def test_truediv(self, sys222, sys322):
"""Test state space truediv"""
for sys in [sys222, sys322]:
# Divide by self
result = (sys.__truediv__(sys)).minreal()
expected = StateSpace([], [], [], np.eye(2), dt=0)
assert_tf_close_coeff(
ss2tf(expected).minreal(),
ss2tf(result).minreal(),
)
# Divide by TF
result = sys.__truediv__(TransferFunction.s)
expected = ss2tf(sys) / TransferFunction.s
assert_tf_close_coeff(
expected.minreal(),
ss2tf(result).minreal(),
)
@pytest.mark.slycot
def test_rtruediv(self, sys222, sys322):
"""Test state space rtruediv"""
for sys in [sys222, sys322]:
result = (sys.__rtruediv__(sys)).minreal()
expected = StateSpace([], [], [], np.eye(2), dt=0)
assert_tf_close_coeff(
ss2tf(expected).minreal(),
ss2tf(result).minreal(),
)
# Divide TF by SS
result = sys.__rtruediv__(TransferFunction.s)
expected = TransferFunction.s / sys
assert_tf_close_coeff(
expected.minreal(),
result.minreal(),
)
# Divide array by SS
sys = tf2ss(TransferFunction([1, 2], [2, 1]))
result = sys.__rtruediv__(np.eye(2))
expected = TransferFunction([2, 1], [1, 2]) * np.eye(2)
assert_tf_close_coeff(
expected.minreal(),
ss2tf(result).minreal(),
)
@pytest.mark.parametrize("k", [2, -3.141, np.float32(2.718), np.array([[4.321], [5.678]])])
def test_truediv_ss_scalar(self, sys322, k):
"""Divide SS by scalar."""
sys = sys322 / k
syscheck = sys322 * (1/k)
np.testing.assert_array_almost_equal(sys.A, syscheck.A)
np.testing.assert_array_almost_equal(sys.B, syscheck.B)
np.testing.assert_array_almost_equal(sys.C, syscheck.C)
np.testing.assert_array_almost_equal(sys.D, syscheck.D)
@pytest.mark.parametrize("omega, resp",
[(1.,
np.array([[ 4.37636761e-05-0.01522976j,
-7.92603939e-01+0.02617068j],
[-3.31544858e-01+0.0576105j,
1.28919037e-01-0.14382495j]])),
(32,
np.array([[-1.16548243e-05-3.13444825e-04j,
-7.99936828e-01+4.54201816e-06j],
[-3.00137118e-01+3.42881660e-03j,
6.32015038e-04-1.21462255e-02j]]))])
@pytest.mark.parametrize("dt", [None, 0, 1e-3])
def test_call(self, dt, omega, resp):
"""Evaluate the frequency response at single frequencies"""
A = [[-2, 0.5], [0.5, -0.3]]
B = [[0.3, -1.3], [0.1, 0.]]
C = [[0., 0.1], [-0.3, -0.2]]
D = [[0., -0.8], [-0.3, 0.]]
sys = StateSpace(A, B, C, D)
if dt:
sys = sample_system(sys, dt)
s = np.exp(omega * 1j * dt)
else:
s = omega * 1j
# Correct versions of the call
np.testing.assert_allclose(evalfr(sys, s), resp, atol=1e-3)
np.testing.assert_allclose(sys(s), resp, atol=1e-3)
# Deprecated name of the call (should generate error)
with pytest.raises(AttributeError):
sys.evalfr(omega)
def test_freq_resp(self):
"""Evaluate the frequency response at multiple frequencies."""
A = [[-2, 0.5], [0.5, -0.3]]
B = [[0.3, -1.3], [0.1, 0.]]
C = [[0., 0.1], [-0.3, -0.2]]
D = [[0., -0.8], [-0.3, 0.]]
sys = StateSpace(A, B, C, D)
true_mag = [[[0.0852992637230322, 0.00103596611395218],
[0.935374692849736, 0.799380720864549]],
[[0.55656854563842, 0.301542699860857],
[0.609178071542849, 0.0382108097985257]]]
true_phase = [[[-0.566195599644593, -1.68063565332582],
[3.0465958317514, 3.14141384339534]],
[[2.90457947657161, 3.10601268291914],
[-0.438157380501337, -1.40720969147217]]]
true_omega = [0.1, 10.]
mag, phase, omega = sys.frequency_response(true_omega)
np.testing.assert_almost_equal(mag, true_mag)
np.testing.assert_almost_equal(phase, true_phase)
np.testing.assert_almost_equal(omega, true_omega)
# Deprecated version of the call (should return warning)
with pytest.warns(FutureWarning, match="will be removed"):
mag, phase, omega = sys.freqresp(true_omega)
np.testing.assert_almost_equal(mag, true_mag)
@pytest.mark.slycot
def test_minreal(self):
"""Test a minreal model reduction."""
# A = [-2, 0.5, 0; 0.5, -0.3, 0; 0, 0, -0.1]
A = [[-2, 0.5, 0], [0.5, -0.3, 0], [0, 0, -0.1]]
# B = [0.3, -1.3; 0.1, 0; 1, 0]
B = [[0.3, -1.3], [0.1, 0.], [1.0, 0.0]]
# C = [0, 0.1, 0; -0.3, -0.2, 0]
C = [[0., 0.1, 0.0], [-0.3, -0.2, 0.0]]
# D = [0 -0.8; -0.3 0]
D = [[0., -0.8], [-0.3, 0.]]
# sys = ss(A, B, C, D)
sys = StateSpace(A, B, C, D)
sysr = sys.minreal()
assert sysr.nstates == 2
assert sysr.ninputs == sys.ninputs
assert sysr.noutputs == sys.noutputs
np.testing.assert_array_almost_equal(
eigvals(sysr.A), [-2.136154, -0.1638459])
def test_append_ss(self):
"""Test appending two state-space systems."""
A1 = [[-2, 0.5, 0], [0.5, -0.3, 0], [0, 0, -0.1]]
B1 = [[0.3, -1.3], [0.1, 0.], [1.0, 0.0]]
C1 = [[0., 0.1, 0.0], [-0.3, -0.2, 0.0]]
D1 = [[0., -0.8], [-0.3, 0.]]
A2 = [[-1.]]
B2 = [[1.2]]
C2 = [[0.5]]
D2 = [[0.4]]
A3 = [[-2, 0.5, 0, 0], [0.5, -0.3, 0, 0], [0, 0, -0.1, 0],
[0, 0, 0., -1.]]
B3 = [[0.3, -1.3, 0], [0.1, 0., 0], [1.0, 0.0, 0], [0., 0, 1.2]]
C3 = [[0., 0.1, 0.0, 0.0], [-0.3, -0.2, 0.0, 0.0], [0., 0., 0., 0.5]]
D3 = [[0., -0.8, 0.], [-0.3, 0., 0.], [0., 0., 0.4]]
sys1 = StateSpace(A1, B1, C1, D1)
sys2 = StateSpace(A2, B2, C2, D2)
sys3 = StateSpace(A3, B3, C3, D3)
sys3c = sys1.append(sys2)
np.testing.assert_array_almost_equal(sys3.A, sys3c.A)
np.testing.assert_array_almost_equal(sys3.B, sys3c.B)
np.testing.assert_array_almost_equal(sys3.C, sys3c.C)
np.testing.assert_array_almost_equal(sys3.D, sys3c.D)
def test_append_tf(self):
"""Test appending a state-space system with a tf"""
A1 = [[-2, 0.5, 0], [0.5, -0.3, 0], [0, 0, -0.1]]
B1 = [[0.3, -1.3], [0.1, 0.], [1.0, 0.0]]
C1 = [[0., 0.1, 0.0], [-0.3, -0.2, 0.0]]
D1 = [[0., -0.8], [-0.3, 0.]]
s = TransferFunction([1, 0], [1])
h = 1 / (s + 1) / (s + 2)
sys1 = StateSpace(A1, B1, C1, D1)
sys2 = _convert_to_statespace(h)
sys3c = sys1.append(sys2)
np.testing.assert_array_almost_equal(sys1.A, sys3c.A[:3, :3])
np.testing.assert_array_almost_equal(sys1.B, sys3c.B[:3, :2])
np.testing.assert_array_almost_equal(sys1.C, sys3c.C[:2, :3])
np.testing.assert_array_almost_equal(sys1.D, sys3c.D[:2, :2])
np.testing.assert_array_almost_equal(sys2.A, sys3c.A[3:, 3:])
np.testing.assert_array_almost_equal(sys2.B, sys3c.B[3:, 2:])
np.testing.assert_array_almost_equal(sys2.C, sys3c.C[2:, 3:])
np.testing.assert_array_almost_equal(sys2.D, sys3c.D[2:, 2:])
np.testing.assert_array_almost_equal(sys3c.A[:3, 3:], np.zeros((3, 2)))
np.testing.assert_array_almost_equal(sys3c.A[3:, :3], np.zeros((2, 3)))
def test_array_access_ss_failure(self):
sys1 = StateSpace(
[[1., 2.], [3., 4.]],
[[5., 6.], [6., 8.]],
[[9., 10.], [11., 12.]],
[[13., 14.], [15., 16.]], 1,
inputs=['u0', 'u1'], outputs=['y0', 'y1'])
with pytest.raises(IOError):
sys1[0]
@pytest.mark.parametrize(
"outdx, inpdx",
[(0, 1),
(slice(0, 1, 1), 1),
(0, slice(1, 2, 1)),
(slice(0, 1, 1), slice(1, 2, 1)),
(slice(None, None, -1), 1),
(0, slice(None, None, -1)),
(slice(None, 2, None), 1),
(slice(None, None, 1), slice(None, None, 2)),
(0, slice(1, 2, 1)),
(slice(0, 1, 1), slice(1, 2, 1)),
# ([0, 1], [0]), # lists of indices
])
@pytest.mark.parametrize("named", [False, True])
def test_array_access_ss(self, outdx, inpdx, named):
sys1 = StateSpace(
[[1., 2.], [3., 4.]],
[[5., 6.], [7., 8.]],
[[9., 10.], [11., 12.]],
[[13., 14.], [15., 16.]], 1,
inputs=['u0', 'u1'], outputs=['y0', 'y1'])
if named:
# Use names instead of numbers (and re-convert in statesp)
outnames = sys1.output_labels[outdx]
inpnames = sys1.input_labels[inpdx]
sys1_01 = sys1[outnames, inpnames]
else:
sys1_01 = sys1[outdx, inpdx]
# Convert int to slice to ensure that numpy doesn't drop the dimension
if isinstance(outdx, int): outdx = slice(outdx, outdx+1, 1)
if isinstance(inpdx, int): inpdx = slice(inpdx, inpdx+1, 1)
np.testing.assert_array_almost_equal(sys1_01.A, sys1.A)
np.testing.assert_array_almost_equal(sys1_01.B, sys1.B[:, inpdx])
np.testing.assert_array_almost_equal(sys1_01.C, sys1.C[outdx, :])
np.testing.assert_array_almost_equal(sys1_01.D, sys1.D[outdx, inpdx])
assert sys1.dt == sys1_01.dt
assert sys1_01.input_labels == sys1.input_labels[inpdx]
assert sys1_01.output_labels == sys1.output_labels[outdx]
assert sys1_01.name == sys1.name + "$indexed"
def test_dc_gain_cont(self):
"""Test DC gain for continuous-time state-space systems."""
sys = StateSpace(-2., 6., 5., 0)
np.testing.assert_allclose(sys.dcgain(), 15.)
sys2 = StateSpace(-2, [6., 4.], [[5.], [7.], [11]], np.zeros((3, 2)))
expected = np.array([[15., 10.], [21., 14.], [33., 22.]])
np.testing.assert_allclose(sys2.dcgain(), expected)
sys3 = StateSpace(0., 1., 1., 0.)
np.testing.assert_equal(sys3.dcgain(), np.inf)
def test_dc_gain_discr(self):
"""Test DC gain for discrete-time state-space systems."""
# static gain
sys = StateSpace([], [], [], 2, True)
np.testing.assert_allclose(sys.dcgain(), 2)
# averaging filter
sys = StateSpace(0.5, 0.5, 1, 0, True)
np.testing.assert_allclose(sys.dcgain(), 1)
# differencer
sys = StateSpace(0, 1, -1, 1, True)
np.testing.assert_allclose(sys.dcgain(), 0)
# summer
sys = StateSpace(1, 1, 1, 0, True)
np.testing.assert_equal(sys.dcgain(), np.inf)
@pytest.mark.parametrize("outputs", range(1, 6))
@pytest.mark.parametrize("inputs", range(1, 6))
@pytest.mark.parametrize("dt", [None, 0, 1, True],
ids=["dtNone", "c", "dt1", "dtTrue"])
def test_dc_gain_integrator(self, outputs, inputs, dt):
"""DC gain w/ pole at origin returns appropriately sized array of inf.
the SISO case is also tested in test_dc_gain_{cont,discr}
time systems (dt=0)
"""
states = max(inputs, outputs)
# a matrix that is singular at DC, and has no "useless" states as in
# _remove_useless_states
a = np.triu(np.tile(2, (states, states)))
# eigenvalues all +2, except for ...
a[0, 0] = 0 if dt in [0, None] else 1
b = np.eye(max(inputs, states))[:states, :inputs]
c = np.eye(max(outputs, states))[:outputs, :states]
d = np.zeros((outputs, inputs))
sys = StateSpace(a, b, c, d, dt)
dc = np.full_like(d, np.inf, dtype=float)
if sys.issiso():
dc = dc.squeeze()
try:
np.testing.assert_array_equal(dc, sys.dcgain())
except NotImplementedError:
# Skip MIMO tests if there is no slycot
pytest.skip("slycot required for MIMO dcgain")
def test_scalar_static_gain(self):
"""Regression: can we create a scalar static gain?
make sure StateSpace internals, specifically ABC matrix
sizes, are OK for LTI operations
"""
g1 = StateSpace([], [], [], [2])
g2 = StateSpace([], [], [], [3])
assert g1.dt == None
assert g2.dt == None
g3 = g1 * g2
assert 6 == g3.D[0, 0]
assert g3.dt == None
g4 = g1 + g2
assert 5 == g4.D[0, 0]
assert g4.dt == None
g5 = g1.feedback(g2)
np.testing.assert_allclose(2. / 7, g5.D[0, 0])
assert g5.dt == None
g6 = g1.append(g2)
np.testing.assert_allclose(np.diag([2, 3]), g6.D)
assert g6.dt == None
def test_matrix_static_gain(self):
"""Regression: can we create matrix static gains?"""
d1 = np.array([[1, 2, 3], [4, 5, 6]])
d2 = np.array([[7, 8], [9, 10], [11, 12]])
g1 = StateSpace([], [], [], d1)
# _remove_useless_states was making A = [[0]]
assert (0, 0) == g1.A.shape
g2 = StateSpace([], [], [], d2)
g3 = StateSpace([], [], [], d2.T)
h1 = g1 * g2
np.testing.assert_allclose(d1 @ d2, h1.D)
h2 = g1 + g3
np.testing.assert_allclose(d1 + d2.T, h2.D)
h3 = g1.feedback(g2)
np.testing.assert_array_almost_equal(
solve(np.eye(2) + d1 @ d2, d1), h3.D)
h4 = g1.append(g2)
np.testing.assert_allclose(block_diag(d1, d2), h4.D)
def test_remove_useless_states(self):
"""Regression: _remove_useless_states gives correct ABC sizes."""
g1 = StateSpace(np.zeros((3, 3)), np.zeros((3, 4)),
np.zeros((5, 3)), np.zeros((5, 4)),
remove_useless_states=True)
assert (0, 0) == g1.A.shape
assert (0, 4) == g1.B.shape
assert (5, 0) == g1.C.shape
assert (5, 4) == g1.D.shape
assert 0 == g1.nstates
@pytest.mark.parametrize("A, B, C, D",
[([1], [], [], [1]),
([1], [1], [], [1]),
([1], [], [1], [1]),
([], [1], [], [1]),
([], [1], [1], [1]),
([], [], [1], [1]),
([1], [1], [1], [])])
def test_bad_empty_matrices(self, A, B, C, D):
"""Mismatched ABCD matrices when some are empty."""
with pytest.raises(ValueError):
StateSpace(A, B, C, D)
def test_minreal_static_gain(self):
"""Regression: minreal on static gain was failing."""
g1 = StateSpace([], [], [], [1])
g2 = g1.minreal()
np.testing.assert_array_equal(g1.A, g2.A)
np.testing.assert_array_equal(g1.B, g2.B)
np.testing.assert_array_equal(g1.C, g2.C)
np.testing.assert_allclose(g1.D, g2.D)
def test_empty(self):
"""Regression: can we create an empty StateSpace object?"""
g1 = StateSpace([], [], [], [])
assert 0 == g1.nstates
assert 0 == g1.ninputs
assert 0 == g1.noutputs
def test_matrix_to_state_space(self):
"""_convert_to_statespace(matrix) gives ss([],[],[],D)"""
with pytest.deprecated_call():
D = np.matrix([[1, 2, 3], [4, 5, 6]])
g = _convert_to_statespace(D)