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