linearize.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. __all__ = ['Linearizer']
  2. from sympy.core.backend import Matrix, eye, zeros
  3. from sympy.core.symbol import Dummy
  4. from sympy.utilities.iterables import flatten
  5. from sympy.physics.vector import dynamicsymbols
  6. from sympy.physics.mechanics.functions import msubs
  7. from collections import namedtuple
  8. from collections.abc import Iterable
  9. class Linearizer:
  10. """This object holds the general model form for a dynamic system.
  11. This model is used for computing the linearized form of the system,
  12. while properly dealing with constraints leading to dependent
  13. coordinates and speeds.
  14. Attributes
  15. ==========
  16. f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
  17. Matrices holding the general system form.
  18. q, u, r : Matrix
  19. Matrices holding the generalized coordinates, speeds, and
  20. input vectors.
  21. q_i, u_i : Matrix
  22. Matrices of the independent generalized coordinates and speeds.
  23. q_d, u_d : Matrix
  24. Matrices of the dependent generalized coordinates and speeds.
  25. perm_mat : Matrix
  26. Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
  27. """
  28. def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u,
  29. q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None):
  30. """
  31. Parameters
  32. ==========
  33. f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
  34. System of equations holding the general system form.
  35. Supply empty array or Matrix if the parameter
  36. doesn't exist.
  37. q : array_like
  38. The generalized coordinates.
  39. u : array_like
  40. The generalized speeds
  41. q_i, u_i : array_like, optional
  42. The independent generalized coordinates and speeds.
  43. q_d, u_d : array_like, optional
  44. The dependent generalized coordinates and speeds.
  45. r : array_like, optional
  46. The input variables.
  47. lams : array_like, optional
  48. The lagrange multipliers
  49. """
  50. # Generalized equation form
  51. self.f_0 = Matrix(f_0)
  52. self.f_1 = Matrix(f_1)
  53. self.f_2 = Matrix(f_2)
  54. self.f_3 = Matrix(f_3)
  55. self.f_4 = Matrix(f_4)
  56. self.f_c = Matrix(f_c)
  57. self.f_v = Matrix(f_v)
  58. self.f_a = Matrix(f_a)
  59. # Generalized equation variables
  60. self.q = Matrix(q)
  61. self.u = Matrix(u)
  62. none_handler = lambda x: Matrix(x) if x else Matrix()
  63. self.q_i = none_handler(q_i)
  64. self.q_d = none_handler(q_d)
  65. self.u_i = none_handler(u_i)
  66. self.u_d = none_handler(u_d)
  67. self.r = none_handler(r)
  68. self.lams = none_handler(lams)
  69. # Derivatives of generalized equation variables
  70. self._qd = self.q.diff(dynamicsymbols._t)
  71. self._ud = self.u.diff(dynamicsymbols._t)
  72. # If the user doesn't actually use generalized variables, and the
  73. # qd and u vectors have any intersecting variables, this can cause
  74. # problems. We'll fix this with some hackery, and Dummy variables
  75. dup_vars = set(self._qd).intersection(self.u)
  76. self._qd_dup = Matrix([var if var not in dup_vars else Dummy()
  77. for var in self._qd])
  78. # Derive dimesion terms
  79. l = len(self.f_c)
  80. m = len(self.f_v)
  81. n = len(self.q)
  82. o = len(self.u)
  83. s = len(self.r)
  84. k = len(self.lams)
  85. dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
  86. self._dims = dims(l, m, n, o, s, k)
  87. self._Pq = None
  88. self._Pqi = None
  89. self._Pqd = None
  90. self._Pu = None
  91. self._Pui = None
  92. self._Pud = None
  93. self._C_0 = None
  94. self._C_1 = None
  95. self._C_2 = None
  96. self.perm_mat = None
  97. self._setup_done = False
  98. def _setup(self):
  99. # Calculations here only need to be run once. They are moved out of
  100. # the __init__ method to increase the speed of Linearizer creation.
  101. self._form_permutation_matrices()
  102. self._form_block_matrices()
  103. self._form_coefficient_matrices()
  104. self._setup_done = True
  105. def _form_permutation_matrices(self):
  106. """Form the permutation matrices Pq and Pu."""
  107. # Extract dimension variables
  108. l, m, n, o, s, k = self._dims
  109. # Compute permutation matrices
  110. if n != 0:
  111. self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
  112. if l > 0:
  113. self._Pqi = self._Pq[:, :-l]
  114. self._Pqd = self._Pq[:, -l:]
  115. else:
  116. self._Pqi = self._Pq
  117. self._Pqd = Matrix()
  118. if o != 0:
  119. self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
  120. if m > 0:
  121. self._Pui = self._Pu[:, :-m]
  122. self._Pud = self._Pu[:, -m:]
  123. else:
  124. self._Pui = self._Pu
  125. self._Pud = Matrix()
  126. # Compute combination permutation matrix for computing A and B
  127. P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
  128. P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
  129. if P_col1:
  130. if P_col2:
  131. self.perm_mat = P_col1.row_join(P_col2)
  132. else:
  133. self.perm_mat = P_col1
  134. else:
  135. self.perm_mat = P_col2
  136. def _form_coefficient_matrices(self):
  137. """Form the coefficient matrices C_0, C_1, and C_2."""
  138. # Extract dimension variables
  139. l, m, n, o, s, k = self._dims
  140. # Build up the coefficient matrices C_0, C_1, and C_2
  141. # If there are configuration constraints (l > 0), form C_0 as normal.
  142. # If not, C_0 is I_(nxn). Note that this works even if n=0
  143. if l > 0:
  144. f_c_jac_q = self.f_c.jacobian(self.q)
  145. self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q *
  146. self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi
  147. else:
  148. self._C_0 = eye(n)
  149. # If there are motion constraints (m > 0), form C_1 and C_2 as normal.
  150. # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
  151. # o = 0.
  152. if m > 0:
  153. f_v_jac_u = self.f_v.jacobian(self.u)
  154. temp = f_v_jac_u * self._Pud
  155. if n != 0:
  156. f_v_jac_q = self.f_v.jacobian(self.q)
  157. self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q)
  158. else:
  159. self._C_1 = zeros(o, n)
  160. self._C_2 = (eye(o) - self._Pud *
  161. temp.LUsolve(f_v_jac_u)) * self._Pui
  162. else:
  163. self._C_1 = zeros(o, n)
  164. self._C_2 = eye(o)
  165. def _form_block_matrices(self):
  166. """Form the block matrices for composing M, A, and B."""
  167. # Extract dimension variables
  168. l, m, n, o, s, k = self._dims
  169. # Block Matrix Definitions. These are only defined if under certain
  170. # conditions. If undefined, an empty matrix is used instead
  171. if n != 0:
  172. self._M_qq = self.f_0.jacobian(self._qd)
  173. self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
  174. else:
  175. self._M_qq = Matrix()
  176. self._A_qq = Matrix()
  177. if n != 0 and m != 0:
  178. self._M_uqc = self.f_a.jacobian(self._qd_dup)
  179. self._A_uqc = -self.f_a.jacobian(self.q)
  180. else:
  181. self._M_uqc = Matrix()
  182. self._A_uqc = Matrix()
  183. if n != 0 and o - m + k != 0:
  184. self._M_uqd = self.f_3.jacobian(self._qd_dup)
  185. self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
  186. else:
  187. self._M_uqd = Matrix()
  188. self._A_uqd = Matrix()
  189. if o != 0 and m != 0:
  190. self._M_uuc = self.f_a.jacobian(self._ud)
  191. self._A_uuc = -self.f_a.jacobian(self.u)
  192. else:
  193. self._M_uuc = Matrix()
  194. self._A_uuc = Matrix()
  195. if o != 0 and o - m + k != 0:
  196. self._M_uud = self.f_2.jacobian(self._ud)
  197. self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
  198. else:
  199. self._M_uud = Matrix()
  200. self._A_uud = Matrix()
  201. if o != 0 and n != 0:
  202. self._A_qu = -self.f_1.jacobian(self.u)
  203. else:
  204. self._A_qu = Matrix()
  205. if k != 0 and o - m + k != 0:
  206. self._M_uld = self.f_4.jacobian(self.lams)
  207. else:
  208. self._M_uld = Matrix()
  209. if s != 0 and o - m + k != 0:
  210. self._B_u = -self.f_3.jacobian(self.r)
  211. else:
  212. self._B_u = Matrix()
  213. def linearize(self, op_point=None, A_and_B=False, simplify=False):
  214. """Linearize the system about the operating point. Note that
  215. q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
  216. These may be either symbolic or numeric.
  217. Parameters
  218. ==========
  219. op_point : dict or iterable of dicts, optional
  220. Dictionary or iterable of dictionaries containing the operating
  221. point conditions. These will be substituted in to the linearized
  222. system before the linearization is complete. Leave blank if you
  223. want a completely symbolic form. Note that any reduction in
  224. symbols (whether substituted for numbers or expressions with a
  225. common parameter) will result in faster runtime.
  226. A_and_B : bool, optional
  227. If A_and_B=False (default), (M, A, B) is returned for forming
  228. [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True,
  229. (A, B) is returned for forming dx = [A]x + [B]r, where
  230. x = [q_ind, u_ind]^T.
  231. simplify : bool, optional
  232. Determines if returned values are simplified before return.
  233. For large expressions this may be time consuming. Default is False.
  234. Potential Issues
  235. ================
  236. Note that the process of solving with A_and_B=True is
  237. computationally intensive if there are many symbolic parameters.
  238. For this reason, it may be more desirable to use the default
  239. A_and_B=False, returning M, A, and B. More values may then be
  240. substituted in to these matrices later on. The state space form can
  241. then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where
  242. P = Linearizer.perm_mat.
  243. """
  244. # Run the setup if needed:
  245. if not self._setup_done:
  246. self._setup()
  247. # Compose dict of operating conditions
  248. if isinstance(op_point, dict):
  249. op_point_dict = op_point
  250. elif isinstance(op_point, Iterable):
  251. op_point_dict = {}
  252. for op in op_point:
  253. op_point_dict.update(op)
  254. else:
  255. op_point_dict = {}
  256. # Extract dimension variables
  257. l, m, n, o, s, k = self._dims
  258. # Rename terms to shorten expressions
  259. M_qq = self._M_qq
  260. M_uqc = self._M_uqc
  261. M_uqd = self._M_uqd
  262. M_uuc = self._M_uuc
  263. M_uud = self._M_uud
  264. M_uld = self._M_uld
  265. A_qq = self._A_qq
  266. A_uqc = self._A_uqc
  267. A_uqd = self._A_uqd
  268. A_qu = self._A_qu
  269. A_uuc = self._A_uuc
  270. A_uud = self._A_uud
  271. B_u = self._B_u
  272. C_0 = self._C_0
  273. C_1 = self._C_1
  274. C_2 = self._C_2
  275. # Build up Mass Matrix
  276. # |M_qq 0_nxo 0_nxk|
  277. # M = |M_uqc M_uuc 0_mxk|
  278. # |M_uqd M_uud M_uld|
  279. if o != 0:
  280. col2 = Matrix([zeros(n, o), M_uuc, M_uud])
  281. if k != 0:
  282. col3 = Matrix([zeros(n + m, k), M_uld])
  283. if n != 0:
  284. col1 = Matrix([M_qq, M_uqc, M_uqd])
  285. if o != 0 and k != 0:
  286. M = col1.row_join(col2).row_join(col3)
  287. elif o != 0:
  288. M = col1.row_join(col2)
  289. else:
  290. M = col1
  291. elif k != 0:
  292. M = col2.row_join(col3)
  293. else:
  294. M = col2
  295. M_eq = msubs(M, op_point_dict)
  296. # Build up state coefficient matrix A
  297. # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
  298. # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
  299. # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
  300. # Col 1 is only defined if n != 0
  301. if n != 0:
  302. r1c1 = A_qq
  303. if o != 0:
  304. r1c1 += (A_qu * C_1)
  305. r1c1 = r1c1 * C_0
  306. if m != 0:
  307. r2c1 = A_uqc
  308. if o != 0:
  309. r2c1 += (A_uuc * C_1)
  310. r2c1 = r2c1 * C_0
  311. else:
  312. r2c1 = Matrix()
  313. if o - m + k != 0:
  314. r3c1 = A_uqd
  315. if o != 0:
  316. r3c1 += (A_uud * C_1)
  317. r3c1 = r3c1 * C_0
  318. else:
  319. r3c1 = Matrix()
  320. col1 = Matrix([r1c1, r2c1, r3c1])
  321. else:
  322. col1 = Matrix()
  323. # Col 2 is only defined if o != 0
  324. if o != 0:
  325. if n != 0:
  326. r1c2 = A_qu * C_2
  327. else:
  328. r1c2 = Matrix()
  329. if m != 0:
  330. r2c2 = A_uuc * C_2
  331. else:
  332. r2c2 = Matrix()
  333. if o - m + k != 0:
  334. r3c2 = A_uud * C_2
  335. else:
  336. r3c2 = Matrix()
  337. col2 = Matrix([r1c2, r2c2, r3c2])
  338. else:
  339. col2 = Matrix()
  340. if col1:
  341. if col2:
  342. Amat = col1.row_join(col2)
  343. else:
  344. Amat = col1
  345. else:
  346. Amat = col2
  347. Amat_eq = msubs(Amat, op_point_dict)
  348. # Build up the B matrix if there are forcing variables
  349. # |0_(n + m)xs|
  350. # B = |B_u |
  351. if s != 0 and o - m + k != 0:
  352. Bmat = zeros(n + m, s).col_join(B_u)
  353. Bmat_eq = msubs(Bmat, op_point_dict)
  354. else:
  355. Bmat_eq = Matrix()
  356. # kwarg A_and_B indicates to return A, B for forming the equation
  357. # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
  358. if A_and_B:
  359. A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq)
  360. if Bmat_eq:
  361. B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq)
  362. else:
  363. # Bmat = Matrix([]), so no need to sub
  364. B_cont = Bmat_eq
  365. if simplify:
  366. A_cont.simplify()
  367. B_cont.simplify()
  368. return A_cont, B_cont
  369. # Otherwise return M, A, B for forming the equation
  370. # [M]dx = [A]x + [B]r, where x = [q, u]^T
  371. else:
  372. if simplify:
  373. M_eq.simplify()
  374. Amat_eq.simplify()
  375. Bmat_eq.simplify()
  376. return M_eq, Amat_eq, Bmat_eq
  377. def permutation_matrix(orig_vec, per_vec):
  378. """Compute the permutation matrix to change order of
  379. orig_vec into order of per_vec.
  380. Parameters
  381. ==========
  382. orig_vec : array_like
  383. Symbols in original ordering.
  384. per_vec : array_like
  385. Symbols in new ordering.
  386. Returns
  387. =======
  388. p_matrix : Matrix
  389. Permutation matrix such that orig_vec == (p_matrix * per_vec).
  390. """
  391. if not isinstance(orig_vec, (list, tuple)):
  392. orig_vec = flatten(orig_vec)
  393. if not isinstance(per_vec, (list, tuple)):
  394. per_vec = flatten(per_vec)
  395. if set(orig_vec) != set(per_vec):
  396. raise ValueError("orig_vec and per_vec must be the same length, " +
  397. "and contain the same symbols.")
  398. ind_list = [orig_vec.index(i) for i in per_vec]
  399. p_matrix = zeros(len(orig_vec))
  400. for i, j in enumerate(ind_list):
  401. p_matrix[i, j] = 1
  402. return p_matrix