scalar.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from sympy.core import AtomicExpr, Symbol, S
  2. from sympy.core.sympify import _sympify
  3. from sympy.printing.pretty.stringpict import prettyForm
  4. from sympy.printing.precedence import PRECEDENCE
  5. class BaseScalar(AtomicExpr):
  6. """
  7. A coordinate symbol/base scalar.
  8. Ideally, users should not instantiate this class.
  9. """
  10. def __new__(cls, index, system, pretty_str=None, latex_str=None):
  11. from sympy.vector.coordsysrect import CoordSys3D
  12. if pretty_str is None:
  13. pretty_str = "x{}".format(index)
  14. elif isinstance(pretty_str, Symbol):
  15. pretty_str = pretty_str.name
  16. if latex_str is None:
  17. latex_str = "x_{}".format(index)
  18. elif isinstance(latex_str, Symbol):
  19. latex_str = latex_str.name
  20. index = _sympify(index)
  21. system = _sympify(system)
  22. obj = super().__new__(cls, index, system)
  23. if not isinstance(system, CoordSys3D):
  24. raise TypeError("system should be a CoordSys3D")
  25. if index not in range(0, 3):
  26. raise ValueError("Invalid index specified.")
  27. # The _id is used for equating purposes, and for hashing
  28. obj._id = (index, system)
  29. obj._name = obj.name = system._name + '.' + system._variable_names[index]
  30. obj._pretty_form = '' + pretty_str
  31. obj._latex_form = latex_str
  32. obj._system = system
  33. return obj
  34. is_commutative = True
  35. is_symbol = True
  36. @property
  37. def free_symbols(self):
  38. return {self}
  39. _diff_wrt = True
  40. def _eval_derivative(self, s):
  41. if self == s:
  42. return S.One
  43. return S.Zero
  44. def _latex(self, printer=None):
  45. return self._latex_form
  46. def _pretty(self, printer=None):
  47. return prettyForm(self._pretty_form)
  48. precedence = PRECEDENCE['Atom']
  49. @property
  50. def system(self):
  51. return self._system
  52. def _sympystr(self, printer):
  53. return self._name