test_ltisys.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. import warnings
  2. import numpy as np
  3. from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,
  4. assert_, suppress_warnings)
  5. from pytest import raises as assert_raises
  6. from scipy.signal import (ss2tf, tf2ss, lsim2, impulse2, step2, lti,
  7. dlti, bode, freqresp, lsim, impulse, step,
  8. abcd_normalize, place_poles,
  9. TransferFunction, StateSpace, ZerosPolesGain)
  10. from scipy.signal._filter_design import BadCoefficients
  11. import scipy.linalg as linalg
  12. from scipy.sparse._sputils import matrix
  13. def _assert_poles_close(P1,P2, rtol=1e-8, atol=1e-8):
  14. """
  15. Check each pole in P1 is close to a pole in P2 with a 1e-8
  16. relative tolerance or 1e-8 absolute tolerance (useful for zero poles).
  17. These tolerances are very strict but the systems tested are known to
  18. accept these poles so we should not be far from what is requested.
  19. """
  20. P2 = P2.copy()
  21. for p1 in P1:
  22. found = False
  23. for p2_idx in range(P2.shape[0]):
  24. if np.allclose([np.real(p1), np.imag(p1)],
  25. [np.real(P2[p2_idx]), np.imag(P2[p2_idx])],
  26. rtol, atol):
  27. found = True
  28. np.delete(P2, p2_idx)
  29. break
  30. if not found:
  31. raise ValueError("Can't find pole " + str(p1) + " in " + str(P2))
  32. class TestPlacePoles:
  33. def _check(self, A, B, P, **kwargs):
  34. """
  35. Perform the most common tests on the poles computed by place_poles
  36. and return the Bunch object for further specific tests
  37. """
  38. fsf = place_poles(A, B, P, **kwargs)
  39. expected, _ = np.linalg.eig(A - np.dot(B, fsf.gain_matrix))
  40. _assert_poles_close(expected, fsf.requested_poles)
  41. _assert_poles_close(expected, fsf.computed_poles)
  42. _assert_poles_close(P,fsf.requested_poles)
  43. return fsf
  44. def test_real(self):
  45. # Test real pole placement using KNV and YT0 algorithm and example 1 in
  46. # section 4 of the reference publication (see place_poles docstring)
  47. A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0,
  48. 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273,
  49. 1.343, -2.104]).reshape(4, 4)
  50. B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146,0]).reshape(4, 2)
  51. P = np.array([-0.2, -0.5, -5.0566, -8.6659])
  52. # Check that both KNV and YT compute correct K matrix
  53. self._check(A, B, P, method='KNV0')
  54. self._check(A, B, P, method='YT')
  55. # Try to reach the specific case in _YT_real where two singular
  56. # values are almost equal. This is to improve code coverage but I
  57. # have no way to be sure this code is really reached
  58. # on some architectures this can lead to a RuntimeWarning invalid
  59. # value in divide (see gh-7590), so suppress it for now
  60. with np.errstate(invalid='ignore'):
  61. self._check(A, B, (2,2,3,3))
  62. def test_complex(self):
  63. # Test complex pole placement on a linearized car model, taken from L.
  64. # Jaulin, Automatique pour la robotique, Cours et Exercices, iSTE
  65. # editions p 184/185
  66. A = np.array([[0, 7, 0, 0],
  67. [0, 0, 0, 7/3.],
  68. [0, 0, 0, 0],
  69. [0, 0, 0, 0]])
  70. B = np.array([[0, 0],
  71. [0, 0],
  72. [1, 0],
  73. [0, 1]])
  74. # Test complex poles on YT
  75. P = np.array([-3, -1, -2-1j, -2+1j])
  76. # on macOS arm64 this can lead to a RuntimeWarning invalid
  77. # value in divide, so suppress it for now
  78. with np.errstate(divide='ignore', invalid='ignore'):
  79. self._check(A, B, P)
  80. # Try to reach the specific case in _YT_complex where two singular
  81. # values are almost equal. This is to improve code coverage but I
  82. # have no way to be sure this code is really reached
  83. P = [0-1e-6j,0+1e-6j,-10,10]
  84. with np.errstate(divide='ignore', invalid='ignore'):
  85. self._check(A, B, P, maxiter=1000)
  86. # Try to reach the specific case in _YT_complex where the rank two
  87. # update yields two null vectors. This test was found via Monte Carlo.
  88. A = np.array(
  89. [-2148,-2902, -2267, -598, -1722, -1829, -165, -283, -2546,
  90. -167, -754, -2285, -543, -1700, -584, -2978, -925, -1300,
  91. -1583, -984, -386, -2650, -764, -897, -517, -1598, 2, -1709,
  92. -291, -338, -153, -1804, -1106, -1168, -867, -2297]
  93. ).reshape(6,6)
  94. B = np.array(
  95. [-108, -374, -524, -1285, -1232, -161, -1204, -672, -637,
  96. -15, -483, -23, -931, -780, -1245, -1129, -1290, -1502,
  97. -952, -1374, -62, -964, -930, -939, -792, -756, -1437,
  98. -491, -1543, -686]
  99. ).reshape(6,5)
  100. P = [-25.-29.j, -25.+29.j, 31.-42.j, 31.+42.j, 33.-41.j, 33.+41.j]
  101. self._check(A, B, P)
  102. # Use a lot of poles to go through all cases for update_order
  103. # in _YT_loop
  104. big_A = np.ones((11,11))-np.eye(11)
  105. big_B = np.ones((11,10))-np.diag([1]*10,1)[:,1:]
  106. big_A[:6,:6] = A
  107. big_B[:6,:5] = B
  108. P = [-10,-20,-30,40,50,60,70,-20-5j,-20+5j,5+3j,5-3j]
  109. with np.errstate(divide='ignore', invalid='ignore'):
  110. self._check(big_A, big_B, P)
  111. #check with only complex poles and only real poles
  112. P = [-10,-20,-30,-40,-50,-60,-70,-80,-90,-100]
  113. self._check(big_A[:-1,:-1], big_B[:-1,:-1], P)
  114. P = [-10+10j,-20+20j,-30+30j,-40+40j,-50+50j,
  115. -10-10j,-20-20j,-30-30j,-40-40j,-50-50j]
  116. self._check(big_A[:-1,:-1], big_B[:-1,:-1], P)
  117. # need a 5x5 array to ensure YT handles properly when there
  118. # is only one real pole and several complex
  119. A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0,
  120. 0,0,0,5,0,0,0,0,9]).reshape(5,5)
  121. B = np.array([0,0,0,0,1,0,0,1,2,3]).reshape(5,2)
  122. P = np.array([-2, -3+1j, -3-1j, -1+1j, -1-1j])
  123. with np.errstate(divide='ignore', invalid='ignore'):
  124. place_poles(A, B, P)
  125. # same test with an odd number of real poles > 1
  126. # this is another specific case of YT
  127. P = np.array([-2, -3, -4, -1+1j, -1-1j])
  128. with np.errstate(divide='ignore', invalid='ignore'):
  129. self._check(A, B, P)
  130. def test_tricky_B(self):
  131. # check we handle as we should the 1 column B matrices and
  132. # n column B matrices (with n such as shape(A)=(n, n))
  133. A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0,
  134. 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273,
  135. 1.343, -2.104]).reshape(4, 4)
  136. B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146, 0, 1, 2, 3, 4,
  137. 5, 6, 7, 8]).reshape(4, 4)
  138. # KNV or YT are not called here, it's a specific case with only
  139. # one unique solution
  140. P = np.array([-0.2, -0.5, -5.0566, -8.6659])
  141. fsf = self._check(A, B, P)
  142. # rtol and nb_iter should be set to np.nan as the identity can be
  143. # used as transfer matrix
  144. assert_equal(fsf.rtol, np.nan)
  145. assert_equal(fsf.nb_iter, np.nan)
  146. # check with complex poles too as they trigger a specific case in
  147. # the specific case :-)
  148. P = np.array((-2+1j,-2-1j,-3,-2))
  149. fsf = self._check(A, B, P)
  150. assert_equal(fsf.rtol, np.nan)
  151. assert_equal(fsf.nb_iter, np.nan)
  152. #now test with a B matrix with only one column (no optimisation)
  153. B = B[:,0].reshape(4,1)
  154. P = np.array((-2+1j,-2-1j,-3,-2))
  155. fsf = self._check(A, B, P)
  156. # we can't optimize anything, check they are set to 0 as expected
  157. assert_equal(fsf.rtol, 0)
  158. assert_equal(fsf.nb_iter, 0)
  159. def test_errors(self):
  160. # Test input mistakes from user
  161. A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0]).reshape(4,4)
  162. B = np.array([0,0,0,0,1,0,0,1]).reshape(4,2)
  163. #should fail as the method keyword is invalid
  164. assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
  165. method="foo")
  166. #should fail as poles are not 1D array
  167. assert_raises(ValueError, place_poles, A, B,
  168. np.array((-2.1,-2.2,-2.3,-2.4)).reshape(4,1))
  169. #should fail as A is not a 2D array
  170. assert_raises(ValueError, place_poles, A[:,:,np.newaxis], B,
  171. (-2.1,-2.2,-2.3,-2.4))
  172. #should fail as B is not a 2D array
  173. assert_raises(ValueError, place_poles, A, B[:,:,np.newaxis],
  174. (-2.1,-2.2,-2.3,-2.4))
  175. #should fail as there are too many poles
  176. assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4,-3))
  177. #should fail as there are not enough poles
  178. assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3))
  179. #should fail as the rtol is greater than 1
  180. assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
  181. rtol=42)
  182. #should fail as maxiter is smaller than 1
  183. assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
  184. maxiter=-42)
  185. # should fail as ndim(B) is two
  186. assert_raises(ValueError, place_poles, A, B, (-2,-2,-2,-2))
  187. #unctrollable system
  188. assert_raises(ValueError, place_poles, np.ones((4,4)),
  189. np.ones((4,2)), (1,2,3,4))
  190. # Should not raise ValueError as the poles can be placed but should
  191. # raise a warning as the convergence is not reached
  192. with warnings.catch_warnings(record=True) as w:
  193. warnings.simplefilter("always")
  194. fsf = place_poles(A, B, (-1,-2,-3,-4), rtol=1e-16, maxiter=42)
  195. assert_(len(w) == 1)
  196. assert_(issubclass(w[-1].category, UserWarning))
  197. assert_("Convergence was not reached after maxiter iterations"
  198. in str(w[-1].message))
  199. assert_equal(fsf.nb_iter, 42)
  200. # should fail as a complex misses its conjugate
  201. assert_raises(ValueError, place_poles, A, B, (-2+1j,-2-1j,-2+3j,-2))
  202. # should fail as A is not square
  203. assert_raises(ValueError, place_poles, A[:,:3], B, (-2,-3,-4,-5))
  204. # should fail as B has not the same number of lines as A
  205. assert_raises(ValueError, place_poles, A, B[:3,:], (-2,-3,-4,-5))
  206. # should fail as KNV0 does not support complex poles
  207. assert_raises(ValueError, place_poles, A, B,
  208. (-2+1j,-2-1j,-2+3j,-2-3j), method="KNV0")
  209. class TestSS2TF:
  210. def check_matrix_shapes(self, p, q, r):
  211. ss2tf(np.zeros((p, p)),
  212. np.zeros((p, q)),
  213. np.zeros((r, p)),
  214. np.zeros((r, q)), 0)
  215. def test_shapes(self):
  216. # Each tuple holds:
  217. # number of states, number of inputs, number of outputs
  218. for p, q, r in [(3, 3, 3), (1, 3, 3), (1, 1, 1)]:
  219. self.check_matrix_shapes(p, q, r)
  220. def test_basic(self):
  221. # Test a round trip through tf2ss and ss2tf.
  222. b = np.array([1.0, 3.0, 5.0])
  223. a = np.array([1.0, 2.0, 3.0])
  224. A, B, C, D = tf2ss(b, a)
  225. assert_allclose(A, [[-2, -3], [1, 0]], rtol=1e-13)
  226. assert_allclose(B, [[1], [0]], rtol=1e-13)
  227. assert_allclose(C, [[1, 2]], rtol=1e-13)
  228. assert_allclose(D, [[1]], rtol=1e-14)
  229. bb, aa = ss2tf(A, B, C, D)
  230. assert_allclose(bb[0], b, rtol=1e-13)
  231. assert_allclose(aa, a, rtol=1e-13)
  232. def test_zero_order_round_trip(self):
  233. # See gh-5760
  234. tf = (2, 1)
  235. A, B, C, D = tf2ss(*tf)
  236. assert_allclose(A, [[0]], rtol=1e-13)
  237. assert_allclose(B, [[0]], rtol=1e-13)
  238. assert_allclose(C, [[0]], rtol=1e-13)
  239. assert_allclose(D, [[2]], rtol=1e-13)
  240. num, den = ss2tf(A, B, C, D)
  241. assert_allclose(num, [[2, 0]], rtol=1e-13)
  242. assert_allclose(den, [1, 0], rtol=1e-13)
  243. tf = ([[5], [2]], 1)
  244. A, B, C, D = tf2ss(*tf)
  245. assert_allclose(A, [[0]], rtol=1e-13)
  246. assert_allclose(B, [[0]], rtol=1e-13)
  247. assert_allclose(C, [[0], [0]], rtol=1e-13)
  248. assert_allclose(D, [[5], [2]], rtol=1e-13)
  249. num, den = ss2tf(A, B, C, D)
  250. assert_allclose(num, [[5, 0], [2, 0]], rtol=1e-13)
  251. assert_allclose(den, [1, 0], rtol=1e-13)
  252. def test_simo_round_trip(self):
  253. # See gh-5753
  254. tf = ([[1, 2], [1, 1]], [1, 2])
  255. A, B, C, D = tf2ss(*tf)
  256. assert_allclose(A, [[-2]], rtol=1e-13)
  257. assert_allclose(B, [[1]], rtol=1e-13)
  258. assert_allclose(C, [[0], [-1]], rtol=1e-13)
  259. assert_allclose(D, [[1], [1]], rtol=1e-13)
  260. num, den = ss2tf(A, B, C, D)
  261. assert_allclose(num, [[1, 2], [1, 1]], rtol=1e-13)
  262. assert_allclose(den, [1, 2], rtol=1e-13)
  263. tf = ([[1, 0, 1], [1, 1, 1]], [1, 1, 1])
  264. A, B, C, D = tf2ss(*tf)
  265. assert_allclose(A, [[-1, -1], [1, 0]], rtol=1e-13)
  266. assert_allclose(B, [[1], [0]], rtol=1e-13)
  267. assert_allclose(C, [[-1, 0], [0, 0]], rtol=1e-13)
  268. assert_allclose(D, [[1], [1]], rtol=1e-13)
  269. num, den = ss2tf(A, B, C, D)
  270. assert_allclose(num, [[1, 0, 1], [1, 1, 1]], rtol=1e-13)
  271. assert_allclose(den, [1, 1, 1], rtol=1e-13)
  272. tf = ([[1, 2, 3], [1, 2, 3]], [1, 2, 3, 4])
  273. A, B, C, D = tf2ss(*tf)
  274. assert_allclose(A, [[-2, -3, -4], [1, 0, 0], [0, 1, 0]], rtol=1e-13)
  275. assert_allclose(B, [[1], [0], [0]], rtol=1e-13)
  276. assert_allclose(C, [[1, 2, 3], [1, 2, 3]], rtol=1e-13)
  277. assert_allclose(D, [[0], [0]], rtol=1e-13)
  278. num, den = ss2tf(A, B, C, D)
  279. assert_allclose(num, [[0, 1, 2, 3], [0, 1, 2, 3]], rtol=1e-13)
  280. assert_allclose(den, [1, 2, 3, 4], rtol=1e-13)
  281. tf = (np.array([1, [2, 3]], dtype=object), [1, 6])
  282. A, B, C, D = tf2ss(*tf)
  283. assert_allclose(A, [[-6]], rtol=1e-31)
  284. assert_allclose(B, [[1]], rtol=1e-31)
  285. assert_allclose(C, [[1], [-9]], rtol=1e-31)
  286. assert_allclose(D, [[0], [2]], rtol=1e-31)
  287. num, den = ss2tf(A, B, C, D)
  288. assert_allclose(num, [[0, 1], [2, 3]], rtol=1e-13)
  289. assert_allclose(den, [1, 6], rtol=1e-13)
  290. tf = (np.array([[1, -3], [1, 2, 3]], dtype=object), [1, 6, 5])
  291. A, B, C, D = tf2ss(*tf)
  292. assert_allclose(A, [[-6, -5], [1, 0]], rtol=1e-13)
  293. assert_allclose(B, [[1], [0]], rtol=1e-13)
  294. assert_allclose(C, [[1, -3], [-4, -2]], rtol=1e-13)
  295. assert_allclose(D, [[0], [1]], rtol=1e-13)
  296. num, den = ss2tf(A, B, C, D)
  297. assert_allclose(num, [[0, 1, -3], [1, 2, 3]], rtol=1e-13)
  298. assert_allclose(den, [1, 6, 5], rtol=1e-13)
  299. def test_all_int_arrays(self):
  300. A = [[0, 1, 0], [0, 0, 1], [-3, -4, -2]]
  301. B = [[0], [0], [1]]
  302. C = [[5, 1, 0]]
  303. D = [[0]]
  304. num, den = ss2tf(A, B, C, D)
  305. assert_allclose(num, [[0.0, 0.0, 1.0, 5.0]], rtol=1e-13, atol=1e-14)
  306. assert_allclose(den, [1.0, 2.0, 4.0, 3.0], rtol=1e-13)
  307. def test_multioutput(self):
  308. # Regression test for gh-2669.
  309. # 4 states
  310. A = np.array([[-1.0, 0.0, 1.0, 0.0],
  311. [-1.0, 0.0, 2.0, 0.0],
  312. [-4.0, 0.0, 3.0, 0.0],
  313. [-8.0, 8.0, 0.0, 4.0]])
  314. # 1 input
  315. B = np.array([[0.3],
  316. [0.0],
  317. [7.0],
  318. [0.0]])
  319. # 3 outputs
  320. C = np.array([[0.0, 1.0, 0.0, 0.0],
  321. [0.0, 0.0, 0.0, 1.0],
  322. [8.0, 8.0, 0.0, 0.0]])
  323. D = np.array([[0.0],
  324. [0.0],
  325. [1.0]])
  326. # Get the transfer functions for all the outputs in one call.
  327. b_all, a = ss2tf(A, B, C, D)
  328. # Get the transfer functions for each output separately.
  329. b0, a0 = ss2tf(A, B, C[0], D[0])
  330. b1, a1 = ss2tf(A, B, C[1], D[1])
  331. b2, a2 = ss2tf(A, B, C[2], D[2])
  332. # Check that we got the same results.
  333. assert_allclose(a0, a, rtol=1e-13)
  334. assert_allclose(a1, a, rtol=1e-13)
  335. assert_allclose(a2, a, rtol=1e-13)
  336. assert_allclose(b_all, np.vstack((b0, b1, b2)), rtol=1e-13, atol=1e-14)
  337. class TestLsim:
  338. def lti_nowarn(self, *args):
  339. with suppress_warnings() as sup:
  340. sup.filter(BadCoefficients)
  341. system = lti(*args)
  342. return system
  343. def test_first_order(self):
  344. # y' = -y
  345. # exact solution is y(t) = exp(-t)
  346. system = self.lti_nowarn(-1.,1.,1.,0.)
  347. t = np.linspace(0,5)
  348. u = np.zeros_like(t)
  349. tout, y, x = lsim(system, u, t, X0=[1.0])
  350. expected_x = np.exp(-tout)
  351. assert_almost_equal(x, expected_x)
  352. assert_almost_equal(y, expected_x)
  353. def test_integrator(self):
  354. # integrator: y' = u
  355. system = self.lti_nowarn(0., 1., 1., 0.)
  356. t = np.linspace(0,5)
  357. u = t
  358. tout, y, x = lsim(system, u, t)
  359. expected_x = 0.5 * tout**2
  360. assert_almost_equal(x, expected_x)
  361. assert_almost_equal(y, expected_x)
  362. def test_double_integrator(self):
  363. # double integrator: y'' = 2u
  364. A = matrix([[0., 1.], [0., 0.]])
  365. B = matrix([[0.], [1.]])
  366. C = matrix([[2., 0.]])
  367. system = self.lti_nowarn(A, B, C, 0.)
  368. t = np.linspace(0,5)
  369. u = np.ones_like(t)
  370. tout, y, x = lsim(system, u, t)
  371. expected_x = np.transpose(np.array([0.5 * tout**2, tout]))
  372. expected_y = tout**2
  373. assert_almost_equal(x, expected_x)
  374. assert_almost_equal(y, expected_y)
  375. def test_jordan_block(self):
  376. # Non-diagonalizable A matrix
  377. # x1' + x1 = x2
  378. # x2' + x2 = u
  379. # y = x1
  380. # Exact solution with u = 0 is y(t) = t exp(-t)
  381. A = matrix([[-1., 1.], [0., -1.]])
  382. B = matrix([[0.], [1.]])
  383. C = matrix([[1., 0.]])
  384. system = self.lti_nowarn(A, B, C, 0.)
  385. t = np.linspace(0,5)
  386. u = np.zeros_like(t)
  387. tout, y, x = lsim(system, u, t, X0=[0.0, 1.0])
  388. expected_y = tout * np.exp(-tout)
  389. assert_almost_equal(y, expected_y)
  390. def test_miso(self):
  391. # A system with two state variables, two inputs, and one output.
  392. A = np.array([[-1.0, 0.0], [0.0, -2.0]])
  393. B = np.array([[1.0, 0.0], [0.0, 1.0]])
  394. C = np.array([1.0, 0.0])
  395. D = np.zeros((1,2))
  396. system = self.lti_nowarn(A, B, C, D)
  397. t = np.linspace(0, 5.0, 101)
  398. u = np.zeros_like(t)
  399. tout, y, x = lsim(system, u, t, X0=[1.0, 1.0])
  400. expected_y = np.exp(-tout)
  401. expected_x0 = np.exp(-tout)
  402. expected_x1 = np.exp(-2.0*tout)
  403. assert_almost_equal(y, expected_y)
  404. assert_almost_equal(x[:,0], expected_x0)
  405. assert_almost_equal(x[:,1], expected_x1)
  406. def test_nonzero_initial_time(self):
  407. system = self.lti_nowarn(-1.,1.,1.,0.)
  408. t = np.linspace(1,2)
  409. u = np.zeros_like(t)
  410. tout, y, x = lsim(system, u, t, X0=[1.0])
  411. expected_y = np.exp(-tout)
  412. assert_almost_equal(y, expected_y)
  413. class Test_lsim2:
  414. def test_01(self):
  415. t = np.linspace(0,10,1001)
  416. u = np.zeros_like(t)
  417. # First order system: x'(t) + x(t) = u(t), x(0) = 1.
  418. # Exact solution is x(t) = exp(-t).
  419. system = ([1.0],[1.0,1.0])
  420. tout, y, x = lsim2(system, u, t, X0=[1.0])
  421. expected_x = np.exp(-tout)
  422. assert_almost_equal(x[:,0], expected_x)
  423. def test_02(self):
  424. t = np.array([0.0, 1.0, 1.0, 3.0])
  425. u = np.array([0.0, 0.0, 1.0, 1.0])
  426. # Simple integrator: x'(t) = u(t)
  427. system = ([1.0],[1.0,0.0])
  428. tout, y, x = lsim2(system, u, t, X0=[1.0])
  429. expected_x = np.maximum(1.0, tout)
  430. assert_almost_equal(x[:,0], expected_x)
  431. def test_03(self):
  432. t = np.array([0.0, 1.0, 1.0, 1.1, 1.1, 2.0])
  433. u = np.array([0.0, 0.0, 1.0, 1.0, 0.0, 0.0])
  434. # Simple integrator: x'(t) = u(t)
  435. system = ([1.0],[1.0, 0.0])
  436. tout, y, x = lsim2(system, u, t, hmax=0.01)
  437. expected_x = np.array([0.0, 0.0, 0.0, 0.1, 0.1, 0.1])
  438. assert_almost_equal(x[:,0], expected_x)
  439. def test_04(self):
  440. t = np.linspace(0, 10, 1001)
  441. u = np.zeros_like(t)
  442. # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0.
  443. # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution
  444. # is (1-t)*exp(-t).
  445. system = ([1.0], [1.0, 2.0, 1.0])
  446. tout, y, x = lsim2(system, u, t, X0=[1.0, 0.0])
  447. expected_x = (1.0 - tout) * np.exp(-tout)
  448. assert_almost_equal(x[:,0], expected_x)
  449. def test_05(self):
  450. # The call to lsim2 triggers a "BadCoefficients" warning from
  451. # scipy.signal._filter_design, but the test passes. I think the warning
  452. # is related to the incomplete handling of multi-input systems in
  453. # scipy.signal.
  454. # A system with two state variables, two inputs, and one output.
  455. A = np.array([[-1.0, 0.0], [0.0, -2.0]])
  456. B = np.array([[1.0, 0.0], [0.0, 1.0]])
  457. C = np.array([1.0, 0.0])
  458. D = np.zeros((1, 2))
  459. t = np.linspace(0, 10.0, 101)
  460. with suppress_warnings() as sup:
  461. sup.filter(BadCoefficients)
  462. tout, y, x = lsim2((A,B,C,D), T=t, X0=[1.0, 1.0])
  463. expected_y = np.exp(-tout)
  464. expected_x0 = np.exp(-tout)
  465. expected_x1 = np.exp(-2.0 * tout)
  466. assert_almost_equal(y, expected_y)
  467. assert_almost_equal(x[:,0], expected_x0)
  468. assert_almost_equal(x[:,1], expected_x1)
  469. def test_06(self):
  470. # Test use of the default values of the arguments `T` and `U`.
  471. # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0.
  472. # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution
  473. # is (1-t)*exp(-t).
  474. system = ([1.0], [1.0, 2.0, 1.0])
  475. tout, y, x = lsim2(system, X0=[1.0, 0.0])
  476. expected_x = (1.0 - tout) * np.exp(-tout)
  477. assert_almost_equal(x[:,0], expected_x)
  478. class _TestImpulseFuncs:
  479. # Common tests for impulse/impulse2 (= self.func)
  480. def test_01(self):
  481. # First order system: x'(t) + x(t) = u(t)
  482. # Exact impulse response is x(t) = exp(-t).
  483. system = ([1.0], [1.0,1.0])
  484. tout, y = self.func(system)
  485. expected_y = np.exp(-tout)
  486. assert_almost_equal(y, expected_y)
  487. def test_02(self):
  488. # Specify the desired time values for the output.
  489. # First order system: x'(t) + x(t) = u(t)
  490. # Exact impulse response is x(t) = exp(-t).
  491. system = ([1.0], [1.0,1.0])
  492. n = 21
  493. t = np.linspace(0, 2.0, n)
  494. tout, y = self.func(system, T=t)
  495. assert_equal(tout.shape, (n,))
  496. assert_almost_equal(tout, t)
  497. expected_y = np.exp(-t)
  498. assert_almost_equal(y, expected_y)
  499. def test_03(self):
  500. # Specify an initial condition as a scalar.
  501. # First order system: x'(t) + x(t) = u(t), x(0)=3.0
  502. # Exact impulse response is x(t) = 4*exp(-t).
  503. system = ([1.0], [1.0,1.0])
  504. tout, y = self.func(system, X0=3.0)
  505. expected_y = 4.0 * np.exp(-tout)
  506. assert_almost_equal(y, expected_y)
  507. def test_04(self):
  508. # Specify an initial condition as a list.
  509. # First order system: x'(t) + x(t) = u(t), x(0)=3.0
  510. # Exact impulse response is x(t) = 4*exp(-t).
  511. system = ([1.0], [1.0,1.0])
  512. tout, y = self.func(system, X0=[3.0])
  513. expected_y = 4.0 * np.exp(-tout)
  514. assert_almost_equal(y, expected_y)
  515. def test_05(self):
  516. # Simple integrator: x'(t) = u(t)
  517. system = ([1.0], [1.0,0.0])
  518. tout, y = self.func(system)
  519. expected_y = np.ones_like(tout)
  520. assert_almost_equal(y, expected_y)
  521. def test_06(self):
  522. # Second order system with a repeated root:
  523. # x''(t) + 2*x(t) + x(t) = u(t)
  524. # The exact impulse response is t*exp(-t).
  525. system = ([1.0], [1.0, 2.0, 1.0])
  526. tout, y = self.func(system)
  527. expected_y = tout * np.exp(-tout)
  528. assert_almost_equal(y, expected_y)
  529. def test_array_like(self):
  530. # Test that function can accept sequences, scalars.
  531. system = ([1.0], [1.0, 2.0, 1.0])
  532. # TODO: add meaningful test where X0 is a list
  533. tout, y = self.func(system, X0=[3], T=[5, 6])
  534. tout, y = self.func(system, X0=[3], T=[5])
  535. def test_array_like2(self):
  536. system = ([1.0], [1.0, 2.0, 1.0])
  537. tout, y = self.func(system, X0=3, T=5)
  538. class TestImpulse2(_TestImpulseFuncs):
  539. def setup_method(self):
  540. self.func = impulse2
  541. class TestImpulse(_TestImpulseFuncs):
  542. def setup_method(self):
  543. self.func = impulse
  544. class _TestStepFuncs:
  545. def test_01(self):
  546. # First order system: x'(t) + x(t) = u(t)
  547. # Exact step response is x(t) = 1 - exp(-t).
  548. system = ([1.0], [1.0,1.0])
  549. tout, y = self.func(system)
  550. expected_y = 1.0 - np.exp(-tout)
  551. assert_almost_equal(y, expected_y)
  552. def test_02(self):
  553. # Specify the desired time values for the output.
  554. # First order system: x'(t) + x(t) = u(t)
  555. # Exact step response is x(t) = 1 - exp(-t).
  556. system = ([1.0], [1.0,1.0])
  557. n = 21
  558. t = np.linspace(0, 2.0, n)
  559. tout, y = self.func(system, T=t)
  560. assert_equal(tout.shape, (n,))
  561. assert_almost_equal(tout, t)
  562. expected_y = 1 - np.exp(-t)
  563. assert_almost_equal(y, expected_y)
  564. def test_03(self):
  565. # Specify an initial condition as a scalar.
  566. # First order system: x'(t) + x(t) = u(t), x(0)=3.0
  567. # Exact step response is x(t) = 1 + 2*exp(-t).
  568. system = ([1.0], [1.0,1.0])
  569. tout, y = self.func(system, X0=3.0)
  570. expected_y = 1 + 2.0*np.exp(-tout)
  571. assert_almost_equal(y, expected_y)
  572. def test_04(self):
  573. # Specify an initial condition as a list.
  574. # First order system: x'(t) + x(t) = u(t), x(0)=3.0
  575. # Exact step response is x(t) = 1 + 2*exp(-t).
  576. system = ([1.0], [1.0,1.0])
  577. tout, y = self.func(system, X0=[3.0])
  578. expected_y = 1 + 2.0*np.exp(-tout)
  579. assert_almost_equal(y, expected_y)
  580. def test_05(self):
  581. # Simple integrator: x'(t) = u(t)
  582. # Exact step response is x(t) = t.
  583. system = ([1.0],[1.0,0.0])
  584. tout, y = self.func(system)
  585. expected_y = tout
  586. assert_almost_equal(y, expected_y)
  587. def test_06(self):
  588. # Second order system with a repeated root:
  589. # x''(t) + 2*x(t) + x(t) = u(t)
  590. # The exact step response is 1 - (1 + t)*exp(-t).
  591. system = ([1.0], [1.0, 2.0, 1.0])
  592. tout, y = self.func(system)
  593. expected_y = 1 - (1 + tout) * np.exp(-tout)
  594. assert_almost_equal(y, expected_y)
  595. def test_array_like(self):
  596. # Test that function can accept sequences, scalars.
  597. system = ([1.0], [1.0, 2.0, 1.0])
  598. # TODO: add meaningful test where X0 is a list
  599. tout, y = self.func(system, T=[5, 6])
  600. class TestStep2(_TestStepFuncs):
  601. def setup_method(self):
  602. self.func = step2
  603. def test_05(self):
  604. # This test is almost the same as the one it overwrites in the base
  605. # class. The only difference is the tolerances passed to step2:
  606. # the default tolerances are not accurate enough for this test
  607. # Simple integrator: x'(t) = u(t)
  608. # Exact step response is x(t) = t.
  609. system = ([1.0], [1.0,0.0])
  610. tout, y = self.func(system, atol=1e-10, rtol=1e-8)
  611. expected_y = tout
  612. assert_almost_equal(y, expected_y)
  613. class TestStep(_TestStepFuncs):
  614. def setup_method(self):
  615. self.func = step
  616. def test_complex_input(self):
  617. # Test that complex input doesn't raise an error.
  618. # `step` doesn't seem to have been designed for complex input, but this
  619. # works and may be used, so add regression test. See gh-2654.
  620. step(([], [-1], 1+0j))
  621. class TestLti:
  622. def test_lti_instantiation(self):
  623. # Test that lti can be instantiated with sequences, scalars.
  624. # See PR-225.
  625. # TransferFunction
  626. s = lti([1], [-1])
  627. assert_(isinstance(s, TransferFunction))
  628. assert_(isinstance(s, lti))
  629. assert_(not isinstance(s, dlti))
  630. assert_(s.dt is None)
  631. # ZerosPolesGain
  632. s = lti(np.array([]), np.array([-1]), 1)
  633. assert_(isinstance(s, ZerosPolesGain))
  634. assert_(isinstance(s, lti))
  635. assert_(not isinstance(s, dlti))
  636. assert_(s.dt is None)
  637. # StateSpace
  638. s = lti([], [-1], 1)
  639. s = lti([1], [-1], 1, 3)
  640. assert_(isinstance(s, StateSpace))
  641. assert_(isinstance(s, lti))
  642. assert_(not isinstance(s, dlti))
  643. assert_(s.dt is None)
  644. class TestStateSpace:
  645. def test_initialization(self):
  646. # Check that all initializations work
  647. StateSpace(1, 1, 1, 1)
  648. StateSpace([1], [2], [3], [4])
  649. StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]),
  650. np.array([[1, 0]]), np.array([[0]]))
  651. def test_conversion(self):
  652. # Check the conversion functions
  653. s = StateSpace(1, 2, 3, 4)
  654. assert_(isinstance(s.to_ss(), StateSpace))
  655. assert_(isinstance(s.to_tf(), TransferFunction))
  656. assert_(isinstance(s.to_zpk(), ZerosPolesGain))
  657. # Make sure copies work
  658. assert_(StateSpace(s) is not s)
  659. assert_(s.to_ss() is not s)
  660. def test_properties(self):
  661. # Test setters/getters for cross class properties.
  662. # This implicitly tests to_tf() and to_zpk()
  663. # Getters
  664. s = StateSpace(1, 1, 1, 1)
  665. assert_equal(s.poles, [1])
  666. assert_equal(s.zeros, [0])
  667. assert_(s.dt is None)
  668. def test_operators(self):
  669. # Test +/-/* operators on systems
  670. class BadType:
  671. pass
  672. s1 = StateSpace(np.array([[-0.5, 0.7], [0.3, -0.8]]),
  673. np.array([[1], [0]]),
  674. np.array([[1, 0]]),
  675. np.array([[0]]),
  676. )
  677. s2 = StateSpace(np.array([[-0.2, -0.1], [0.4, -0.1]]),
  678. np.array([[1], [0]]),
  679. np.array([[1, 0]]),
  680. np.array([[0]])
  681. )
  682. s_discrete = s1.to_discrete(0.1)
  683. s2_discrete = s2.to_discrete(0.2)
  684. s3_discrete = s2.to_discrete(0.1)
  685. # Impulse response
  686. t = np.linspace(0, 1, 100)
  687. u = np.zeros_like(t)
  688. u[0] = 1
  689. # Test multiplication
  690. for typ in (int, float, complex, np.float32, np.complex128, np.array):
  691. assert_allclose(lsim(typ(2) * s1, U=u, T=t)[1],
  692. typ(2) * lsim(s1, U=u, T=t)[1])
  693. assert_allclose(lsim(s1 * typ(2), U=u, T=t)[1],
  694. lsim(s1, U=u, T=t)[1] * typ(2))
  695. assert_allclose(lsim(s1 / typ(2), U=u, T=t)[1],
  696. lsim(s1, U=u, T=t)[1] / typ(2))
  697. with assert_raises(TypeError):
  698. typ(2) / s1
  699. assert_allclose(lsim(s1 * 2, U=u, T=t)[1],
  700. lsim(s1, U=2 * u, T=t)[1])
  701. assert_allclose(lsim(s1 * s2, U=u, T=t)[1],
  702. lsim(s1, U=lsim(s2, U=u, T=t)[1], T=t)[1],
  703. atol=1e-5)
  704. with assert_raises(TypeError):
  705. s1 / s1
  706. with assert_raises(TypeError):
  707. s1 * s_discrete
  708. with assert_raises(TypeError):
  709. # Check different discretization constants
  710. s_discrete * s2_discrete
  711. with assert_raises(TypeError):
  712. s1 * BadType()
  713. with assert_raises(TypeError):
  714. BadType() * s1
  715. with assert_raises(TypeError):
  716. s1 / BadType()
  717. with assert_raises(TypeError):
  718. BadType() / s1
  719. # Test addition
  720. assert_allclose(lsim(s1 + 2, U=u, T=t)[1],
  721. 2 * u + lsim(s1, U=u, T=t)[1])
  722. # Check for dimension mismatch
  723. with assert_raises(ValueError):
  724. s1 + np.array([1, 2])
  725. with assert_raises(ValueError):
  726. np.array([1, 2]) + s1
  727. with assert_raises(TypeError):
  728. s1 + s_discrete
  729. with assert_raises(ValueError):
  730. s1 / np.array([[1, 2], [3, 4]])
  731. with assert_raises(TypeError):
  732. # Check different discretization constants
  733. s_discrete + s2_discrete
  734. with assert_raises(TypeError):
  735. s1 + BadType()
  736. with assert_raises(TypeError):
  737. BadType() + s1
  738. assert_allclose(lsim(s1 + s2, U=u, T=t)[1],
  739. lsim(s1, U=u, T=t)[1] + lsim(s2, U=u, T=t)[1])
  740. # Test subtraction
  741. assert_allclose(lsim(s1 - 2, U=u, T=t)[1],
  742. -2 * u + lsim(s1, U=u, T=t)[1])
  743. assert_allclose(lsim(2 - s1, U=u, T=t)[1],
  744. 2 * u + lsim(-s1, U=u, T=t)[1])
  745. assert_allclose(lsim(s1 - s2, U=u, T=t)[1],
  746. lsim(s1, U=u, T=t)[1] - lsim(s2, U=u, T=t)[1])
  747. with assert_raises(TypeError):
  748. s1 - BadType()
  749. with assert_raises(TypeError):
  750. BadType() - s1
  751. s = s_discrete + s3_discrete
  752. assert_(s.dt == 0.1)
  753. s = s_discrete * s3_discrete
  754. assert_(s.dt == 0.1)
  755. s = 3 * s_discrete
  756. assert_(s.dt == 0.1)
  757. s = -s_discrete
  758. assert_(s.dt == 0.1)
  759. class TestTransferFunction:
  760. def test_initialization(self):
  761. # Check that all initializations work
  762. TransferFunction(1, 1)
  763. TransferFunction([1], [2])
  764. TransferFunction(np.array([1]), np.array([2]))
  765. def test_conversion(self):
  766. # Check the conversion functions
  767. s = TransferFunction([1, 0], [1, -1])
  768. assert_(isinstance(s.to_ss(), StateSpace))
  769. assert_(isinstance(s.to_tf(), TransferFunction))
  770. assert_(isinstance(s.to_zpk(), ZerosPolesGain))
  771. # Make sure copies work
  772. assert_(TransferFunction(s) is not s)
  773. assert_(s.to_tf() is not s)
  774. def test_properties(self):
  775. # Test setters/getters for cross class properties.
  776. # This implicitly tests to_ss() and to_zpk()
  777. # Getters
  778. s = TransferFunction([1, 0], [1, -1])
  779. assert_equal(s.poles, [1])
  780. assert_equal(s.zeros, [0])
  781. class TestZerosPolesGain:
  782. def test_initialization(self):
  783. # Check that all initializations work
  784. ZerosPolesGain(1, 1, 1)
  785. ZerosPolesGain([1], [2], 1)
  786. ZerosPolesGain(np.array([1]), np.array([2]), 1)
  787. def test_conversion(self):
  788. #Check the conversion functions
  789. s = ZerosPolesGain(1, 2, 3)
  790. assert_(isinstance(s.to_ss(), StateSpace))
  791. assert_(isinstance(s.to_tf(), TransferFunction))
  792. assert_(isinstance(s.to_zpk(), ZerosPolesGain))
  793. # Make sure copies work
  794. assert_(ZerosPolesGain(s) is not s)
  795. assert_(s.to_zpk() is not s)
  796. class Test_abcd_normalize:
  797. def setup_method(self):
  798. self.A = np.array([[1.0, 2.0], [3.0, 4.0]])
  799. self.B = np.array([[-1.0], [5.0]])
  800. self.C = np.array([[4.0, 5.0]])
  801. self.D = np.array([[2.5]])
  802. def test_no_matrix_fails(self):
  803. assert_raises(ValueError, abcd_normalize)
  804. def test_A_nosquare_fails(self):
  805. assert_raises(ValueError, abcd_normalize, [1, -1],
  806. self.B, self.C, self.D)
  807. def test_AB_mismatch_fails(self):
  808. assert_raises(ValueError, abcd_normalize, self.A, [-1, 5],
  809. self.C, self.D)
  810. def test_AC_mismatch_fails(self):
  811. assert_raises(ValueError, abcd_normalize, self.A, self.B,
  812. [[4.0], [5.0]], self.D)
  813. def test_CD_mismatch_fails(self):
  814. assert_raises(ValueError, abcd_normalize, self.A, self.B,
  815. self.C, [2.5, 0])
  816. def test_BD_mismatch_fails(self):
  817. assert_raises(ValueError, abcd_normalize, self.A, [-1, 5],
  818. self.C, self.D)
  819. def test_normalized_matrices_unchanged(self):
  820. A, B, C, D = abcd_normalize(self.A, self.B, self.C, self.D)
  821. assert_equal(A, self.A)
  822. assert_equal(B, self.B)
  823. assert_equal(C, self.C)
  824. assert_equal(D, self.D)
  825. def test_shapes(self):
  826. A, B, C, D = abcd_normalize(self.A, self.B, [1, 0], 0)
  827. assert_equal(A.shape[0], A.shape[1])
  828. assert_equal(A.shape[0], B.shape[0])
  829. assert_equal(A.shape[0], C.shape[1])
  830. assert_equal(C.shape[0], D.shape[0])
  831. assert_equal(B.shape[1], D.shape[1])
  832. def test_zero_dimension_is_not_none1(self):
  833. B_ = np.zeros((2, 0))
  834. D_ = np.zeros((0, 0))
  835. A, B, C, D = abcd_normalize(A=self.A, B=B_, D=D_)
  836. assert_equal(A, self.A)
  837. assert_equal(B, B_)
  838. assert_equal(D, D_)
  839. assert_equal(C.shape[0], D_.shape[0])
  840. assert_equal(C.shape[1], self.A.shape[0])
  841. def test_zero_dimension_is_not_none2(self):
  842. B_ = np.zeros((2, 0))
  843. C_ = np.zeros((0, 2))
  844. A, B, C, D = abcd_normalize(A=self.A, B=B_, C=C_)
  845. assert_equal(A, self.A)
  846. assert_equal(B, B_)
  847. assert_equal(C, C_)
  848. assert_equal(D.shape[0], C_.shape[0])
  849. assert_equal(D.shape[1], B_.shape[1])
  850. def test_missing_A(self):
  851. A, B, C, D = abcd_normalize(B=self.B, C=self.C, D=self.D)
  852. assert_equal(A.shape[0], A.shape[1])
  853. assert_equal(A.shape[0], B.shape[0])
  854. assert_equal(A.shape, (self.B.shape[0], self.B.shape[0]))
  855. def test_missing_B(self):
  856. A, B, C, D = abcd_normalize(A=self.A, C=self.C, D=self.D)
  857. assert_equal(B.shape[0], A.shape[0])
  858. assert_equal(B.shape[1], D.shape[1])
  859. assert_equal(B.shape, (self.A.shape[0], self.D.shape[1]))
  860. def test_missing_C(self):
  861. A, B, C, D = abcd_normalize(A=self.A, B=self.B, D=self.D)
  862. assert_equal(C.shape[0], D.shape[0])
  863. assert_equal(C.shape[1], A.shape[0])
  864. assert_equal(C.shape, (self.D.shape[0], self.A.shape[0]))
  865. def test_missing_D(self):
  866. A, B, C, D = abcd_normalize(A=self.A, B=self.B, C=self.C)
  867. assert_equal(D.shape[0], C.shape[0])
  868. assert_equal(D.shape[1], B.shape[1])
  869. assert_equal(D.shape, (self.C.shape[0], self.B.shape[1]))
  870. def test_missing_AB(self):
  871. A, B, C, D = abcd_normalize(C=self.C, D=self.D)
  872. assert_equal(A.shape[0], A.shape[1])
  873. assert_equal(A.shape[0], B.shape[0])
  874. assert_equal(B.shape[1], D.shape[1])
  875. assert_equal(A.shape, (self.C.shape[1], self.C.shape[1]))
  876. assert_equal(B.shape, (self.C.shape[1], self.D.shape[1]))
  877. def test_missing_AC(self):
  878. A, B, C, D = abcd_normalize(B=self.B, D=self.D)
  879. assert_equal(A.shape[0], A.shape[1])
  880. assert_equal(A.shape[0], B.shape[0])
  881. assert_equal(C.shape[0], D.shape[0])
  882. assert_equal(C.shape[1], A.shape[0])
  883. assert_equal(A.shape, (self.B.shape[0], self.B.shape[0]))
  884. assert_equal(C.shape, (self.D.shape[0], self.B.shape[0]))
  885. def test_missing_AD(self):
  886. A, B, C, D = abcd_normalize(B=self.B, C=self.C)
  887. assert_equal(A.shape[0], A.shape[1])
  888. assert_equal(A.shape[0], B.shape[0])
  889. assert_equal(D.shape[0], C.shape[0])
  890. assert_equal(D.shape[1], B.shape[1])
  891. assert_equal(A.shape, (self.B.shape[0], self.B.shape[0]))
  892. assert_equal(D.shape, (self.C.shape[0], self.B.shape[1]))
  893. def test_missing_BC(self):
  894. A, B, C, D = abcd_normalize(A=self.A, D=self.D)
  895. assert_equal(B.shape[0], A.shape[0])
  896. assert_equal(B.shape[1], D.shape[1])
  897. assert_equal(C.shape[0], D.shape[0])
  898. assert_equal(C.shape[1], A.shape[0])
  899. assert_equal(B.shape, (self.A.shape[0], self.D.shape[1]))
  900. assert_equal(C.shape, (self.D.shape[0], self.A.shape[0]))
  901. def test_missing_ABC_fails(self):
  902. assert_raises(ValueError, abcd_normalize, D=self.D)
  903. def test_missing_BD_fails(self):
  904. assert_raises(ValueError, abcd_normalize, A=self.A, C=self.C)
  905. def test_missing_CD_fails(self):
  906. assert_raises(ValueError, abcd_normalize, A=self.A, B=self.B)
  907. class Test_bode:
  908. def test_01(self):
  909. # Test bode() magnitude calculation (manual sanity check).
  910. # 1st order low-pass filter: H(s) = 1 / (s + 1),
  911. # cutoff: 1 rad/s, slope: -20 dB/decade
  912. # H(s=0.1) ~= 0 dB
  913. # H(s=1) ~= -3 dB
  914. # H(s=10) ~= -20 dB
  915. # H(s=100) ~= -40 dB
  916. system = lti([1], [1, 1])
  917. w = [0.1, 1, 10, 100]
  918. w, mag, phase = bode(system, w=w)
  919. expected_mag = [0, -3, -20, -40]
  920. assert_almost_equal(mag, expected_mag, decimal=1)
  921. def test_02(self):
  922. # Test bode() phase calculation (manual sanity check).
  923. # 1st order low-pass filter: H(s) = 1 / (s + 1),
  924. # angle(H(s=0.1)) ~= -5.7 deg
  925. # angle(H(s=1)) ~= -45 deg
  926. # angle(H(s=10)) ~= -84.3 deg
  927. system = lti([1], [1, 1])
  928. w = [0.1, 1, 10]
  929. w, mag, phase = bode(system, w=w)
  930. expected_phase = [-5.7, -45, -84.3]
  931. assert_almost_equal(phase, expected_phase, decimal=1)
  932. def test_03(self):
  933. # Test bode() magnitude calculation.
  934. # 1st order low-pass filter: H(s) = 1 / (s + 1)
  935. system = lti([1], [1, 1])
  936. w = [0.1, 1, 10, 100]
  937. w, mag, phase = bode(system, w=w)
  938. jw = w * 1j
  939. y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
  940. expected_mag = 20.0 * np.log10(abs(y))
  941. assert_almost_equal(mag, expected_mag)
  942. def test_04(self):
  943. # Test bode() phase calculation.
  944. # 1st order low-pass filter: H(s) = 1 / (s + 1)
  945. system = lti([1], [1, 1])
  946. w = [0.1, 1, 10, 100]
  947. w, mag, phase = bode(system, w=w)
  948. jw = w * 1j
  949. y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
  950. expected_phase = np.arctan2(y.imag, y.real) * 180.0 / np.pi
  951. assert_almost_equal(phase, expected_phase)
  952. def test_05(self):
  953. # Test that bode() finds a reasonable frequency range.
  954. # 1st order low-pass filter: H(s) = 1 / (s + 1)
  955. system = lti([1], [1, 1])
  956. n = 10
  957. # Expected range is from 0.01 to 10.
  958. expected_w = np.logspace(-2, 1, n)
  959. w, mag, phase = bode(system, n=n)
  960. assert_almost_equal(w, expected_w)
  961. def test_06(self):
  962. # Test that bode() doesn't fail on a system with a pole at 0.
  963. # integrator, pole at zero: H(s) = 1 / s
  964. system = lti([1], [1, 0])
  965. w, mag, phase = bode(system, n=2)
  966. assert_equal(w[0], 0.01) # a fail would give not-a-number
  967. def test_07(self):
  968. # bode() should not fail on a system with pure imaginary poles.
  969. # The test passes if bode doesn't raise an exception.
  970. system = lti([1], [1, 0, 100])
  971. w, mag, phase = bode(system, n=2)
  972. def test_08(self):
  973. # Test that bode() return continuous phase, issues/2331.
  974. system = lti([], [-10, -30, -40, -60, -70], 1)
  975. w, mag, phase = system.bode(w=np.logspace(-3, 40, 100))
  976. assert_almost_equal(min(phase), -450, decimal=15)
  977. def test_from_state_space(self):
  978. # Ensure that bode works with a system that was created from the
  979. # state space representation matrices A, B, C, D. In this case,
  980. # system.num will be a 2-D array with shape (1, n+1), where (n,n)
  981. # is the shape of A.
  982. # A Butterworth lowpass filter is used, so we know the exact
  983. # frequency response.
  984. a = np.array([1.0, 2.0, 2.0, 1.0])
  985. A = linalg.companion(a).T
  986. B = np.array([[0.0], [0.0], [1.0]])
  987. C = np.array([[1.0, 0.0, 0.0]])
  988. D = np.array([[0.0]])
  989. with suppress_warnings() as sup:
  990. sup.filter(BadCoefficients)
  991. system = lti(A, B, C, D)
  992. w, mag, phase = bode(system, n=100)
  993. expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6)))
  994. assert_almost_equal(mag, expected_magnitude)
  995. class Test_freqresp:
  996. def test_output_manual(self):
  997. # Test freqresp() output calculation (manual sanity check).
  998. # 1st order low-pass filter: H(s) = 1 / (s + 1),
  999. # re(H(s=0.1)) ~= 0.99
  1000. # re(H(s=1)) ~= 0.5
  1001. # re(H(s=10)) ~= 0.0099
  1002. system = lti([1], [1, 1])
  1003. w = [0.1, 1, 10]
  1004. w, H = freqresp(system, w=w)
  1005. expected_re = [0.99, 0.5, 0.0099]
  1006. expected_im = [-0.099, -0.5, -0.099]
  1007. assert_almost_equal(H.real, expected_re, decimal=1)
  1008. assert_almost_equal(H.imag, expected_im, decimal=1)
  1009. def test_output(self):
  1010. # Test freqresp() output calculation.
  1011. # 1st order low-pass filter: H(s) = 1 / (s + 1)
  1012. system = lti([1], [1, 1])
  1013. w = [0.1, 1, 10, 100]
  1014. w, H = freqresp(system, w=w)
  1015. s = w * 1j
  1016. expected = np.polyval(system.num, s) / np.polyval(system.den, s)
  1017. assert_almost_equal(H.real, expected.real)
  1018. assert_almost_equal(H.imag, expected.imag)
  1019. def test_freq_range(self):
  1020. # Test that freqresp() finds a reasonable frequency range.
  1021. # 1st order low-pass filter: H(s) = 1 / (s + 1)
  1022. # Expected range is from 0.01 to 10.
  1023. system = lti([1], [1, 1])
  1024. n = 10
  1025. expected_w = np.logspace(-2, 1, n)
  1026. w, H = freqresp(system, n=n)
  1027. assert_almost_equal(w, expected_w)
  1028. def test_pole_zero(self):
  1029. # Test that freqresp() doesn't fail on a system with a pole at 0.
  1030. # integrator, pole at zero: H(s) = 1 / s
  1031. system = lti([1], [1, 0])
  1032. w, H = freqresp(system, n=2)
  1033. assert_equal(w[0], 0.01) # a fail would give not-a-number
  1034. def test_from_state_space(self):
  1035. # Ensure that freqresp works with a system that was created from the
  1036. # state space representation matrices A, B, C, D. In this case,
  1037. # system.num will be a 2-D array with shape (1, n+1), where (n,n) is
  1038. # the shape of A.
  1039. # A Butterworth lowpass filter is used, so we know the exact
  1040. # frequency response.
  1041. a = np.array([1.0, 2.0, 2.0, 1.0])
  1042. A = linalg.companion(a).T
  1043. B = np.array([[0.0],[0.0],[1.0]])
  1044. C = np.array([[1.0, 0.0, 0.0]])
  1045. D = np.array([[0.0]])
  1046. with suppress_warnings() as sup:
  1047. sup.filter(BadCoefficients)
  1048. system = lti(A, B, C, D)
  1049. w, H = freqresp(system, n=100)
  1050. s = w * 1j
  1051. expected = (1.0 / (1.0 + 2*s + 2*s**2 + s**3))
  1052. assert_almost_equal(H.real, expected.real)
  1053. assert_almost_equal(H.imag, expected.imag)
  1054. def test_from_zpk(self):
  1055. # 4th order low-pass filter: H(s) = 1 / (s + 1)
  1056. system = lti([],[-1]*4,[1])
  1057. w = [0.1, 1, 10, 100]
  1058. w, H = freqresp(system, w=w)
  1059. s = w * 1j
  1060. expected = 1 / (s + 1)**4
  1061. assert_almost_equal(H.real, expected.real)
  1062. assert_almost_equal(H.imag, expected.imag)