prefixes.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """
  2. Module defining unit prefixe class and some constants.
  3. Constant dict for SI and binary prefixes are defined as PREFIXES and
  4. BIN_PREFIXES.
  5. """
  6. from sympy.core.expr import Expr
  7. from sympy.core.sympify import sympify
  8. from sympy.core.singleton import S
  9. class Prefix(Expr):
  10. """
  11. This class represent prefixes, with their name, symbol and factor.
  12. Prefixes are used to create derived units from a given unit. They should
  13. always be encapsulated into units.
  14. The factor is constructed from a base (default is 10) to some power, and
  15. it gives the total multiple or fraction. For example the kilometer km
  16. is constructed from the meter (factor 1) and the kilo (10 to the power 3,
  17. i.e. 1000). The base can be changed to allow e.g. binary prefixes.
  18. A prefix multiplied by something will always return the product of this
  19. other object times the factor, except if the other object:
  20. - is a prefix and they can be combined into a new prefix;
  21. - defines multiplication with prefixes (which is the case for the Unit
  22. class).
  23. """
  24. _op_priority = 13.0
  25. is_commutative = True
  26. def __new__(cls, name, abbrev, exponent, base=sympify(10), latex_repr=None):
  27. name = sympify(name)
  28. abbrev = sympify(abbrev)
  29. exponent = sympify(exponent)
  30. base = sympify(base)
  31. obj = Expr.__new__(cls, name, abbrev, exponent, base)
  32. obj._name = name
  33. obj._abbrev = abbrev
  34. obj._scale_factor = base**exponent
  35. obj._exponent = exponent
  36. obj._base = base
  37. obj._latex_repr = latex_repr
  38. return obj
  39. @property
  40. def name(self):
  41. return self._name
  42. @property
  43. def abbrev(self):
  44. return self._abbrev
  45. @property
  46. def scale_factor(self):
  47. return self._scale_factor
  48. def _latex(self, printer):
  49. if self._latex_repr is None:
  50. return r'\text{%s}' % self._abbrev
  51. return self._latex_repr
  52. @property
  53. def base(self):
  54. return self._base
  55. def __str__(self):
  56. return str(self._abbrev)
  57. def __repr__(self):
  58. if self.base == 10:
  59. return "Prefix(%r, %r, %r)" % (
  60. str(self.name), str(self.abbrev), self._exponent)
  61. else:
  62. return "Prefix(%r, %r, %r, %r)" % (
  63. str(self.name), str(self.abbrev), self._exponent, self.base)
  64. def __mul__(self, other):
  65. from sympy.physics.units import Quantity
  66. if not isinstance(other, (Quantity, Prefix)):
  67. return super().__mul__(other)
  68. fact = self.scale_factor * other.scale_factor
  69. if isinstance(other, Prefix):
  70. if fact == 1:
  71. return S.One
  72. # simplify prefix
  73. for p in PREFIXES:
  74. if PREFIXES[p].scale_factor == fact:
  75. return PREFIXES[p]
  76. return fact
  77. return self.scale_factor * other
  78. def __truediv__(self, other):
  79. if not hasattr(other, "scale_factor"):
  80. return super().__truediv__(other)
  81. fact = self.scale_factor / other.scale_factor
  82. if fact == 1:
  83. return S.One
  84. elif isinstance(other, Prefix):
  85. for p in PREFIXES:
  86. if PREFIXES[p].scale_factor == fact:
  87. return PREFIXES[p]
  88. return fact
  89. return self.scale_factor / other
  90. def __rtruediv__(self, other):
  91. if other == 1:
  92. for p in PREFIXES:
  93. if PREFIXES[p].scale_factor == 1 / self.scale_factor:
  94. return PREFIXES[p]
  95. return other / self.scale_factor
  96. def prefix_unit(unit, prefixes):
  97. """
  98. Return a list of all units formed by unit and the given prefixes.
  99. You can use the predefined PREFIXES or BIN_PREFIXES, but you can also
  100. pass as argument a subdict of them if you do not want all prefixed units.
  101. >>> from sympy.physics.units.prefixes import (PREFIXES,
  102. ... prefix_unit)
  103. >>> from sympy.physics.units import m
  104. >>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
  105. >>> prefix_unit(m, pref) # doctest: +SKIP
  106. [millimeter, centimeter, decimeter]
  107. """
  108. from sympy.physics.units.quantities import Quantity
  109. from sympy.physics.units import UnitSystem
  110. prefixed_units = []
  111. for prefix in prefixes.values():
  112. quantity = Quantity(
  113. "%s%s" % (prefix.name, unit.name),
  114. abbrev=("%s%s" % (prefix.abbrev, unit.abbrev)),
  115. is_prefixed=True,
  116. )
  117. UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit
  118. UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit)
  119. prefixed_units.append(quantity)
  120. return prefixed_units
  121. yotta = Prefix('yotta', 'Y', 24)
  122. zetta = Prefix('zetta', 'Z', 21)
  123. exa = Prefix('exa', 'E', 18)
  124. peta = Prefix('peta', 'P', 15)
  125. tera = Prefix('tera', 'T', 12)
  126. giga = Prefix('giga', 'G', 9)
  127. mega = Prefix('mega', 'M', 6)
  128. kilo = Prefix('kilo', 'k', 3)
  129. hecto = Prefix('hecto', 'h', 2)
  130. deca = Prefix('deca', 'da', 1)
  131. deci = Prefix('deci', 'd', -1)
  132. centi = Prefix('centi', 'c', -2)
  133. milli = Prefix('milli', 'm', -3)
  134. micro = Prefix('micro', 'mu', -6, latex_repr=r"\mu")
  135. nano = Prefix('nano', 'n', -9)
  136. pico = Prefix('pico', 'p', -12)
  137. femto = Prefix('femto', 'f', -15)
  138. atto = Prefix('atto', 'a', -18)
  139. zepto = Prefix('zepto', 'z', -21)
  140. yocto = Prefix('yocto', 'y', -24)
  141. # https://physics.nist.gov/cuu/Units/prefixes.html
  142. PREFIXES = {
  143. 'Y': yotta,
  144. 'Z': zetta,
  145. 'E': exa,
  146. 'P': peta,
  147. 'T': tera,
  148. 'G': giga,
  149. 'M': mega,
  150. 'k': kilo,
  151. 'h': hecto,
  152. 'da': deca,
  153. 'd': deci,
  154. 'c': centi,
  155. 'm': milli,
  156. 'mu': micro,
  157. 'n': nano,
  158. 'p': pico,
  159. 'f': femto,
  160. 'a': atto,
  161. 'z': zepto,
  162. 'y': yocto,
  163. }
  164. kibi = Prefix('kibi', 'Y', 10, 2)
  165. mebi = Prefix('mebi', 'Y', 20, 2)
  166. gibi = Prefix('gibi', 'Y', 30, 2)
  167. tebi = Prefix('tebi', 'Y', 40, 2)
  168. pebi = Prefix('pebi', 'Y', 50, 2)
  169. exbi = Prefix('exbi', 'Y', 60, 2)
  170. # https://physics.nist.gov/cuu/Units/binary.html
  171. BIN_PREFIXES = {
  172. 'Ki': kibi,
  173. 'Mi': mebi,
  174. 'Gi': gibi,
  175. 'Ti': tebi,
  176. 'Pi': pebi,
  177. 'Ei': exbi,
  178. }