m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

830 lines
26 KiB

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