test_ltisys.py 45 KB

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