dimensions.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. """
  2. Definition of physical dimensions.
  3. Unit systems will be constructed on top of these dimensions.
  4. Most of the examples in the doc use MKS system and are presented from the
  5. computer point of view: from a human point, adding length to time is not legal
  6. in MKS but it is in natural system; for a computer in natural system there is
  7. no time dimension (but a velocity dimension instead) - in the basis - so the
  8. question of adding time to length has no meaning.
  9. """
  10. from typing import Dict as tDict
  11. import collections
  12. from functools import reduce
  13. from sympy.core.basic import Basic
  14. from sympy.core.containers import (Dict, Tuple)
  15. from sympy.core.singleton import S
  16. from sympy.core.sorting import default_sort_key
  17. from sympy.core.symbol import Symbol
  18. from sympy.core.sympify import sympify
  19. from sympy.matrices.dense import Matrix
  20. from sympy.functions.elementary.trigonometric import TrigonometricFunction
  21. from sympy.core.expr import Expr
  22. from sympy.core.power import Pow
  23. class _QuantityMapper:
  24. _quantity_scale_factors_global = {} # type: tDict[Expr, Expr]
  25. _quantity_dimensional_equivalence_map_global = {} # type: tDict[Expr, Expr]
  26. _quantity_dimension_global = {} # type: tDict[Expr, Expr]
  27. def __init__(self, *args, **kwargs):
  28. self._quantity_dimension_map = {}
  29. self._quantity_scale_factors = {}
  30. def set_quantity_dimension(self, unit, dimension):
  31. from sympy.physics.units import Quantity
  32. dimension = sympify(dimension)
  33. if not isinstance(dimension, Dimension):
  34. if dimension == 1:
  35. dimension = Dimension(1)
  36. else:
  37. raise ValueError("expected dimension or 1")
  38. elif isinstance(dimension, Quantity):
  39. dimension = self.get_quantity_dimension(dimension)
  40. self._quantity_dimension_map[unit] = dimension
  41. def set_quantity_scale_factor(self, unit, scale_factor):
  42. from sympy.physics.units import Quantity
  43. from sympy.physics.units.prefixes import Prefix
  44. scale_factor = sympify(scale_factor)
  45. # replace all prefixes by their ratio to canonical units:
  46. scale_factor = scale_factor.replace(
  47. lambda x: isinstance(x, Prefix),
  48. lambda x: x.scale_factor
  49. )
  50. # replace all quantities by their ratio to canonical units:
  51. scale_factor = scale_factor.replace(
  52. lambda x: isinstance(x, Quantity),
  53. lambda x: self.get_quantity_scale_factor(x)
  54. )
  55. self._quantity_scale_factors[unit] = scale_factor
  56. def get_quantity_dimension(self, unit):
  57. from sympy.physics.units import Quantity
  58. # First look-up the local dimension map, then the global one:
  59. if unit in self._quantity_dimension_map:
  60. return self._quantity_dimension_map[unit]
  61. if unit in self._quantity_dimension_global:
  62. return self._quantity_dimension_global[unit]
  63. if unit in self._quantity_dimensional_equivalence_map_global:
  64. dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
  65. if isinstance(dep_unit, Quantity):
  66. return self.get_quantity_dimension(dep_unit)
  67. else:
  68. return Dimension(self.get_dimensional_expr(dep_unit))
  69. if isinstance(unit, Quantity):
  70. return Dimension(unit.name)
  71. else:
  72. return Dimension(1)
  73. def get_quantity_scale_factor(self, unit):
  74. if unit in self._quantity_scale_factors:
  75. return self._quantity_scale_factors[unit]
  76. if unit in self._quantity_scale_factors_global:
  77. mul_factor, other_unit = self._quantity_scale_factors_global[unit]
  78. return mul_factor*self.get_quantity_scale_factor(other_unit)
  79. return S.One
  80. class Dimension(Expr):
  81. """
  82. This class represent the dimension of a physical quantities.
  83. The ``Dimension`` constructor takes as parameters a name and an optional
  84. symbol.
  85. For example, in classical mechanics we know that time is different from
  86. temperature and dimensions make this difference (but they do not provide
  87. any measure of these quantites.
  88. >>> from sympy.physics.units import Dimension
  89. >>> length = Dimension('length')
  90. >>> length
  91. Dimension(length)
  92. >>> time = Dimension('time')
  93. >>> time
  94. Dimension(time)
  95. Dimensions can be composed using multiplication, division and
  96. exponentiation (by a number) to give new dimensions. Addition and
  97. subtraction is defined only when the two objects are the same dimension.
  98. >>> velocity = length / time
  99. >>> velocity
  100. Dimension(length/time)
  101. It is possible to use a dimension system object to get the dimensionsal
  102. dependencies of a dimension, for example the dimension system used by the
  103. SI units convention can be used:
  104. >>> from sympy.physics.units.systems.si import dimsys_SI
  105. >>> dimsys_SI.get_dimensional_dependencies(velocity)
  106. {'length': 1, 'time': -1}
  107. >>> length + length
  108. Dimension(length)
  109. >>> l2 = length**2
  110. >>> l2
  111. Dimension(length**2)
  112. >>> dimsys_SI.get_dimensional_dependencies(l2)
  113. {'length': 2}
  114. """
  115. _op_priority = 13.0
  116. # XXX: This doesn't seem to be used anywhere...
  117. _dimensional_dependencies = dict() # type: ignore
  118. is_commutative = True
  119. is_number = False
  120. # make sqrt(M**2) --> M
  121. is_positive = True
  122. is_real = True
  123. def __new__(cls, name, symbol=None):
  124. if isinstance(name, str):
  125. name = Symbol(name)
  126. else:
  127. name = sympify(name)
  128. if not isinstance(name, Expr):
  129. raise TypeError("Dimension name needs to be a valid math expression")
  130. if isinstance(symbol, str):
  131. symbol = Symbol(symbol)
  132. elif symbol is not None:
  133. assert isinstance(symbol, Symbol)
  134. if symbol is not None:
  135. obj = Expr.__new__(cls, name, symbol)
  136. else:
  137. obj = Expr.__new__(cls, name)
  138. obj._name = name
  139. obj._symbol = symbol
  140. return obj
  141. @property
  142. def name(self):
  143. return self._name
  144. @property
  145. def symbol(self):
  146. return self._symbol
  147. def __hash__(self):
  148. return Expr.__hash__(self)
  149. def __eq__(self, other):
  150. if isinstance(other, Dimension):
  151. return self.name == other.name
  152. return False
  153. def __str__(self):
  154. """
  155. Display the string representation of the dimension.
  156. """
  157. if self.symbol is None:
  158. return "Dimension(%s)" % (self.name)
  159. else:
  160. return "Dimension(%s, %s)" % (self.name, self.symbol)
  161. def __repr__(self):
  162. return self.__str__()
  163. def __neg__(self):
  164. return self
  165. def __add__(self, other):
  166. from sympy.physics.units.quantities import Quantity
  167. other = sympify(other)
  168. if isinstance(other, Basic):
  169. if other.has(Quantity):
  170. raise TypeError("cannot sum dimension and quantity")
  171. if isinstance(other, Dimension) and self == other:
  172. return self
  173. return super().__add__(other)
  174. return self
  175. def __radd__(self, other):
  176. return self.__add__(other)
  177. def __sub__(self, other):
  178. # there is no notion of ordering (or magnitude) among dimension,
  179. # subtraction is equivalent to addition when the operation is legal
  180. return self + other
  181. def __rsub__(self, other):
  182. # there is no notion of ordering (or magnitude) among dimension,
  183. # subtraction is equivalent to addition when the operation is legal
  184. return self + other
  185. def __pow__(self, other):
  186. return self._eval_power(other)
  187. def _eval_power(self, other):
  188. other = sympify(other)
  189. return Dimension(self.name**other)
  190. def __mul__(self, other):
  191. from sympy.physics.units.quantities import Quantity
  192. if isinstance(other, Basic):
  193. if other.has(Quantity):
  194. raise TypeError("cannot sum dimension and quantity")
  195. if isinstance(other, Dimension):
  196. return Dimension(self.name*other.name)
  197. if not other.free_symbols: # other.is_number cannot be used
  198. return self
  199. return super().__mul__(other)
  200. return self
  201. def __rmul__(self, other):
  202. return self.__mul__(other)
  203. def __truediv__(self, other):
  204. return self*Pow(other, -1)
  205. def __rtruediv__(self, other):
  206. return other * pow(self, -1)
  207. @classmethod
  208. def _from_dimensional_dependencies(cls, dependencies):
  209. return reduce(lambda x, y: x * y, (
  210. Dimension(d)**e for d, e in dependencies.items()
  211. ), 1)
  212. def has_integer_powers(self, dim_sys):
  213. """
  214. Check if the dimension object has only integer powers.
  215. All the dimension powers should be integers, but rational powers may
  216. appear in intermediate steps. This method may be used to check that the
  217. final result is well-defined.
  218. """
  219. return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
  220. # Create dimensions according to the base units in MKSA.
  221. # For other unit systems, they can be derived by transforming the base
  222. # dimensional dependency dictionary.
  223. class DimensionSystem(Basic, _QuantityMapper):
  224. r"""
  225. DimensionSystem represents a coherent set of dimensions.
  226. The constructor takes three parameters:
  227. - base dimensions;
  228. - derived dimensions: these are defined in terms of the base dimensions
  229. (for example velocity is defined from the division of length by time);
  230. - dependency of dimensions: how the derived dimensions depend
  231. on the base dimensions.
  232. Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
  233. may be omitted.
  234. """
  235. def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}):
  236. dimensional_dependencies = dict(dimensional_dependencies)
  237. def parse_dim(dim):
  238. if isinstance(dim, str):
  239. dim = Dimension(Symbol(dim))
  240. elif isinstance(dim, Dimension):
  241. pass
  242. elif isinstance(dim, Symbol):
  243. dim = Dimension(dim)
  244. else:
  245. raise TypeError("%s wrong type" % dim)
  246. return dim
  247. base_dims = [parse_dim(i) for i in base_dims]
  248. derived_dims = [parse_dim(i) for i in derived_dims]
  249. for dim in base_dims:
  250. dim = dim.name
  251. if (dim in dimensional_dependencies
  252. and (len(dimensional_dependencies[dim]) != 1 or
  253. dimensional_dependencies[dim].get(dim, None) != 1)):
  254. raise IndexError("Repeated value in base dimensions")
  255. dimensional_dependencies[dim] = Dict({dim: 1})
  256. def parse_dim_name(dim):
  257. if isinstance(dim, Dimension):
  258. return dim.name
  259. elif isinstance(dim, str):
  260. return Symbol(dim)
  261. elif isinstance(dim, Symbol):
  262. return dim
  263. else:
  264. raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
  265. for dim in dimensional_dependencies.keys():
  266. dim = parse_dim(dim)
  267. if (dim not in derived_dims) and (dim not in base_dims):
  268. derived_dims.append(dim)
  269. def parse_dict(d):
  270. return Dict({parse_dim_name(i): j for i, j in d.items()})
  271. # Make sure everything is a SymPy type:
  272. dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
  273. dimensional_dependencies.items()}
  274. for dim in derived_dims:
  275. if dim in base_dims:
  276. raise ValueError("Dimension %s both in base and derived" % dim)
  277. if dim.name not in dimensional_dependencies:
  278. # TODO: should this raise a warning?
  279. dimensional_dependencies[dim.name] = Dict({dim.name: 1})
  280. base_dims.sort(key=default_sort_key)
  281. derived_dims.sort(key=default_sort_key)
  282. base_dims = Tuple(*base_dims)
  283. derived_dims = Tuple(*derived_dims)
  284. dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
  285. obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
  286. return obj
  287. @property
  288. def base_dims(self):
  289. return self.args[0]
  290. @property
  291. def derived_dims(self):
  292. return self.args[1]
  293. @property
  294. def dimensional_dependencies(self):
  295. return self.args[2]
  296. def _get_dimensional_dependencies_for_name(self, name):
  297. if isinstance(name, Dimension):
  298. name = name.name
  299. if isinstance(name, str):
  300. name = Symbol(name)
  301. if name.is_Symbol:
  302. # Dimensions not included in the dependencies are considered
  303. # as base dimensions:
  304. return dict(self.dimensional_dependencies.get(name, {name: 1}))
  305. if name.is_number or name.is_NumberSymbol:
  306. return {}
  307. get_for_name = self._get_dimensional_dependencies_for_name
  308. if name.is_Mul:
  309. ret = collections.defaultdict(int)
  310. dicts = [get_for_name(i) for i in name.args]
  311. for d in dicts:
  312. for k, v in d.items():
  313. ret[k] += v
  314. return {k: v for (k, v) in ret.items() if v != 0}
  315. if name.is_Add:
  316. dicts = [get_for_name(i) for i in name.args]
  317. if all(d == dicts[0] for d in dicts[1:]):
  318. return dicts[0]
  319. raise TypeError("Only equivalent dimensions can be added or subtracted.")
  320. if name.is_Pow:
  321. dim_base = get_for_name(name.base)
  322. dim_exp = get_for_name(name.exp)
  323. if dim_exp == {} or name.exp.is_Symbol:
  324. return {k: v*name.exp for (k, v) in dim_base.items()}
  325. else:
  326. raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
  327. if name.is_Function:
  328. args = (Dimension._from_dimensional_dependencies(
  329. get_for_name(arg)) for arg in name.args)
  330. result = name.func(*args)
  331. dicts = [get_for_name(i) for i in name.args]
  332. if isinstance(result, Dimension):
  333. return self.get_dimensional_dependencies(result)
  334. elif result.func == name.func:
  335. if isinstance(name, TrigonometricFunction):
  336. if dicts[0] in ({}, {Symbol('angle'): 1}):
  337. return {}
  338. else:
  339. raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(name.func))
  340. else:
  341. if all( (item == {} for item in dicts) ):
  342. return {}
  343. else:
  344. raise TypeError("The input arguments for the function {} must be dimensionless.".format(name.func))
  345. else:
  346. return get_for_name(result)
  347. raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(name)))
  348. def get_dimensional_dependencies(self, name, mark_dimensionless=False):
  349. dimdep = self._get_dimensional_dependencies_for_name(name)
  350. if mark_dimensionless and dimdep == {}:
  351. return {'dimensionless': 1}
  352. return {str(i): j for i, j in dimdep.items()}
  353. def equivalent_dims(self, dim1, dim2):
  354. deps1 = self.get_dimensional_dependencies(dim1)
  355. deps2 = self.get_dimensional_dependencies(dim2)
  356. return deps1 == deps2
  357. def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None):
  358. deps = dict(self.dimensional_dependencies)
  359. if new_dim_deps:
  360. deps.update(new_dim_deps)
  361. new_dim_sys = DimensionSystem(
  362. tuple(self.base_dims) + tuple(new_base_dims),
  363. tuple(self.derived_dims) + tuple(new_derived_dims),
  364. deps
  365. )
  366. new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
  367. new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
  368. return new_dim_sys
  369. def is_dimensionless(self, dimension):
  370. """
  371. Check if the dimension object really has a dimension.
  372. A dimension should have at least one component with non-zero power.
  373. """
  374. if dimension.name == 1:
  375. return True
  376. return self.get_dimensional_dependencies(dimension) == {}
  377. @property
  378. def list_can_dims(self):
  379. """
  380. Useless method, kept for compatibility with previous versions.
  381. DO NOT USE.
  382. List all canonical dimension names.
  383. """
  384. dimset = set()
  385. for i in self.base_dims:
  386. dimset.update(set(self.get_dimensional_dependencies(i).keys()))
  387. return tuple(sorted(dimset, key=str))
  388. @property
  389. def inv_can_transf_matrix(self):
  390. """
  391. Useless method, kept for compatibility with previous versions.
  392. DO NOT USE.
  393. Compute the inverse transformation matrix from the base to the
  394. canonical dimension basis.
  395. It corresponds to the matrix where columns are the vector of base
  396. dimensions in canonical basis.
  397. This matrix will almost never be used because dimensions are always
  398. defined with respect to the canonical basis, so no work has to be done
  399. to get them in this basis. Nonetheless if this matrix is not square
  400. (or not invertible) it means that we have chosen a bad basis.
  401. """
  402. matrix = reduce(lambda x, y: x.row_join(y),
  403. [self.dim_can_vector(d) for d in self.base_dims])
  404. return matrix
  405. @property
  406. def can_transf_matrix(self):
  407. """
  408. Useless method, kept for compatibility with previous versions.
  409. DO NOT USE.
  410. Return the canonical transformation matrix from the canonical to the
  411. base dimension basis.
  412. It is the inverse of the matrix computed with inv_can_transf_matrix().
  413. """
  414. #TODO: the inversion will fail if the system is inconsistent, for
  415. # example if the matrix is not a square
  416. return reduce(lambda x, y: x.row_join(y),
  417. [self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
  418. ).inv()
  419. def dim_can_vector(self, dim):
  420. """
  421. Useless method, kept for compatibility with previous versions.
  422. DO NOT USE.
  423. Dimensional representation in terms of the canonical base dimensions.
  424. """
  425. vec = []
  426. for d in self.list_can_dims:
  427. vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
  428. return Matrix(vec)
  429. def dim_vector(self, dim):
  430. """
  431. Useless method, kept for compatibility with previous versions.
  432. DO NOT USE.
  433. Vector representation in terms of the base dimensions.
  434. """
  435. return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
  436. def print_dim_base(self, dim):
  437. """
  438. Give the string expression of a dimension in term of the basis symbols.
  439. """
  440. dims = self.dim_vector(dim)
  441. symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
  442. res = S.One
  443. for (s, p) in zip(symbols, dims):
  444. res *= s**p
  445. return res
  446. @property
  447. def dim(self):
  448. """
  449. Useless method, kept for compatibility with previous versions.
  450. DO NOT USE.
  451. Give the dimension of the system.
  452. That is return the number of dimensions forming the basis.
  453. """
  454. return len(self.base_dims)
  455. @property
  456. def is_consistent(self):
  457. """
  458. Useless method, kept for compatibility with previous versions.
  459. DO NOT USE.
  460. Check if the system is well defined.
  461. """
  462. # not enough or too many base dimensions compared to independent
  463. # dimensions
  464. # in vector language: the set of vectors do not form a basis
  465. return self.inv_can_transf_matrix.is_square