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.

623 lines
18 KiB

6 months ago
  1. from typing import Type
  2. from sympy.core.add import Add
  3. from sympy.core.assumptions import StdFactKB
  4. from sympy.core.expr import AtomicExpr, Expr
  5. from sympy.core.power import Pow
  6. from sympy.core.singleton import S
  7. from sympy.core.sorting import default_sort_key
  8. from sympy.core.sympify import sympify
  9. from sympy.functions.elementary.miscellaneous import sqrt
  10. from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix
  11. from sympy.vector.basisdependent import (BasisDependentZero,
  12. BasisDependent, BasisDependentMul, BasisDependentAdd)
  13. from sympy.vector.coordsysrect import CoordSys3D
  14. from sympy.vector.dyadic import Dyadic, BaseDyadic, DyadicAdd
  15. class Vector(BasisDependent):
  16. """
  17. Super class for all Vector classes.
  18. Ideally, neither this class nor any of its subclasses should be
  19. instantiated by the user.
  20. """
  21. is_Vector = True
  22. _op_priority = 12.0
  23. _expr_type = None # type: Type[Vector]
  24. _mul_func = None # type: Type[Vector]
  25. _add_func = None # type: Type[Vector]
  26. _zero_func = None # type: Type[Vector]
  27. _base_func = None # type: Type[Vector]
  28. zero = None # type: VectorZero
  29. @property
  30. def components(self):
  31. """
  32. Returns the components of this vector in the form of a
  33. Python dictionary mapping BaseVector instances to the
  34. corresponding measure numbers.
  35. Examples
  36. ========
  37. >>> from sympy.vector import CoordSys3D
  38. >>> C = CoordSys3D('C')
  39. >>> v = 3*C.i + 4*C.j + 5*C.k
  40. >>> v.components
  41. {C.i: 3, C.j: 4, C.k: 5}
  42. """
  43. # The '_components' attribute is defined according to the
  44. # subclass of Vector the instance belongs to.
  45. return self._components
  46. def magnitude(self):
  47. """
  48. Returns the magnitude of this vector.
  49. """
  50. return sqrt(self & self)
  51. def normalize(self):
  52. """
  53. Returns the normalized version of this vector.
  54. """
  55. return self / self.magnitude()
  56. def dot(self, other):
  57. """
  58. Returns the dot product of this Vector, either with another
  59. Vector, or a Dyadic, or a Del operator.
  60. If 'other' is a Vector, returns the dot product scalar (SymPy
  61. expression).
  62. If 'other' is a Dyadic, the dot product is returned as a Vector.
  63. If 'other' is an instance of Del, returns the directional
  64. derivative operator as a Python function. If this function is
  65. applied to a scalar expression, it returns the directional
  66. derivative of the scalar field wrt this Vector.
  67. Parameters
  68. ==========
  69. other: Vector/Dyadic/Del
  70. The Vector or Dyadic we are dotting with, or a Del operator .
  71. Examples
  72. ========
  73. >>> from sympy.vector import CoordSys3D, Del
  74. >>> C = CoordSys3D('C')
  75. >>> delop = Del()
  76. >>> C.i.dot(C.j)
  77. 0
  78. >>> C.i & C.i
  79. 1
  80. >>> v = 3*C.i + 4*C.j + 5*C.k
  81. >>> v.dot(C.k)
  82. 5
  83. >>> (C.i & delop)(C.x*C.y*C.z)
  84. C.y*C.z
  85. >>> d = C.i.outer(C.i)
  86. >>> C.i.dot(d)
  87. C.i
  88. """
  89. # Check special cases
  90. if isinstance(other, Dyadic):
  91. if isinstance(self, VectorZero):
  92. return Vector.zero
  93. outvec = Vector.zero
  94. for k, v in other.components.items():
  95. vect_dot = k.args[0].dot(self)
  96. outvec += vect_dot * v * k.args[1]
  97. return outvec
  98. from sympy.vector.deloperator import Del
  99. if not isinstance(other, (Del, Vector)):
  100. raise TypeError(str(other) + " is not a vector, dyadic or " +
  101. "del operator")
  102. # Check if the other is a del operator
  103. if isinstance(other, Del):
  104. def directional_derivative(field):
  105. from sympy.vector.functions import directional_derivative
  106. return directional_derivative(field, self)
  107. return directional_derivative
  108. return dot(self, other)
  109. def __and__(self, other):
  110. return self.dot(other)
  111. __and__.__doc__ = dot.__doc__
  112. def cross(self, other):
  113. """
  114. Returns the cross product of this Vector with another Vector or
  115. Dyadic instance.
  116. The cross product is a Vector, if 'other' is a Vector. If 'other'
  117. is a Dyadic, this returns a Dyadic instance.
  118. Parameters
  119. ==========
  120. other: Vector/Dyadic
  121. The Vector or Dyadic we are crossing with.
  122. Examples
  123. ========
  124. >>> from sympy.vector import CoordSys3D
  125. >>> C = CoordSys3D('C')
  126. >>> C.i.cross(C.j)
  127. C.k
  128. >>> C.i ^ C.i
  129. 0
  130. >>> v = 3*C.i + 4*C.j + 5*C.k
  131. >>> v ^ C.i
  132. 5*C.j + (-4)*C.k
  133. >>> d = C.i.outer(C.i)
  134. >>> C.j.cross(d)
  135. (-1)*(C.k|C.i)
  136. """
  137. # Check special cases
  138. if isinstance(other, Dyadic):
  139. if isinstance(self, VectorZero):
  140. return Dyadic.zero
  141. outdyad = Dyadic.zero
  142. for k, v in other.components.items():
  143. cross_product = self.cross(k.args[0])
  144. outer = cross_product.outer(k.args[1])
  145. outdyad += v * outer
  146. return outdyad
  147. return cross(self, other)
  148. def __xor__(self, other):
  149. return self.cross(other)
  150. __xor__.__doc__ = cross.__doc__
  151. def outer(self, other):
  152. """
  153. Returns the outer product of this vector with another, in the
  154. form of a Dyadic instance.
  155. Parameters
  156. ==========
  157. other : Vector
  158. The Vector with respect to which the outer product is to
  159. be computed.
  160. Examples
  161. ========
  162. >>> from sympy.vector import CoordSys3D
  163. >>> N = CoordSys3D('N')
  164. >>> N.i.outer(N.j)
  165. (N.i|N.j)
  166. """
  167. # Handle the special cases
  168. if not isinstance(other, Vector):
  169. raise TypeError("Invalid operand for outer product")
  170. elif (isinstance(self, VectorZero) or
  171. isinstance(other, VectorZero)):
  172. return Dyadic.zero
  173. # Iterate over components of both the vectors to generate
  174. # the required Dyadic instance
  175. args = []
  176. for k1, v1 in self.components.items():
  177. for k2, v2 in other.components.items():
  178. args.append((v1 * v2) * BaseDyadic(k1, k2))
  179. return DyadicAdd(*args)
  180. def projection(self, other, scalar=False):
  181. """
  182. Returns the vector or scalar projection of the 'other' on 'self'.
  183. Examples
  184. ========
  185. >>> from sympy.vector.coordsysrect import CoordSys3D
  186. >>> C = CoordSys3D('C')
  187. >>> i, j, k = C.base_vectors()
  188. >>> v1 = i + j + k
  189. >>> v2 = 3*i + 4*j
  190. >>> v1.projection(v2)
  191. 7/3*C.i + 7/3*C.j + 7/3*C.k
  192. >>> v1.projection(v2, scalar=True)
  193. 7/3
  194. """
  195. if self.equals(Vector.zero):
  196. return S.Zero if scalar else Vector.zero
  197. if scalar:
  198. return self.dot(other) / self.dot(self)
  199. else:
  200. return self.dot(other) / self.dot(self) * self
  201. @property
  202. def _projections(self):
  203. """
  204. Returns the components of this vector but the output includes
  205. also zero values components.
  206. Examples
  207. ========
  208. >>> from sympy.vector import CoordSys3D, Vector
  209. >>> C = CoordSys3D('C')
  210. >>> v1 = 3*C.i + 4*C.j + 5*C.k
  211. >>> v1._projections
  212. (3, 4, 5)
  213. >>> v2 = C.x*C.y*C.z*C.i
  214. >>> v2._projections
  215. (C.x*C.y*C.z, 0, 0)
  216. >>> v3 = Vector.zero
  217. >>> v3._projections
  218. (0, 0, 0)
  219. """
  220. from sympy.vector.operators import _get_coord_systems
  221. if isinstance(self, VectorZero):
  222. return (S.Zero, S.Zero, S.Zero)
  223. base_vec = next(iter(_get_coord_systems(self))).base_vectors()
  224. return tuple([self.dot(i) for i in base_vec])
  225. def __or__(self, other):
  226. return self.outer(other)
  227. __or__.__doc__ = outer.__doc__
  228. def to_matrix(self, system):
  229. """
  230. Returns the matrix form of this vector with respect to the
  231. specified coordinate system.
  232. Parameters
  233. ==========
  234. system : CoordSys3D
  235. The system wrt which the matrix form is to be computed
  236. Examples
  237. ========
  238. >>> from sympy.vector import CoordSys3D
  239. >>> C = CoordSys3D('C')
  240. >>> from sympy.abc import a, b, c
  241. >>> v = a*C.i + b*C.j + c*C.k
  242. >>> v.to_matrix(C)
  243. Matrix([
  244. [a],
  245. [b],
  246. [c]])
  247. """
  248. return Matrix([self.dot(unit_vec) for unit_vec in
  249. system.base_vectors()])
  250. def separate(self):
  251. """
  252. The constituents of this vector in different coordinate systems,
  253. as per its definition.
  254. Returns a dict mapping each CoordSys3D to the corresponding
  255. constituent Vector.
  256. Examples
  257. ========
  258. >>> from sympy.vector import CoordSys3D
  259. >>> R1 = CoordSys3D('R1')
  260. >>> R2 = CoordSys3D('R2')
  261. >>> v = R1.i + R2.i
  262. >>> v.separate() == {R1: R1.i, R2: R2.i}
  263. True
  264. """
  265. parts = {}
  266. for vect, measure in self.components.items():
  267. parts[vect.system] = (parts.get(vect.system, Vector.zero) +
  268. vect * measure)
  269. return parts
  270. def _div_helper(one, other):
  271. """ Helper for division involving vectors. """
  272. if isinstance(one, Vector) and isinstance(other, Vector):
  273. raise TypeError("Cannot divide two vectors")
  274. elif isinstance(one, Vector):
  275. if other == S.Zero:
  276. raise ValueError("Cannot divide a vector by zero")
  277. return VectorMul(one, Pow(other, S.NegativeOne))
  278. else:
  279. raise TypeError("Invalid division involving a vector")
  280. class BaseVector(Vector, AtomicExpr):
  281. """
  282. Class to denote a base vector.
  283. """
  284. def __new__(cls, index, system, pretty_str=None, latex_str=None):
  285. if pretty_str is None:
  286. pretty_str = "x{}".format(index)
  287. if latex_str is None:
  288. latex_str = "x_{}".format(index)
  289. pretty_str = str(pretty_str)
  290. latex_str = str(latex_str)
  291. # Verify arguments
  292. if index not in range(0, 3):
  293. raise ValueError("index must be 0, 1 or 2")
  294. if not isinstance(system, CoordSys3D):
  295. raise TypeError("system should be a CoordSys3D")
  296. name = system._vector_names[index]
  297. # Initialize an object
  298. obj = super().__new__(cls, S(index), system)
  299. # Assign important attributes
  300. obj._base_instance = obj
  301. obj._components = {obj: S.One}
  302. obj._measure_number = S.One
  303. obj._name = system._name + '.' + name
  304. obj._pretty_form = '' + pretty_str
  305. obj._latex_form = latex_str
  306. obj._system = system
  307. # The _id is used for printing purposes
  308. obj._id = (index, system)
  309. assumptions = {'commutative': True}
  310. obj._assumptions = StdFactKB(assumptions)
  311. # This attr is used for re-expression to one of the systems
  312. # involved in the definition of the Vector. Applies to
  313. # VectorMul and VectorAdd too.
  314. obj._sys = system
  315. return obj
  316. @property
  317. def system(self):
  318. return self._system
  319. def _sympystr(self, printer):
  320. return self._name
  321. def _sympyrepr(self, printer):
  322. index, system = self._id
  323. return printer._print(system) + '.' + system._vector_names[index]
  324. @property
  325. def free_symbols(self):
  326. return {self}
  327. class VectorAdd(BasisDependentAdd, Vector):
  328. """
  329. Class to denote sum of Vector instances.
  330. """
  331. def __new__(cls, *args, **options):
  332. obj = BasisDependentAdd.__new__(cls, *args, **options)
  333. return obj
  334. def _sympystr(self, printer):
  335. ret_str = ''
  336. items = list(self.separate().items())
  337. items.sort(key=lambda x: x[0].__str__())
  338. for system, vect in items:
  339. base_vects = system.base_vectors()
  340. for x in base_vects:
  341. if x in vect.components:
  342. temp_vect = self.components[x] * x
  343. ret_str += printer._print(temp_vect) + " + "
  344. return ret_str[:-3]
  345. class VectorMul(BasisDependentMul, Vector):
  346. """
  347. Class to denote products of scalars and BaseVectors.
  348. """
  349. def __new__(cls, *args, **options):
  350. obj = BasisDependentMul.__new__(cls, *args, **options)
  351. return obj
  352. @property
  353. def base_vector(self):
  354. """ The BaseVector involved in the product. """
  355. return self._base_instance
  356. @property
  357. def measure_number(self):
  358. """ The scalar expression involved in the definition of
  359. this VectorMul.
  360. """
  361. return self._measure_number
  362. class VectorZero(BasisDependentZero, Vector):
  363. """
  364. Class to denote a zero vector
  365. """
  366. _op_priority = 12.1
  367. _pretty_form = '0'
  368. _latex_form = r'\mathbf{\hat{0}}'
  369. def __new__(cls):
  370. obj = BasisDependentZero.__new__(cls)
  371. return obj
  372. class Cross(Vector):
  373. """
  374. Represents unevaluated Cross product.
  375. Examples
  376. ========
  377. >>> from sympy.vector import CoordSys3D, Cross
  378. >>> R = CoordSys3D('R')
  379. >>> v1 = R.i + R.j + R.k
  380. >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k
  381. >>> Cross(v1, v2)
  382. Cross(R.i + R.j + R.k, R.x*R.i + R.y*R.j + R.z*R.k)
  383. >>> Cross(v1, v2).doit()
  384. (-R.y + R.z)*R.i + (R.x - R.z)*R.j + (-R.x + R.y)*R.k
  385. """
  386. def __new__(cls, expr1, expr2):
  387. expr1 = sympify(expr1)
  388. expr2 = sympify(expr2)
  389. if default_sort_key(expr1) > default_sort_key(expr2):
  390. return -Cross(expr2, expr1)
  391. obj = Expr.__new__(cls, expr1, expr2)
  392. obj._expr1 = expr1
  393. obj._expr2 = expr2
  394. return obj
  395. def doit(self, **kwargs):
  396. return cross(self._expr1, self._expr2)
  397. class Dot(Expr):
  398. """
  399. Represents unevaluated Dot product.
  400. Examples
  401. ========
  402. >>> from sympy.vector import CoordSys3D, Dot
  403. >>> from sympy import symbols
  404. >>> R = CoordSys3D('R')
  405. >>> a, b, c = symbols('a b c')
  406. >>> v1 = R.i + R.j + R.k
  407. >>> v2 = a * R.i + b * R.j + c * R.k
  408. >>> Dot(v1, v2)
  409. Dot(R.i + R.j + R.k, a*R.i + b*R.j + c*R.k)
  410. >>> Dot(v1, v2).doit()
  411. a + b + c
  412. """
  413. def __new__(cls, expr1, expr2):
  414. expr1 = sympify(expr1)
  415. expr2 = sympify(expr2)
  416. expr1, expr2 = sorted([expr1, expr2], key=default_sort_key)
  417. obj = Expr.__new__(cls, expr1, expr2)
  418. obj._expr1 = expr1
  419. obj._expr2 = expr2
  420. return obj
  421. def doit(self, **kwargs):
  422. return dot(self._expr1, self._expr2)
  423. def cross(vect1, vect2):
  424. """
  425. Returns cross product of two vectors.
  426. Examples
  427. ========
  428. >>> from sympy.vector import CoordSys3D
  429. >>> from sympy.vector.vector import cross
  430. >>> R = CoordSys3D('R')
  431. >>> v1 = R.i + R.j + R.k
  432. >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k
  433. >>> cross(v1, v2)
  434. (-R.y + R.z)*R.i + (R.x - R.z)*R.j + (-R.x + R.y)*R.k
  435. """
  436. if isinstance(vect1, Add):
  437. return VectorAdd.fromiter(cross(i, vect2) for i in vect1.args)
  438. if isinstance(vect2, Add):
  439. return VectorAdd.fromiter(cross(vect1, i) for i in vect2.args)
  440. if isinstance(vect1, BaseVector) and isinstance(vect2, BaseVector):
  441. if vect1._sys == vect2._sys:
  442. n1 = vect1.args[0]
  443. n2 = vect2.args[0]
  444. if n1 == n2:
  445. return Vector.zero
  446. n3 = ({0,1,2}.difference({n1, n2})).pop()
  447. sign = 1 if ((n1 + 1) % 3 == n2) else -1
  448. return sign*vect1._sys.base_vectors()[n3]
  449. from .functions import express
  450. try:
  451. v = express(vect1, vect2._sys)
  452. except ValueError:
  453. return Cross(vect1, vect2)
  454. else:
  455. return cross(v, vect2)
  456. if isinstance(vect1, VectorZero) or isinstance(vect2, VectorZero):
  457. return Vector.zero
  458. if isinstance(vect1, VectorMul):
  459. v1, m1 = next(iter(vect1.components.items()))
  460. return m1*cross(v1, vect2)
  461. if isinstance(vect2, VectorMul):
  462. v2, m2 = next(iter(vect2.components.items()))
  463. return m2*cross(vect1, v2)
  464. return Cross(vect1, vect2)
  465. def dot(vect1, vect2):
  466. """
  467. Returns dot product of two vectors.
  468. Examples
  469. ========
  470. >>> from sympy.vector import CoordSys3D
  471. >>> from sympy.vector.vector import dot
  472. >>> R = CoordSys3D('R')
  473. >>> v1 = R.i + R.j + R.k
  474. >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k
  475. >>> dot(v1, v2)
  476. R.x + R.y + R.z
  477. """
  478. if isinstance(vect1, Add):
  479. return Add.fromiter(dot(i, vect2) for i in vect1.args)
  480. if isinstance(vect2, Add):
  481. return Add.fromiter(dot(vect1, i) for i in vect2.args)
  482. if isinstance(vect1, BaseVector) and isinstance(vect2, BaseVector):
  483. if vect1._sys == vect2._sys:
  484. return S.One if vect1 == vect2 else S.Zero
  485. from .functions import express
  486. try:
  487. v = express(vect2, vect1._sys)
  488. except ValueError:
  489. return Dot(vect1, vect2)
  490. else:
  491. return dot(vect1, v)
  492. if isinstance(vect1, VectorZero) or isinstance(vect2, VectorZero):
  493. return S.Zero
  494. if isinstance(vect1, VectorMul):
  495. v1, m1 = next(iter(vect1.components.items()))
  496. return m1*dot(v1, vect2)
  497. if isinstance(vect2, VectorMul):
  498. v2, m2 = next(iter(vect2.components.items()))
  499. return m2*dot(vect1, v2)
  500. return Dot(vect1, vect2)
  501. Vector._expr_type = Vector
  502. Vector._mul_func = VectorMul
  503. Vector._add_func = VectorAdd
  504. Vector._zero_func = VectorZero
  505. Vector._base_func = BaseVector
  506. Vector.zero = VectorZero()