test_ltisys.py 45 KB

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