vector.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. from sympy import (S, sympify, expand, sqrt, Add, zeros, acos,
  2. ImmutableMatrix as Matrix, simplify)
  3. from sympy.simplify.trigsimp import trigsimp
  4. from sympy.printing.defaults import Printable
  5. from sympy.utilities.misc import filldedent
  6. from sympy.core.evalf import EvalfMixin
  7. from mpmath.libmp.libmpf import prec_to_dps
  8. __all__ = ['Vector']
  9. class Vector(Printable, EvalfMixin):
  10. """The class used to define vectors.
  11. It along with ReferenceFrame are the building blocks of describing a
  12. classical mechanics system in PyDy and sympy.physics.vector.
  13. Attributes
  14. ==========
  15. simp : Boolean
  16. Let certain methods use trigsimp on their outputs
  17. """
  18. simp = False
  19. is_number = False
  20. def __init__(self, inlist):
  21. """This is the constructor for the Vector class. You should not be
  22. calling this, it should only be used by other functions. You should be
  23. treating Vectors like you would with if you were doing the math by
  24. hand, and getting the first 3 from the standard basis vectors from a
  25. ReferenceFrame.
  26. The only exception is to create a zero vector:
  27. zv = Vector(0)
  28. """
  29. self.args = []
  30. if inlist == 0:
  31. inlist = []
  32. if isinstance(inlist, dict):
  33. d = inlist
  34. else:
  35. d = {}
  36. for inp in inlist:
  37. if inp[1] in d:
  38. d[inp[1]] += inp[0]
  39. else:
  40. d[inp[1]] = inp[0]
  41. for k, v in d.items():
  42. if v != Matrix([0, 0, 0]):
  43. self.args.append((v, k))
  44. @property
  45. def func(self):
  46. """Returns the class Vector. """
  47. return Vector
  48. def __hash__(self):
  49. return hash(tuple(self.args))
  50. def __add__(self, other):
  51. """The add operator for Vector. """
  52. if other == 0:
  53. return self
  54. other = _check_vector(other)
  55. return Vector(self.args + other.args)
  56. def dot(self, other):
  57. """Dot product of two vectors.
  58. Returns a scalar, the dot product of the two Vectors
  59. Parameters
  60. ==========
  61. other : Vector
  62. The Vector which we are dotting with
  63. Examples
  64. ========
  65. >>> from sympy.physics.vector import ReferenceFrame, dot
  66. >>> from sympy import symbols
  67. >>> q1 = symbols('q1')
  68. >>> N = ReferenceFrame('N')
  69. >>> dot(N.x, N.x)
  70. 1
  71. >>> dot(N.x, N.y)
  72. 0
  73. >>> A = N.orientnew('A', 'Axis', [q1, N.x])
  74. >>> dot(N.y, A.y)
  75. cos(q1)
  76. """
  77. from sympy.physics.vector.dyadic import Dyadic, _check_dyadic
  78. if isinstance(other, Dyadic):
  79. other = _check_dyadic(other)
  80. ol = Vector(0)
  81. for v in other.args:
  82. ol += v[0] * v[2] * (v[1].dot(self))
  83. return ol
  84. other = _check_vector(other)
  85. out = S.Zero
  86. for v1 in self.args:
  87. for v2 in other.args:
  88. out += ((v2[0].T) * (v2[1].dcm(v1[1])) * (v1[0]))[0]
  89. if Vector.simp:
  90. return trigsimp(out, recursive=True)
  91. else:
  92. return out
  93. def __truediv__(self, other):
  94. """This uses mul and inputs self and 1 divided by other. """
  95. return self.__mul__(S.One / other)
  96. def __eq__(self, other):
  97. """Tests for equality.
  98. It is very import to note that this is only as good as the SymPy
  99. equality test; False does not always mean they are not equivalent
  100. Vectors.
  101. If other is 0, and self is empty, returns True.
  102. If other is 0 and self is not empty, returns False.
  103. If none of the above, only accepts other as a Vector.
  104. """
  105. if other == 0:
  106. other = Vector(0)
  107. try:
  108. other = _check_vector(other)
  109. except TypeError:
  110. return False
  111. if (self.args == []) and (other.args == []):
  112. return True
  113. elif (self.args == []) or (other.args == []):
  114. return False
  115. frame = self.args[0][1]
  116. for v in frame:
  117. if expand((self - other).dot(v)) != 0:
  118. return False
  119. return True
  120. def __mul__(self, other):
  121. """Multiplies the Vector by a sympifyable expression.
  122. Parameters
  123. ==========
  124. other : Sympifyable
  125. The scalar to multiply this Vector with
  126. Examples
  127. ========
  128. >>> from sympy.physics.vector import ReferenceFrame
  129. >>> from sympy import Symbol
  130. >>> N = ReferenceFrame('N')
  131. >>> b = Symbol('b')
  132. >>> V = 10 * b * N.x
  133. >>> print(V)
  134. 10*b*N.x
  135. """
  136. newlist = list(self.args)
  137. other = sympify(other)
  138. for i in range(len(newlist)):
  139. newlist[i] = (other * newlist[i][0], newlist[i][1])
  140. return Vector(newlist)
  141. def __neg__(self):
  142. return self * -1
  143. def outer(self, other):
  144. """Outer product between two Vectors.
  145. A rank increasing operation, which returns a Dyadic from two Vectors
  146. Parameters
  147. ==========
  148. other : Vector
  149. The Vector to take the outer product with
  150. Examples
  151. ========
  152. >>> from sympy.physics.vector import ReferenceFrame, outer
  153. >>> N = ReferenceFrame('N')
  154. >>> outer(N.x, N.x)
  155. (N.x|N.x)
  156. """
  157. from sympy.physics.vector.dyadic import Dyadic
  158. other = _check_vector(other)
  159. ol = Dyadic(0)
  160. for v in self.args:
  161. for v2 in other.args:
  162. # it looks this way because if we are in the same frame and
  163. # use the enumerate function on the same frame in a nested
  164. # fashion, then bad things happen
  165. ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
  166. ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
  167. ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
  168. ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
  169. ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
  170. ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
  171. ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
  172. ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
  173. ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
  174. return ol
  175. def _latex(self, printer):
  176. """Latex Printing method. """
  177. ar = self.args # just to shorten things
  178. if len(ar) == 0:
  179. return str(0)
  180. ol = [] # output list, to be concatenated to a string
  181. for v in ar:
  182. for j in 0, 1, 2:
  183. # if the coef of the basis vector is 1, we skip the 1
  184. if v[0][j] == 1:
  185. ol.append(' + ' + v[1].latex_vecs[j])
  186. # if the coef of the basis vector is -1, we skip the 1
  187. elif v[0][j] == -1:
  188. ol.append(' - ' + v[1].latex_vecs[j])
  189. elif v[0][j] != 0:
  190. # If the coefficient of the basis vector is not 1 or -1;
  191. # also, we might wrap it in parentheses, for readability.
  192. arg_str = printer._print(v[0][j])
  193. if isinstance(v[0][j], Add):
  194. arg_str = "(%s)" % arg_str
  195. if arg_str[0] == '-':
  196. arg_str = arg_str[1:]
  197. str_start = ' - '
  198. else:
  199. str_start = ' + '
  200. ol.append(str_start + arg_str + v[1].latex_vecs[j])
  201. outstr = ''.join(ol)
  202. if outstr.startswith(' + '):
  203. outstr = outstr[3:]
  204. elif outstr.startswith(' '):
  205. outstr = outstr[1:]
  206. return outstr
  207. def _pretty(self, printer):
  208. """Pretty Printing method. """
  209. from sympy.printing.pretty.stringpict import prettyForm
  210. terms = []
  211. def juxtapose(a, b):
  212. pa = printer._print(a)
  213. pb = printer._print(b)
  214. if a.is_Add:
  215. pa = prettyForm(*pa.parens())
  216. return printer._print_seq([pa, pb], delimiter=' ')
  217. for M, N in self.args:
  218. for i in range(3):
  219. if M[i] == 0:
  220. continue
  221. elif M[i] == 1:
  222. terms.append(prettyForm(N.pretty_vecs[i]))
  223. elif M[i] == -1:
  224. terms.append(prettyForm("-1") * prettyForm(N.pretty_vecs[i]))
  225. else:
  226. terms.append(juxtapose(M[i], N.pretty_vecs[i]))
  227. if terms:
  228. pretty_result = prettyForm.__add__(*terms)
  229. else:
  230. pretty_result = prettyForm("0")
  231. return pretty_result
  232. def __rsub__(self, other):
  233. return (-1 * self) + other
  234. def _sympystr(self, printer, order=True):
  235. """Printing method. """
  236. if not order or len(self.args) == 1:
  237. ar = list(self.args)
  238. elif len(self.args) == 0:
  239. return printer._print(0)
  240. else:
  241. d = {v[1]: v[0] for v in self.args}
  242. keys = sorted(d.keys(), key=lambda x: x.index)
  243. ar = []
  244. for key in keys:
  245. ar.append((d[key], key))
  246. ol = [] # output list, to be concatenated to a string
  247. for v in ar:
  248. for j in 0, 1, 2:
  249. # if the coef of the basis vector is 1, we skip the 1
  250. if v[0][j] == 1:
  251. ol.append(' + ' + v[1].str_vecs[j])
  252. # if the coef of the basis vector is -1, we skip the 1
  253. elif v[0][j] == -1:
  254. ol.append(' - ' + v[1].str_vecs[j])
  255. elif v[0][j] != 0:
  256. # If the coefficient of the basis vector is not 1 or -1;
  257. # also, we might wrap it in parentheses, for readability.
  258. arg_str = printer._print(v[0][j])
  259. if isinstance(v[0][j], Add):
  260. arg_str = "(%s)" % arg_str
  261. if arg_str[0] == '-':
  262. arg_str = arg_str[1:]
  263. str_start = ' - '
  264. else:
  265. str_start = ' + '
  266. ol.append(str_start + arg_str + '*' + v[1].str_vecs[j])
  267. outstr = ''.join(ol)
  268. if outstr.startswith(' + '):
  269. outstr = outstr[3:]
  270. elif outstr.startswith(' '):
  271. outstr = outstr[1:]
  272. return outstr
  273. def __sub__(self, other):
  274. """The subtraction operator. """
  275. return self.__add__(other * -1)
  276. def cross(self, other):
  277. """The cross product operator for two Vectors.
  278. Returns a Vector, expressed in the same ReferenceFrames as self.
  279. Parameters
  280. ==========
  281. other : Vector
  282. The Vector which we are crossing with
  283. Examples
  284. ========
  285. >>> from sympy import symbols
  286. >>> from sympy.physics.vector import ReferenceFrame, cross
  287. >>> q1 = symbols('q1')
  288. >>> N = ReferenceFrame('N')
  289. >>> cross(N.x, N.y)
  290. N.z
  291. >>> A = ReferenceFrame('A')
  292. >>> A.orient_axis(N, q1, N.x)
  293. >>> cross(A.x, N.y)
  294. N.z
  295. >>> cross(N.y, A.x)
  296. - sin(q1)*A.y - cos(q1)*A.z
  297. """
  298. from sympy.physics.vector.dyadic import Dyadic, _check_dyadic
  299. if isinstance(other, Dyadic):
  300. other = _check_dyadic(other)
  301. ol = Dyadic(0)
  302. for i, v in enumerate(other.args):
  303. ol += v[0] * ((self.cross(v[1])).outer(v[2]))
  304. return ol
  305. other = _check_vector(other)
  306. if other.args == []:
  307. return Vector(0)
  308. def _det(mat):
  309. """This is needed as a little method for to find the determinant
  310. of a list in python; needs to work for a 3x3 list.
  311. SymPy's Matrix will not take in Vector, so need a custom function.
  312. You should not be calling this.
  313. """
  314. return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1])
  315. + mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] *
  316. mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] -
  317. mat[1][1] * mat[2][0]))
  318. outlist = []
  319. ar = other.args # For brevity
  320. for v in ar:
  321. tempx = v[1].x
  322. tempy = v[1].y
  323. tempz = v[1].z
  324. tempm = ([[tempx, tempy, tempz],
  325. [self.dot(tempx), self.dot(tempy), self.dot(tempz)],
  326. [Vector([v]).dot(tempx), Vector([v]).dot(tempy),
  327. Vector([v]).dot(tempz)]])
  328. outlist += _det(tempm).args
  329. return Vector(outlist)
  330. __radd__ = __add__
  331. __rmul__ = __mul__
  332. def separate(self):
  333. """
  334. The constituents of this vector in different reference frames,
  335. as per its definition.
  336. Returns a dict mapping each ReferenceFrame to the corresponding
  337. constituent Vector.
  338. Examples
  339. ========
  340. >>> from sympy.physics.vector import ReferenceFrame
  341. >>> R1 = ReferenceFrame('R1')
  342. >>> R2 = ReferenceFrame('R2')
  343. >>> v = R1.x + R2.x
  344. >>> v.separate() == {R1: R1.x, R2: R2.x}
  345. True
  346. """
  347. components = {}
  348. for x in self.args:
  349. components[x[1]] = Vector([x])
  350. return components
  351. def __and__(self, other):
  352. return self.dot(other)
  353. __and__.__doc__ = dot.__doc__
  354. __rand__ = __and__
  355. def __xor__(self, other):
  356. return self.cross(other)
  357. __xor__.__doc__ = cross.__doc__
  358. def __or__(self, other):
  359. return self.outer(other)
  360. __or__.__doc__ = outer.__doc__
  361. def diff(self, var, frame, var_in_dcm=True):
  362. """Returns the partial derivative of the vector with respect to a
  363. variable in the provided reference frame.
  364. Parameters
  365. ==========
  366. var : Symbol
  367. What the partial derivative is taken with respect to.
  368. frame : ReferenceFrame
  369. The reference frame that the partial derivative is taken in.
  370. var_in_dcm : boolean
  371. If true, the differentiation algorithm assumes that the variable
  372. may be present in any of the direction cosine matrices that relate
  373. the frame to the frames of any component of the vector. But if it
  374. is known that the variable is not present in the direction cosine
  375. matrices, false can be set to skip full reexpression in the desired
  376. frame.
  377. Examples
  378. ========
  379. >>> from sympy import Symbol
  380. >>> from sympy.physics.vector import dynamicsymbols, ReferenceFrame
  381. >>> from sympy.physics.vector import init_vprinting
  382. >>> init_vprinting(pretty_print=False)
  383. >>> t = Symbol('t')
  384. >>> q1 = dynamicsymbols('q1')
  385. >>> N = ReferenceFrame('N')
  386. >>> A = N.orientnew('A', 'Axis', [q1, N.y])
  387. >>> A.x.diff(t, N)
  388. - sin(q1)*q1'*N.x - cos(q1)*q1'*N.z
  389. >>> A.x.diff(t, N).express(A).simplify()
  390. - q1'*A.z
  391. >>> B = ReferenceFrame('B')
  392. >>> u1, u2 = dynamicsymbols('u1, u2')
  393. >>> v = u1 * A.x + u2 * B.y
  394. >>> v.diff(u2, N, var_in_dcm=False)
  395. B.y
  396. """
  397. from sympy.physics.vector.frame import _check_frame
  398. _check_frame(frame)
  399. var = sympify(var)
  400. inlist = []
  401. for vector_component in self.args:
  402. measure_number = vector_component[0]
  403. component_frame = vector_component[1]
  404. if component_frame == frame:
  405. inlist += [(measure_number.diff(var), frame)]
  406. else:
  407. # If the direction cosine matrix relating the component frame
  408. # with the derivative frame does not contain the variable.
  409. if not var_in_dcm or (frame.dcm(component_frame).diff(var) ==
  410. zeros(3, 3)):
  411. inlist += [(measure_number.diff(var), component_frame)]
  412. else: # else express in the frame
  413. reexp_vec_comp = Vector([vector_component]).express(frame)
  414. deriv = reexp_vec_comp.args[0][0].diff(var)
  415. inlist += Vector([(deriv, frame)]).args
  416. return Vector(inlist)
  417. def express(self, otherframe, variables=False):
  418. """
  419. Returns a Vector equivalent to this one, expressed in otherframe.
  420. Uses the global express method.
  421. Parameters
  422. ==========
  423. otherframe : ReferenceFrame
  424. The frame for this Vector to be described in
  425. variables : boolean
  426. If True, the coordinate symbols(if present) in this Vector
  427. are re-expressed in terms otherframe
  428. Examples
  429. ========
  430. >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
  431. >>> from sympy.physics.vector import init_vprinting
  432. >>> init_vprinting(pretty_print=False)
  433. >>> q1 = dynamicsymbols('q1')
  434. >>> N = ReferenceFrame('N')
  435. >>> A = N.orientnew('A', 'Axis', [q1, N.y])
  436. >>> A.x.express(N)
  437. cos(q1)*N.x - sin(q1)*N.z
  438. """
  439. from sympy.physics.vector import express
  440. return express(self, otherframe, variables=variables)
  441. def to_matrix(self, reference_frame):
  442. """Returns the matrix form of the vector with respect to the given
  443. frame.
  444. Parameters
  445. ----------
  446. reference_frame : ReferenceFrame
  447. The reference frame that the rows of the matrix correspond to.
  448. Returns
  449. -------
  450. matrix : ImmutableMatrix, shape(3,1)
  451. The matrix that gives the 1D vector.
  452. Examples
  453. ========
  454. >>> from sympy import symbols
  455. >>> from sympy.physics.vector import ReferenceFrame
  456. >>> a, b, c = symbols('a, b, c')
  457. >>> N = ReferenceFrame('N')
  458. >>> vector = a * N.x + b * N.y + c * N.z
  459. >>> vector.to_matrix(N)
  460. Matrix([
  461. [a],
  462. [b],
  463. [c]])
  464. >>> beta = symbols('beta')
  465. >>> A = N.orientnew('A', 'Axis', (beta, N.x))
  466. >>> vector.to_matrix(A)
  467. Matrix([
  468. [ a],
  469. [ b*cos(beta) + c*sin(beta)],
  470. [-b*sin(beta) + c*cos(beta)]])
  471. """
  472. return Matrix([self.dot(unit_vec) for unit_vec in
  473. reference_frame]).reshape(3, 1)
  474. def doit(self, **hints):
  475. """Calls .doit() on each term in the Vector"""
  476. d = {}
  477. for v in self.args:
  478. d[v[1]] = v[0].applyfunc(lambda x: x.doit(**hints))
  479. return Vector(d)
  480. def dt(self, otherframe):
  481. """
  482. Returns a Vector which is the time derivative of
  483. the self Vector, taken in frame otherframe.
  484. Calls the global time_derivative method
  485. Parameters
  486. ==========
  487. otherframe : ReferenceFrame
  488. The frame to calculate the time derivative in
  489. """
  490. from sympy.physics.vector import time_derivative
  491. return time_derivative(self, otherframe)
  492. def simplify(self):
  493. """Returns a simplified Vector."""
  494. d = {}
  495. for v in self.args:
  496. d[v[1]] = simplify(v[0])
  497. return Vector(d)
  498. def subs(self, *args, **kwargs):
  499. """Substitution on the Vector.
  500. Examples
  501. ========
  502. >>> from sympy.physics.vector import ReferenceFrame
  503. >>> from sympy import Symbol
  504. >>> N = ReferenceFrame('N')
  505. >>> s = Symbol('s')
  506. >>> a = N.x * s
  507. >>> a.subs({s: 2})
  508. 2*N.x
  509. """
  510. d = {}
  511. for v in self.args:
  512. d[v[1]] = v[0].subs(*args, **kwargs)
  513. return Vector(d)
  514. def magnitude(self):
  515. """Returns the magnitude (Euclidean norm) of self.
  516. Warnings
  517. ========
  518. Python ignores the leading negative sign so that might
  519. give wrong results.
  520. ``-A.x.magnitude()`` would be treated as ``-(A.x.magnitude())``,
  521. instead of ``(-A.x).magnitude()``.
  522. """
  523. return sqrt(self.dot(self))
  524. def normalize(self):
  525. """Returns a Vector of magnitude 1, codirectional with self."""
  526. return Vector(self.args + []) / self.magnitude()
  527. def applyfunc(self, f):
  528. """Apply a function to each component of a vector."""
  529. if not callable(f):
  530. raise TypeError("`f` must be callable.")
  531. d = {}
  532. for v in self.args:
  533. d[v[1]] = v[0].applyfunc(f)
  534. return Vector(d)
  535. def angle_between(self, vec):
  536. """
  537. Returns the smallest angle between Vector 'vec' and self.
  538. Parameter
  539. =========
  540. vec : Vector
  541. The Vector between which angle is needed.
  542. Examples
  543. ========
  544. >>> from sympy.physics.vector import ReferenceFrame
  545. >>> A = ReferenceFrame("A")
  546. >>> v1 = A.x
  547. >>> v2 = A.y
  548. >>> v1.angle_between(v2)
  549. pi/2
  550. >>> v3 = A.x + A.y + A.z
  551. >>> v1.angle_between(v3)
  552. acos(sqrt(3)/3)
  553. Warnings
  554. ========
  555. Python ignores the leading negative sign so that might give wrong
  556. results. ``-A.x.angle_between()`` would be treated as
  557. ``-(A.x.angle_between())``, instead of ``(-A.x).angle_between()``.
  558. """
  559. vec1 = self.normalize()
  560. vec2 = vec.normalize()
  561. angle = acos(vec1.dot(vec2))
  562. return angle
  563. def free_symbols(self, reference_frame):
  564. """Returns the free symbols in the measure numbers of the vector
  565. expressed in the given reference frame.
  566. Parameters
  567. ==========
  568. reference_frame : ReferenceFrame
  569. The frame with respect to which the free symbols of the given
  570. vector is to be determined.
  571. Returns
  572. =======
  573. set of Symbol
  574. set of symbols present in the measure numbers of
  575. ``reference_frame``.
  576. """
  577. return self.to_matrix(reference_frame).free_symbols
  578. def free_dynamicsymbols(self, reference_frame):
  579. """Returns the free dynamic symbols (functions of time ``t``) in the
  580. measure numbers of the vector expressed in the given reference frame.
  581. Parameters
  582. ==========
  583. reference_frame : ReferenceFrame
  584. The frame with respect to which the free dynamic symbols of the
  585. given vector is to be determined.
  586. Returns
  587. =======
  588. set
  589. Set of functions of time ``t``, e.g.
  590. ``Function('f')(me.dynamicsymbols._t)``.
  591. """
  592. # TODO : Circular dependency if imported at top. Should move
  593. # find_dynamicsymbols into physics.vector.functions.
  594. from sympy.physics.mechanics.functions import find_dynamicsymbols
  595. return find_dynamicsymbols(self, reference_frame=reference_frame)
  596. def _eval_evalf(self, prec):
  597. if not self.args:
  598. return self
  599. new_args = []
  600. dps = prec_to_dps(prec)
  601. for mat, frame in self.args:
  602. new_args.append([mat.evalf(n=dps), frame])
  603. return Vector(new_args)
  604. def xreplace(self, rule):
  605. """Replace occurrences of objects within the measure numbers of the
  606. vector.
  607. Parameters
  608. ==========
  609. rule : dict-like
  610. Expresses a replacement rule.
  611. Returns
  612. =======
  613. Vector
  614. Result of the replacement.
  615. Examples
  616. ========
  617. >>> from sympy import symbols, pi
  618. >>> from sympy.physics.vector import ReferenceFrame
  619. >>> A = ReferenceFrame('A')
  620. >>> x, y, z = symbols('x y z')
  621. >>> ((1 + x*y) * A.x).xreplace({x: pi})
  622. (pi*y + 1)*A.x
  623. >>> ((1 + x*y) * A.x).xreplace({x: pi, y: 2})
  624. (1 + 2*pi)*A.x
  625. Replacements occur only if an entire node in the expression tree is
  626. matched:
  627. >>> ((x*y + z) * A.x).xreplace({x*y: pi})
  628. (z + pi)*A.x
  629. >>> ((x*y*z) * A.x).xreplace({x*y: pi})
  630. x*y*z*A.x
  631. """
  632. new_args = []
  633. for mat, frame in self.args:
  634. mat = mat.xreplace(rule)
  635. new_args.append([mat, frame])
  636. return Vector(new_args)
  637. class VectorTypeError(TypeError):
  638. def __init__(self, other, want):
  639. msg = filldedent("Expected an instance of %s, but received object "
  640. "'%s' of %s." % (type(want), other, type(other)))
  641. super().__init__(msg)
  642. def _check_vector(other):
  643. if not isinstance(other, Vector):
  644. raise TypeError('A Vector must be supplied')
  645. return other