applied-ai-018 commited on
Commit
21b1cd1
·
verified ·
1 Parent(s): 528457d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/functions/__init__.py +111 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py +2203 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py +915 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py +1506 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__init__.py +38 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/__init__.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/gaussopt.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/medium.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/polarization.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/utils.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/waves.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py +923 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/medium.py +253 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/polarization.py +732 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/utils.py +698 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/waves.py +340 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__init__.py +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py +126 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py +57 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py +84 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py +50 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py +1280 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__init__.py +453 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/dimensions.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/prefixes.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/unitsystem.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/util.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py +265 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py +43 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py +400 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/dimensions.py +590 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/physics/units/prefixes.py +219 -0
env-llmeval/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc ADDED
Binary file (65.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/functions/__init__.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A functions module, includes all the standard functions.
2
+
3
+ Combinatorial - factorial, fibonacci, harmonic, bernoulli...
4
+ Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt...
5
+ Special - gamma, zeta,spherical harmonics...
6
+ """
7
+
8
+ from sympy.functions.combinatorial.factorials import (factorial, factorial2,
9
+ rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial)
10
+ from sympy.functions.combinatorial.numbers import (carmichael, fibonacci, lucas, tribonacci,
11
+ harmonic, bernoulli, bell, euler, catalan, genocchi, andre, partition, motzkin)
12
+ from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
13
+ Id, real_root, cbrt, Rem)
14
+ from sympy.functions.elementary.complexes import (re, im, sign, Abs,
15
+ conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
16
+ principal_branch, transpose, adjoint, polarify, unpolarify)
17
+ from sympy.functions.elementary.trigonometric import (sin, cos, tan,
18
+ sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2)
19
+ from sympy.functions.elementary.exponential import (exp_polar, exp, log,
20
+ LambertW)
21
+ from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
22
+ sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
23
+ from sympy.functions.elementary.integers import floor, ceiling, frac
24
+ from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
25
+ piecewise_exclusive)
26
+ from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
27
+ erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
28
+ fresnels, fresnelc)
29
+ from sympy.functions.special.gamma_functions import (gamma, lowergamma,
30
+ uppergamma, polygamma, loggamma, digamma, trigamma, multigamma)
31
+ from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
32
+ lerchphi, polylog, stieltjes, riemann_xi)
33
+ from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
34
+ KroneckerDelta)
35
+ from sympy.functions.special.singularity_functions import SingularityFunction
36
+ from sympy.functions.special.delta_functions import DiracDelta, Heaviside
37
+ from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set, interpolating_spline
38
+ from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
39
+ hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq)
40
+ from sympy.functions.special.hyper import hyper, meijerg, appellf1
41
+ from sympy.functions.special.polynomials import (legendre, assoc_legendre,
42
+ hermite, hermite_prob, chebyshevt, chebyshevu, chebyshevu_root,
43
+ chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
44
+ from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
45
+ from sympy.functions.special.elliptic_integrals import (elliptic_k,
46
+ elliptic_f, elliptic_e, elliptic_pi)
47
+ from sympy.functions.special.beta_functions import beta, betainc, betainc_regularized
48
+ from sympy.functions.special.mathieu_functions import (mathieus, mathieuc,
49
+ mathieusprime, mathieucprime)
50
+ ln = log
51
+
52
+ __all__ = [
53
+ 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
54
+ 'FallingFactorial', 'subfactorial',
55
+
56
+ 'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic',
57
+ 'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'andre', 'partition',
58
+
59
+ 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt', 'Rem',
60
+
61
+ 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
62
+ 'periodic_argument', 'unbranched_argument', 'principal_branch',
63
+ 'transpose', 'adjoint', 'polarify', 'unpolarify',
64
+
65
+ 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan',
66
+ 'asec', 'acsc', 'acot', 'atan2',
67
+
68
+ 'exp_polar', 'exp', 'ln', 'log', 'LambertW',
69
+
70
+ 'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
71
+ 'acoth', 'asech', 'acsch',
72
+
73
+ 'floor', 'ceiling', 'frac',
74
+
75
+ 'Piecewise', 'piecewise_fold', 'piecewise_exclusive',
76
+
77
+ 'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei',
78
+ 'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels',
79
+ 'fresnelc',
80
+
81
+ 'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma',
82
+ 'trigamma', 'multigamma',
83
+
84
+ 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'riemann_xi',
85
+
86
+ 'Eijk', 'LeviCivita', 'KroneckerDelta',
87
+
88
+ 'SingularityFunction',
89
+
90
+ 'DiracDelta', 'Heaviside',
91
+
92
+ 'bspline_basis', 'bspline_basis_set', 'interpolating_spline',
93
+
94
+ 'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn',
95
+ 'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
96
+ 'airybiprime', 'marcumq',
97
+
98
+ 'hyper', 'meijerg', 'appellf1',
99
+
100
+ 'legendre', 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt',
101
+ 'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre',
102
+ 'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized',
103
+
104
+ 'Ynm', 'Ynm_c', 'Znm',
105
+
106
+ 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi',
107
+
108
+ 'beta', 'betainc', 'betainc_regularized',
109
+
110
+ 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
111
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py ADDED
@@ -0,0 +1,2203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, sympify, cacheit
2
+ from sympy.core.add import Add
3
+ from sympy.core.function import Function, ArgumentIndexError
4
+ from sympy.core.logic import fuzzy_or, fuzzy_and, FuzzyBool
5
+ from sympy.core.numbers import I, pi, Rational
6
+ from sympy.core.symbol import Dummy
7
+ from sympy.functions.combinatorial.factorials import (binomial, factorial,
8
+ RisingFactorial)
9
+ from sympy.functions.combinatorial.numbers import bernoulli, euler, nC
10
+ from sympy.functions.elementary.complexes import Abs, im, re
11
+ from sympy.functions.elementary.exponential import exp, log, match_real_imag
12
+ from sympy.functions.elementary.integers import floor
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.trigonometric import (
15
+ acos, acot, asin, atan, cos, cot, csc, sec, sin, tan,
16
+ _imaginary_unit_as_coefficient)
17
+ from sympy.polys.specialpolys import symmetric_poly
18
+
19
+
20
+ def _rewrite_hyperbolics_as_exp(expr):
21
+ return expr.xreplace({h: h.rewrite(exp)
22
+ for h in expr.atoms(HyperbolicFunction)})
23
+
24
+
25
+ @cacheit
26
+ def _acosh_table():
27
+ return {
28
+ I: log(I*(1 + sqrt(2))),
29
+ -I: log(-I*(1 + sqrt(2))),
30
+ S.Half: pi/3,
31
+ Rational(-1, 2): pi*Rational(2, 3),
32
+ sqrt(2)/2: pi/4,
33
+ -sqrt(2)/2: pi*Rational(3, 4),
34
+ 1/sqrt(2): pi/4,
35
+ -1/sqrt(2): pi*Rational(3, 4),
36
+ sqrt(3)/2: pi/6,
37
+ -sqrt(3)/2: pi*Rational(5, 6),
38
+ (sqrt(3) - 1)/sqrt(2**3): pi*Rational(5, 12),
39
+ -(sqrt(3) - 1)/sqrt(2**3): pi*Rational(7, 12),
40
+ sqrt(2 + sqrt(2))/2: pi/8,
41
+ -sqrt(2 + sqrt(2))/2: pi*Rational(7, 8),
42
+ sqrt(2 - sqrt(2))/2: pi*Rational(3, 8),
43
+ -sqrt(2 - sqrt(2))/2: pi*Rational(5, 8),
44
+ (1 + sqrt(3))/(2*sqrt(2)): pi/12,
45
+ -(1 + sqrt(3))/(2*sqrt(2)): pi*Rational(11, 12),
46
+ (sqrt(5) + 1)/4: pi/5,
47
+ -(sqrt(5) + 1)/4: pi*Rational(4, 5)
48
+ }
49
+
50
+
51
+ @cacheit
52
+ def _acsch_table():
53
+ return {
54
+ I: -pi / 2,
55
+ I*(sqrt(2) + sqrt(6)): -pi / 12,
56
+ I*(1 + sqrt(5)): -pi / 10,
57
+ I*2 / sqrt(2 - sqrt(2)): -pi / 8,
58
+ I*2: -pi / 6,
59
+ I*sqrt(2 + 2/sqrt(5)): -pi / 5,
60
+ I*sqrt(2): -pi / 4,
61
+ I*(sqrt(5)-1): -3*pi / 10,
62
+ I*2 / sqrt(3): -pi / 3,
63
+ I*2 / sqrt(2 + sqrt(2)): -3*pi / 8,
64
+ I*sqrt(2 - 2/sqrt(5)): -2*pi / 5,
65
+ I*(sqrt(6) - sqrt(2)): -5*pi / 12,
66
+ S(2): -I*log((1+sqrt(5))/2),
67
+ }
68
+
69
+
70
+ @cacheit
71
+ def _asech_table():
72
+ return {
73
+ I: - (pi*I / 2) + log(1 + sqrt(2)),
74
+ -I: (pi*I / 2) + log(1 + sqrt(2)),
75
+ (sqrt(6) - sqrt(2)): pi / 12,
76
+ (sqrt(2) - sqrt(6)): 11*pi / 12,
77
+ sqrt(2 - 2/sqrt(5)): pi / 10,
78
+ -sqrt(2 - 2/sqrt(5)): 9*pi / 10,
79
+ 2 / sqrt(2 + sqrt(2)): pi / 8,
80
+ -2 / sqrt(2 + sqrt(2)): 7*pi / 8,
81
+ 2 / sqrt(3): pi / 6,
82
+ -2 / sqrt(3): 5*pi / 6,
83
+ (sqrt(5) - 1): pi / 5,
84
+ (1 - sqrt(5)): 4*pi / 5,
85
+ sqrt(2): pi / 4,
86
+ -sqrt(2): 3*pi / 4,
87
+ sqrt(2 + 2/sqrt(5)): 3*pi / 10,
88
+ -sqrt(2 + 2/sqrt(5)): 7*pi / 10,
89
+ S(2): pi / 3,
90
+ -S(2): 2*pi / 3,
91
+ sqrt(2*(2 + sqrt(2))): 3*pi / 8,
92
+ -sqrt(2*(2 + sqrt(2))): 5*pi / 8,
93
+ (1 + sqrt(5)): 2*pi / 5,
94
+ (-1 - sqrt(5)): 3*pi / 5,
95
+ (sqrt(6) + sqrt(2)): 5*pi / 12,
96
+ (-sqrt(6) - sqrt(2)): 7*pi / 12,
97
+ I*S.Infinity: -pi*I / 2,
98
+ I*S.NegativeInfinity: pi*I / 2,
99
+ }
100
+
101
+ ###############################################################################
102
+ ########################### HYPERBOLIC FUNCTIONS ##############################
103
+ ###############################################################################
104
+
105
+
106
+ class HyperbolicFunction(Function):
107
+ """
108
+ Base class for hyperbolic functions.
109
+
110
+ See Also
111
+ ========
112
+
113
+ sinh, cosh, tanh, coth
114
+ """
115
+
116
+ unbranched = True
117
+
118
+
119
+ def _peeloff_ipi(arg):
120
+ r"""
121
+ Split ARG into two parts, a "rest" and a multiple of $I\pi$.
122
+ This assumes ARG to be an ``Add``.
123
+ The multiple of $I\pi$ returned in the second position is always a ``Rational``.
124
+
125
+ Examples
126
+ ========
127
+
128
+ >>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel
129
+ >>> from sympy import pi, I
130
+ >>> from sympy.abc import x, y
131
+ >>> peel(x + I*pi/2)
132
+ (x, 1/2)
133
+ >>> peel(x + I*2*pi/3 + I*pi*y)
134
+ (x + I*pi*y + I*pi/6, 1/2)
135
+ """
136
+ ipi = pi*I
137
+ for a in Add.make_args(arg):
138
+ if a == ipi:
139
+ K = S.One
140
+ break
141
+ elif a.is_Mul:
142
+ K, p = a.as_two_terms()
143
+ if p == ipi and K.is_Rational:
144
+ break
145
+ else:
146
+ return arg, S.Zero
147
+
148
+ m1 = (K % S.Half)
149
+ m2 = K - m1
150
+ return arg - m2*ipi, m2
151
+
152
+
153
+ class sinh(HyperbolicFunction):
154
+ r"""
155
+ ``sinh(x)`` is the hyperbolic sine of ``x``.
156
+
157
+ The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$.
158
+
159
+ Examples
160
+ ========
161
+
162
+ >>> from sympy import sinh
163
+ >>> from sympy.abc import x
164
+ >>> sinh(x)
165
+ sinh(x)
166
+
167
+ See Also
168
+ ========
169
+
170
+ cosh, tanh, asinh
171
+ """
172
+
173
+ def fdiff(self, argindex=1):
174
+ """
175
+ Returns the first derivative of this function.
176
+ """
177
+ if argindex == 1:
178
+ return cosh(self.args[0])
179
+ else:
180
+ raise ArgumentIndexError(self, argindex)
181
+
182
+ def inverse(self, argindex=1):
183
+ """
184
+ Returns the inverse of this function.
185
+ """
186
+ return asinh
187
+
188
+ @classmethod
189
+ def eval(cls, arg):
190
+ if arg.is_Number:
191
+ if arg is S.NaN:
192
+ return S.NaN
193
+ elif arg is S.Infinity:
194
+ return S.Infinity
195
+ elif arg is S.NegativeInfinity:
196
+ return S.NegativeInfinity
197
+ elif arg.is_zero:
198
+ return S.Zero
199
+ elif arg.is_negative:
200
+ return -cls(-arg)
201
+ else:
202
+ if arg is S.ComplexInfinity:
203
+ return S.NaN
204
+
205
+ i_coeff = _imaginary_unit_as_coefficient(arg)
206
+
207
+ if i_coeff is not None:
208
+ return I * sin(i_coeff)
209
+ else:
210
+ if arg.could_extract_minus_sign():
211
+ return -cls(-arg)
212
+
213
+ if arg.is_Add:
214
+ x, m = _peeloff_ipi(arg)
215
+ if m:
216
+ m = m*pi*I
217
+ return sinh(m)*cosh(x) + cosh(m)*sinh(x)
218
+
219
+ if arg.is_zero:
220
+ return S.Zero
221
+
222
+ if arg.func == asinh:
223
+ return arg.args[0]
224
+
225
+ if arg.func == acosh:
226
+ x = arg.args[0]
227
+ return sqrt(x - 1) * sqrt(x + 1)
228
+
229
+ if arg.func == atanh:
230
+ x = arg.args[0]
231
+ return x/sqrt(1 - x**2)
232
+
233
+ if arg.func == acoth:
234
+ x = arg.args[0]
235
+ return 1/(sqrt(x - 1) * sqrt(x + 1))
236
+
237
+ @staticmethod
238
+ @cacheit
239
+ def taylor_term(n, x, *previous_terms):
240
+ """
241
+ Returns the next term in the Taylor series expansion.
242
+ """
243
+ if n < 0 or n % 2 == 0:
244
+ return S.Zero
245
+ else:
246
+ x = sympify(x)
247
+
248
+ if len(previous_terms) > 2:
249
+ p = previous_terms[-2]
250
+ return p * x**2 / (n*(n - 1))
251
+ else:
252
+ return x**(n) / factorial(n)
253
+
254
+ def _eval_conjugate(self):
255
+ return self.func(self.args[0].conjugate())
256
+
257
+ def as_real_imag(self, deep=True, **hints):
258
+ """
259
+ Returns this function as a complex coordinate.
260
+ """
261
+ if self.args[0].is_extended_real:
262
+ if deep:
263
+ hints['complex'] = False
264
+ return (self.expand(deep, **hints), S.Zero)
265
+ else:
266
+ return (self, S.Zero)
267
+ if deep:
268
+ re, im = self.args[0].expand(deep, **hints).as_real_imag()
269
+ else:
270
+ re, im = self.args[0].as_real_imag()
271
+ return (sinh(re)*cos(im), cosh(re)*sin(im))
272
+
273
+ def _eval_expand_complex(self, deep=True, **hints):
274
+ re_part, im_part = self.as_real_imag(deep=deep, **hints)
275
+ return re_part + im_part*I
276
+
277
+ def _eval_expand_trig(self, deep=True, **hints):
278
+ if deep:
279
+ arg = self.args[0].expand(deep, **hints)
280
+ else:
281
+ arg = self.args[0]
282
+ x = None
283
+ if arg.is_Add: # TODO, implement more if deep stuff here
284
+ x, y = arg.as_two_terms()
285
+ else:
286
+ coeff, terms = arg.as_coeff_Mul(rational=True)
287
+ if coeff is not S.One and coeff.is_Integer and terms is not S.One:
288
+ x = terms
289
+ y = (coeff - 1)*x
290
+ if x is not None:
291
+ return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True)
292
+ return sinh(arg)
293
+
294
+ def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
295
+ return (exp(arg) - exp(-arg)) / 2
296
+
297
+ def _eval_rewrite_as_exp(self, arg, **kwargs):
298
+ return (exp(arg) - exp(-arg)) / 2
299
+
300
+ def _eval_rewrite_as_sin(self, arg, **kwargs):
301
+ return -I * sin(I * arg)
302
+
303
+ def _eval_rewrite_as_csc(self, arg, **kwargs):
304
+ return -I / csc(I * arg)
305
+
306
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
307
+ return -I*cosh(arg + pi*I/2)
308
+
309
+ def _eval_rewrite_as_tanh(self, arg, **kwargs):
310
+ tanh_half = tanh(S.Half*arg)
311
+ return 2*tanh_half/(1 - tanh_half**2)
312
+
313
+ def _eval_rewrite_as_coth(self, arg, **kwargs):
314
+ coth_half = coth(S.Half*arg)
315
+ return 2*coth_half/(coth_half**2 - 1)
316
+
317
+ def _eval_rewrite_as_csch(self, arg, **kwargs):
318
+ return 1 / csch(arg)
319
+
320
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
321
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
322
+ arg0 = arg.subs(x, 0)
323
+
324
+ if arg0 is S.NaN:
325
+ arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+')
326
+ if arg0.is_zero:
327
+ return arg
328
+ elif arg0.is_finite:
329
+ return self.func(arg0)
330
+ else:
331
+ return self
332
+
333
+ def _eval_is_real(self):
334
+ arg = self.args[0]
335
+ if arg.is_real:
336
+ return True
337
+
338
+ # if `im` is of the form n*pi
339
+ # else, check if it is a number
340
+ re, im = arg.as_real_imag()
341
+ return (im%pi).is_zero
342
+
343
+ def _eval_is_extended_real(self):
344
+ if self.args[0].is_extended_real:
345
+ return True
346
+
347
+ def _eval_is_positive(self):
348
+ if self.args[0].is_extended_real:
349
+ return self.args[0].is_positive
350
+
351
+ def _eval_is_negative(self):
352
+ if self.args[0].is_extended_real:
353
+ return self.args[0].is_negative
354
+
355
+ def _eval_is_finite(self):
356
+ arg = self.args[0]
357
+ return arg.is_finite
358
+
359
+ def _eval_is_zero(self):
360
+ rest, ipi_mult = _peeloff_ipi(self.args[0])
361
+ if rest.is_zero:
362
+ return ipi_mult.is_integer
363
+
364
+
365
+ class cosh(HyperbolicFunction):
366
+ r"""
367
+ ``cosh(x)`` is the hyperbolic cosine of ``x``.
368
+
369
+ The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$.
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy import cosh
375
+ >>> from sympy.abc import x
376
+ >>> cosh(x)
377
+ cosh(x)
378
+
379
+ See Also
380
+ ========
381
+
382
+ sinh, tanh, acosh
383
+ """
384
+
385
+ def fdiff(self, argindex=1):
386
+ if argindex == 1:
387
+ return sinh(self.args[0])
388
+ else:
389
+ raise ArgumentIndexError(self, argindex)
390
+
391
+ @classmethod
392
+ def eval(cls, arg):
393
+ from sympy.functions.elementary.trigonometric import cos
394
+ if arg.is_Number:
395
+ if arg is S.NaN:
396
+ return S.NaN
397
+ elif arg is S.Infinity:
398
+ return S.Infinity
399
+ elif arg is S.NegativeInfinity:
400
+ return S.Infinity
401
+ elif arg.is_zero:
402
+ return S.One
403
+ elif arg.is_negative:
404
+ return cls(-arg)
405
+ else:
406
+ if arg is S.ComplexInfinity:
407
+ return S.NaN
408
+
409
+ i_coeff = _imaginary_unit_as_coefficient(arg)
410
+
411
+ if i_coeff is not None:
412
+ return cos(i_coeff)
413
+ else:
414
+ if arg.could_extract_minus_sign():
415
+ return cls(-arg)
416
+
417
+ if arg.is_Add:
418
+ x, m = _peeloff_ipi(arg)
419
+ if m:
420
+ m = m*pi*I
421
+ return cosh(m)*cosh(x) + sinh(m)*sinh(x)
422
+
423
+ if arg.is_zero:
424
+ return S.One
425
+
426
+ if arg.func == asinh:
427
+ return sqrt(1 + arg.args[0]**2)
428
+
429
+ if arg.func == acosh:
430
+ return arg.args[0]
431
+
432
+ if arg.func == atanh:
433
+ return 1/sqrt(1 - arg.args[0]**2)
434
+
435
+ if arg.func == acoth:
436
+ x = arg.args[0]
437
+ return x/(sqrt(x - 1) * sqrt(x + 1))
438
+
439
+ @staticmethod
440
+ @cacheit
441
+ def taylor_term(n, x, *previous_terms):
442
+ if n < 0 or n % 2 == 1:
443
+ return S.Zero
444
+ else:
445
+ x = sympify(x)
446
+
447
+ if len(previous_terms) > 2:
448
+ p = previous_terms[-2]
449
+ return p * x**2 / (n*(n - 1))
450
+ else:
451
+ return x**(n)/factorial(n)
452
+
453
+ def _eval_conjugate(self):
454
+ return self.func(self.args[0].conjugate())
455
+
456
+ def as_real_imag(self, deep=True, **hints):
457
+ if self.args[0].is_extended_real:
458
+ if deep:
459
+ hints['complex'] = False
460
+ return (self.expand(deep, **hints), S.Zero)
461
+ else:
462
+ return (self, S.Zero)
463
+ if deep:
464
+ re, im = self.args[0].expand(deep, **hints).as_real_imag()
465
+ else:
466
+ re, im = self.args[0].as_real_imag()
467
+
468
+ return (cosh(re)*cos(im), sinh(re)*sin(im))
469
+
470
+ def _eval_expand_complex(self, deep=True, **hints):
471
+ re_part, im_part = self.as_real_imag(deep=deep, **hints)
472
+ return re_part + im_part*I
473
+
474
+ def _eval_expand_trig(self, deep=True, **hints):
475
+ if deep:
476
+ arg = self.args[0].expand(deep, **hints)
477
+ else:
478
+ arg = self.args[0]
479
+ x = None
480
+ if arg.is_Add: # TODO, implement more if deep stuff here
481
+ x, y = arg.as_two_terms()
482
+ else:
483
+ coeff, terms = arg.as_coeff_Mul(rational=True)
484
+ if coeff is not S.One and coeff.is_Integer and terms is not S.One:
485
+ x = terms
486
+ y = (coeff - 1)*x
487
+ if x is not None:
488
+ return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True)
489
+ return cosh(arg)
490
+
491
+ def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
492
+ return (exp(arg) + exp(-arg)) / 2
493
+
494
+ def _eval_rewrite_as_exp(self, arg, **kwargs):
495
+ return (exp(arg) + exp(-arg)) / 2
496
+
497
+ def _eval_rewrite_as_cos(self, arg, **kwargs):
498
+ return cos(I * arg)
499
+
500
+ def _eval_rewrite_as_sec(self, arg, **kwargs):
501
+ return 1 / sec(I * arg)
502
+
503
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
504
+ return -I*sinh(arg + pi*I/2)
505
+
506
+ def _eval_rewrite_as_tanh(self, arg, **kwargs):
507
+ tanh_half = tanh(S.Half*arg)**2
508
+ return (1 + tanh_half)/(1 - tanh_half)
509
+
510
+ def _eval_rewrite_as_coth(self, arg, **kwargs):
511
+ coth_half = coth(S.Half*arg)**2
512
+ return (coth_half + 1)/(coth_half - 1)
513
+
514
+ def _eval_rewrite_as_sech(self, arg, **kwargs):
515
+ return 1 / sech(arg)
516
+
517
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
518
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
519
+ arg0 = arg.subs(x, 0)
520
+
521
+ if arg0 is S.NaN:
522
+ arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+')
523
+ if arg0.is_zero:
524
+ return S.One
525
+ elif arg0.is_finite:
526
+ return self.func(arg0)
527
+ else:
528
+ return self
529
+
530
+ def _eval_is_real(self):
531
+ arg = self.args[0]
532
+
533
+ # `cosh(x)` is real for real OR purely imaginary `x`
534
+ if arg.is_real or arg.is_imaginary:
535
+ return True
536
+
537
+ # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)
538
+ # the imaginary part can be an expression like n*pi
539
+ # if not, check if the imaginary part is a number
540
+ re, im = arg.as_real_imag()
541
+ return (im%pi).is_zero
542
+
543
+ def _eval_is_positive(self):
544
+ # cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x)
545
+ # cosh(z) is positive iff it is real and the real part is positive.
546
+ # So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi
547
+ # Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even
548
+ # Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive
549
+ z = self.args[0]
550
+
551
+ x, y = z.as_real_imag()
552
+ ymod = y % (2*pi)
553
+
554
+ yzero = ymod.is_zero
555
+ # shortcut if ymod is zero
556
+ if yzero:
557
+ return True
558
+
559
+ xzero = x.is_zero
560
+ # shortcut x is not zero
561
+ if xzero is False:
562
+ return yzero
563
+
564
+ return fuzzy_or([
565
+ # Case 1:
566
+ yzero,
567
+ # Case 2:
568
+ fuzzy_and([
569
+ xzero,
570
+ fuzzy_or([ymod < pi/2, ymod > 3*pi/2])
571
+ ])
572
+ ])
573
+
574
+
575
+ def _eval_is_nonnegative(self):
576
+ z = self.args[0]
577
+
578
+ x, y = z.as_real_imag()
579
+ ymod = y % (2*pi)
580
+
581
+ yzero = ymod.is_zero
582
+ # shortcut if ymod is zero
583
+ if yzero:
584
+ return True
585
+
586
+ xzero = x.is_zero
587
+ # shortcut x is not zero
588
+ if xzero is False:
589
+ return yzero
590
+
591
+ return fuzzy_or([
592
+ # Case 1:
593
+ yzero,
594
+ # Case 2:
595
+ fuzzy_and([
596
+ xzero,
597
+ fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2])
598
+ ])
599
+ ])
600
+
601
+ def _eval_is_finite(self):
602
+ arg = self.args[0]
603
+ return arg.is_finite
604
+
605
+ def _eval_is_zero(self):
606
+ rest, ipi_mult = _peeloff_ipi(self.args[0])
607
+ if ipi_mult and rest.is_zero:
608
+ return (ipi_mult - S.Half).is_integer
609
+
610
+
611
+ class tanh(HyperbolicFunction):
612
+ r"""
613
+ ``tanh(x)`` is the hyperbolic tangent of ``x``.
614
+
615
+ The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$.
616
+
617
+ Examples
618
+ ========
619
+
620
+ >>> from sympy import tanh
621
+ >>> from sympy.abc import x
622
+ >>> tanh(x)
623
+ tanh(x)
624
+
625
+ See Also
626
+ ========
627
+
628
+ sinh, cosh, atanh
629
+ """
630
+
631
+ def fdiff(self, argindex=1):
632
+ if argindex == 1:
633
+ return S.One - tanh(self.args[0])**2
634
+ else:
635
+ raise ArgumentIndexError(self, argindex)
636
+
637
+ def inverse(self, argindex=1):
638
+ """
639
+ Returns the inverse of this function.
640
+ """
641
+ return atanh
642
+
643
+ @classmethod
644
+ def eval(cls, arg):
645
+ if arg.is_Number:
646
+ if arg is S.NaN:
647
+ return S.NaN
648
+ elif arg is S.Infinity:
649
+ return S.One
650
+ elif arg is S.NegativeInfinity:
651
+ return S.NegativeOne
652
+ elif arg.is_zero:
653
+ return S.Zero
654
+ elif arg.is_negative:
655
+ return -cls(-arg)
656
+ else:
657
+ if arg is S.ComplexInfinity:
658
+ return S.NaN
659
+
660
+ i_coeff = _imaginary_unit_as_coefficient(arg)
661
+
662
+ if i_coeff is not None:
663
+ if i_coeff.could_extract_minus_sign():
664
+ return -I * tan(-i_coeff)
665
+ return I * tan(i_coeff)
666
+ else:
667
+ if arg.could_extract_minus_sign():
668
+ return -cls(-arg)
669
+
670
+ if arg.is_Add:
671
+ x, m = _peeloff_ipi(arg)
672
+ if m:
673
+ tanhm = tanh(m*pi*I)
674
+ if tanhm is S.ComplexInfinity:
675
+ return coth(x)
676
+ else: # tanhm == 0
677
+ return tanh(x)
678
+
679
+ if arg.is_zero:
680
+ return S.Zero
681
+
682
+ if arg.func == asinh:
683
+ x = arg.args[0]
684
+ return x/sqrt(1 + x**2)
685
+
686
+ if arg.func == acosh:
687
+ x = arg.args[0]
688
+ return sqrt(x - 1) * sqrt(x + 1) / x
689
+
690
+ if arg.func == atanh:
691
+ return arg.args[0]
692
+
693
+ if arg.func == acoth:
694
+ return 1/arg.args[0]
695
+
696
+ @staticmethod
697
+ @cacheit
698
+ def taylor_term(n, x, *previous_terms):
699
+ if n < 0 or n % 2 == 0:
700
+ return S.Zero
701
+ else:
702
+ x = sympify(x)
703
+
704
+ a = 2**(n + 1)
705
+
706
+ B = bernoulli(n + 1)
707
+ F = factorial(n + 1)
708
+
709
+ return a*(a - 1) * B/F * x**n
710
+
711
+ def _eval_conjugate(self):
712
+ return self.func(self.args[0].conjugate())
713
+
714
+ def as_real_imag(self, deep=True, **hints):
715
+ if self.args[0].is_extended_real:
716
+ if deep:
717
+ hints['complex'] = False
718
+ return (self.expand(deep, **hints), S.Zero)
719
+ else:
720
+ return (self, S.Zero)
721
+ if deep:
722
+ re, im = self.args[0].expand(deep, **hints).as_real_imag()
723
+ else:
724
+ re, im = self.args[0].as_real_imag()
725
+ denom = sinh(re)**2 + cos(im)**2
726
+ return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom)
727
+
728
+ def _eval_expand_trig(self, **hints):
729
+ arg = self.args[0]
730
+ if arg.is_Add:
731
+ n = len(arg.args)
732
+ TX = [tanh(x, evaluate=False)._eval_expand_trig()
733
+ for x in arg.args]
734
+ p = [0, 0] # [den, num]
735
+ for i in range(n + 1):
736
+ p[i % 2] += symmetric_poly(i, TX)
737
+ return p[1]/p[0]
738
+ elif arg.is_Mul:
739
+ coeff, terms = arg.as_coeff_Mul()
740
+ if coeff.is_Integer and coeff > 1:
741
+ T = tanh(terms)
742
+ n = [nC(range(coeff), k)*T**k for k in range(1, coeff + 1, 2)]
743
+ d = [nC(range(coeff), k)*T**k for k in range(0, coeff + 1, 2)]
744
+ return Add(*n)/Add(*d)
745
+ return tanh(arg)
746
+
747
+ def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
748
+ neg_exp, pos_exp = exp(-arg), exp(arg)
749
+ return (pos_exp - neg_exp)/(pos_exp + neg_exp)
750
+
751
+ def _eval_rewrite_as_exp(self, arg, **kwargs):
752
+ neg_exp, pos_exp = exp(-arg), exp(arg)
753
+ return (pos_exp - neg_exp)/(pos_exp + neg_exp)
754
+
755
+ def _eval_rewrite_as_tan(self, arg, **kwargs):
756
+ return -I * tan(I * arg)
757
+
758
+ def _eval_rewrite_as_cot(self, arg, **kwargs):
759
+ return -I / cot(I * arg)
760
+
761
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
762
+ return I*sinh(arg)/sinh(pi*I/2 - arg)
763
+
764
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
765
+ return I*cosh(pi*I/2 - arg)/cosh(arg)
766
+
767
+ def _eval_rewrite_as_coth(self, arg, **kwargs):
768
+ return 1/coth(arg)
769
+
770
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
771
+ from sympy.series.order import Order
772
+ arg = self.args[0].as_leading_term(x)
773
+
774
+ if x in arg.free_symbols and Order(1, x).contains(arg):
775
+ return arg
776
+ else:
777
+ return self.func(arg)
778
+
779
+ def _eval_is_real(self):
780
+ arg = self.args[0]
781
+ if arg.is_real:
782
+ return True
783
+
784
+ re, im = arg.as_real_imag()
785
+
786
+ # if denom = 0, tanh(arg) = zoo
787
+ if re == 0 and im % pi == pi/2:
788
+ return None
789
+
790
+ # check if im is of the form n*pi/2 to make sin(2*im) = 0
791
+ # if not, im could be a number, return False in that case
792
+ return (im % (pi/2)).is_zero
793
+
794
+ def _eval_is_extended_real(self):
795
+ if self.args[0].is_extended_real:
796
+ return True
797
+
798
+ def _eval_is_positive(self):
799
+ if self.args[0].is_extended_real:
800
+ return self.args[0].is_positive
801
+
802
+ def _eval_is_negative(self):
803
+ if self.args[0].is_extended_real:
804
+ return self.args[0].is_negative
805
+
806
+ def _eval_is_finite(self):
807
+ arg = self.args[0]
808
+
809
+ re, im = arg.as_real_imag()
810
+ denom = cos(im)**2 + sinh(re)**2
811
+ if denom == 0:
812
+ return False
813
+ elif denom.is_number:
814
+ return True
815
+ if arg.is_extended_real:
816
+ return True
817
+
818
+ def _eval_is_zero(self):
819
+ arg = self.args[0]
820
+ if arg.is_zero:
821
+ return True
822
+
823
+
824
+ class coth(HyperbolicFunction):
825
+ r"""
826
+ ``coth(x)`` is the hyperbolic cotangent of ``x``.
827
+
828
+ The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$.
829
+
830
+ Examples
831
+ ========
832
+
833
+ >>> from sympy import coth
834
+ >>> from sympy.abc import x
835
+ >>> coth(x)
836
+ coth(x)
837
+
838
+ See Also
839
+ ========
840
+
841
+ sinh, cosh, acoth
842
+ """
843
+
844
+ def fdiff(self, argindex=1):
845
+ if argindex == 1:
846
+ return -1/sinh(self.args[0])**2
847
+ else:
848
+ raise ArgumentIndexError(self, argindex)
849
+
850
+ def inverse(self, argindex=1):
851
+ """
852
+ Returns the inverse of this function.
853
+ """
854
+ return acoth
855
+
856
+ @classmethod
857
+ def eval(cls, arg):
858
+ if arg.is_Number:
859
+ if arg is S.NaN:
860
+ return S.NaN
861
+ elif arg is S.Infinity:
862
+ return S.One
863
+ elif arg is S.NegativeInfinity:
864
+ return S.NegativeOne
865
+ elif arg.is_zero:
866
+ return S.ComplexInfinity
867
+ elif arg.is_negative:
868
+ return -cls(-arg)
869
+ else:
870
+ if arg is S.ComplexInfinity:
871
+ return S.NaN
872
+
873
+ i_coeff = _imaginary_unit_as_coefficient(arg)
874
+
875
+ if i_coeff is not None:
876
+ if i_coeff.could_extract_minus_sign():
877
+ return I * cot(-i_coeff)
878
+ return -I * cot(i_coeff)
879
+ else:
880
+ if arg.could_extract_minus_sign():
881
+ return -cls(-arg)
882
+
883
+ if arg.is_Add:
884
+ x, m = _peeloff_ipi(arg)
885
+ if m:
886
+ cothm = coth(m*pi*I)
887
+ if cothm is S.ComplexInfinity:
888
+ return coth(x)
889
+ else: # cothm == 0
890
+ return tanh(x)
891
+
892
+ if arg.is_zero:
893
+ return S.ComplexInfinity
894
+
895
+ if arg.func == asinh:
896
+ x = arg.args[0]
897
+ return sqrt(1 + x**2)/x
898
+
899
+ if arg.func == acosh:
900
+ x = arg.args[0]
901
+ return x/(sqrt(x - 1) * sqrt(x + 1))
902
+
903
+ if arg.func == atanh:
904
+ return 1/arg.args[0]
905
+
906
+ if arg.func == acoth:
907
+ return arg.args[0]
908
+
909
+ @staticmethod
910
+ @cacheit
911
+ def taylor_term(n, x, *previous_terms):
912
+ if n == 0:
913
+ return 1 / sympify(x)
914
+ elif n < 0 or n % 2 == 0:
915
+ return S.Zero
916
+ else:
917
+ x = sympify(x)
918
+
919
+ B = bernoulli(n + 1)
920
+ F = factorial(n + 1)
921
+
922
+ return 2**(n + 1) * B/F * x**n
923
+
924
+ def _eval_conjugate(self):
925
+ return self.func(self.args[0].conjugate())
926
+
927
+ def as_real_imag(self, deep=True, **hints):
928
+ from sympy.functions.elementary.trigonometric import (cos, sin)
929
+ if self.args[0].is_extended_real:
930
+ if deep:
931
+ hints['complex'] = False
932
+ return (self.expand(deep, **hints), S.Zero)
933
+ else:
934
+ return (self, S.Zero)
935
+ if deep:
936
+ re, im = self.args[0].expand(deep, **hints).as_real_imag()
937
+ else:
938
+ re, im = self.args[0].as_real_imag()
939
+ denom = sinh(re)**2 + sin(im)**2
940
+ return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom)
941
+
942
+ def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
943
+ neg_exp, pos_exp = exp(-arg), exp(arg)
944
+ return (pos_exp + neg_exp)/(pos_exp - neg_exp)
945
+
946
+ def _eval_rewrite_as_exp(self, arg, **kwargs):
947
+ neg_exp, pos_exp = exp(-arg), exp(arg)
948
+ return (pos_exp + neg_exp)/(pos_exp - neg_exp)
949
+
950
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
951
+ return -I*sinh(pi*I/2 - arg)/sinh(arg)
952
+
953
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
954
+ return -I*cosh(arg)/cosh(pi*I/2 - arg)
955
+
956
+ def _eval_rewrite_as_tanh(self, arg, **kwargs):
957
+ return 1/tanh(arg)
958
+
959
+ def _eval_is_positive(self):
960
+ if self.args[0].is_extended_real:
961
+ return self.args[0].is_positive
962
+
963
+ def _eval_is_negative(self):
964
+ if self.args[0].is_extended_real:
965
+ return self.args[0].is_negative
966
+
967
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
968
+ from sympy.series.order import Order
969
+ arg = self.args[0].as_leading_term(x)
970
+
971
+ if x in arg.free_symbols and Order(1, x).contains(arg):
972
+ return 1/arg
973
+ else:
974
+ return self.func(arg)
975
+
976
+ def _eval_expand_trig(self, **hints):
977
+ arg = self.args[0]
978
+ if arg.is_Add:
979
+ CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args]
980
+ p = [[], []]
981
+ n = len(arg.args)
982
+ for i in range(n, -1, -1):
983
+ p[(n - i) % 2].append(symmetric_poly(i, CX))
984
+ return Add(*p[0])/Add(*p[1])
985
+ elif arg.is_Mul:
986
+ coeff, x = arg.as_coeff_Mul(rational=True)
987
+ if coeff.is_Integer and coeff > 1:
988
+ c = coth(x, evaluate=False)
989
+ p = [[], []]
990
+ for i in range(coeff, -1, -1):
991
+ p[(coeff - i) % 2].append(binomial(coeff, i)*c**i)
992
+ return Add(*p[0])/Add(*p[1])
993
+ return coth(arg)
994
+
995
+
996
+ class ReciprocalHyperbolicFunction(HyperbolicFunction):
997
+ """Base class for reciprocal functions of hyperbolic functions. """
998
+
999
+ #To be defined in class
1000
+ _reciprocal_of = None
1001
+ _is_even: FuzzyBool = None
1002
+ _is_odd: FuzzyBool = None
1003
+
1004
+ @classmethod
1005
+ def eval(cls, arg):
1006
+ if arg.could_extract_minus_sign():
1007
+ if cls._is_even:
1008
+ return cls(-arg)
1009
+ if cls._is_odd:
1010
+ return -cls(-arg)
1011
+
1012
+ t = cls._reciprocal_of.eval(arg)
1013
+ if hasattr(arg, 'inverse') and arg.inverse() == cls:
1014
+ return arg.args[0]
1015
+ return 1/t if t is not None else t
1016
+
1017
+ def _call_reciprocal(self, method_name, *args, **kwargs):
1018
+ # Calls method_name on _reciprocal_of
1019
+ o = self._reciprocal_of(self.args[0])
1020
+ return getattr(o, method_name)(*args, **kwargs)
1021
+
1022
+ def _calculate_reciprocal(self, method_name, *args, **kwargs):
1023
+ # If calling method_name on _reciprocal_of returns a value != None
1024
+ # then return the reciprocal of that value
1025
+ t = self._call_reciprocal(method_name, *args, **kwargs)
1026
+ return 1/t if t is not None else t
1027
+
1028
+ def _rewrite_reciprocal(self, method_name, arg):
1029
+ # Special handling for rewrite functions. If reciprocal rewrite returns
1030
+ # unmodified expression, then return None
1031
+ t = self._call_reciprocal(method_name, arg)
1032
+ if t is not None and t != self._reciprocal_of(arg):
1033
+ return 1/t
1034
+
1035
+ def _eval_rewrite_as_exp(self, arg, **kwargs):
1036
+ return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg)
1037
+
1038
+ def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
1039
+ return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg)
1040
+
1041
+ def _eval_rewrite_as_tanh(self, arg, **kwargs):
1042
+ return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg)
1043
+
1044
+ def _eval_rewrite_as_coth(self, arg, **kwargs):
1045
+ return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg)
1046
+
1047
+ def as_real_imag(self, deep = True, **hints):
1048
+ return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints)
1049
+
1050
+ def _eval_conjugate(self):
1051
+ return self.func(self.args[0].conjugate())
1052
+
1053
+ def _eval_expand_complex(self, deep=True, **hints):
1054
+ re_part, im_part = self.as_real_imag(deep=True, **hints)
1055
+ return re_part + I*im_part
1056
+
1057
+ def _eval_expand_trig(self, **hints):
1058
+ return self._calculate_reciprocal("_eval_expand_trig", **hints)
1059
+
1060
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1061
+ return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)
1062
+
1063
+ def _eval_is_extended_real(self):
1064
+ return self._reciprocal_of(self.args[0]).is_extended_real
1065
+
1066
+ def _eval_is_finite(self):
1067
+ return (1/self._reciprocal_of(self.args[0])).is_finite
1068
+
1069
+
1070
+ class csch(ReciprocalHyperbolicFunction):
1071
+ r"""
1072
+ ``csch(x)`` is the hyperbolic cosecant of ``x``.
1073
+
1074
+ The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$
1075
+
1076
+ Examples
1077
+ ========
1078
+
1079
+ >>> from sympy import csch
1080
+ >>> from sympy.abc import x
1081
+ >>> csch(x)
1082
+ csch(x)
1083
+
1084
+ See Also
1085
+ ========
1086
+
1087
+ sinh, cosh, tanh, sech, asinh, acosh
1088
+ """
1089
+
1090
+ _reciprocal_of = sinh
1091
+ _is_odd = True
1092
+
1093
+ def fdiff(self, argindex=1):
1094
+ """
1095
+ Returns the first derivative of this function
1096
+ """
1097
+ if argindex == 1:
1098
+ return -coth(self.args[0]) * csch(self.args[0])
1099
+ else:
1100
+ raise ArgumentIndexError(self, argindex)
1101
+
1102
+ @staticmethod
1103
+ @cacheit
1104
+ def taylor_term(n, x, *previous_terms):
1105
+ """
1106
+ Returns the next term in the Taylor series expansion
1107
+ """
1108
+ if n == 0:
1109
+ return 1/sympify(x)
1110
+ elif n < 0 or n % 2 == 0:
1111
+ return S.Zero
1112
+ else:
1113
+ x = sympify(x)
1114
+
1115
+ B = bernoulli(n + 1)
1116
+ F = factorial(n + 1)
1117
+
1118
+ return 2 * (1 - 2**n) * B/F * x**n
1119
+
1120
+ def _eval_rewrite_as_sin(self, arg, **kwargs):
1121
+ return I / sin(I * arg)
1122
+
1123
+ def _eval_rewrite_as_csc(self, arg, **kwargs):
1124
+ return I * csc(I * arg)
1125
+
1126
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
1127
+ return I / cosh(arg + I * pi / 2)
1128
+
1129
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
1130
+ return 1 / sinh(arg)
1131
+
1132
+ def _eval_is_positive(self):
1133
+ if self.args[0].is_extended_real:
1134
+ return self.args[0].is_positive
1135
+
1136
+ def _eval_is_negative(self):
1137
+ if self.args[0].is_extended_real:
1138
+ return self.args[0].is_negative
1139
+
1140
+
1141
+ class sech(ReciprocalHyperbolicFunction):
1142
+ r"""
1143
+ ``sech(x)`` is the hyperbolic secant of ``x``.
1144
+
1145
+ The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$
1146
+
1147
+ Examples
1148
+ ========
1149
+
1150
+ >>> from sympy import sech
1151
+ >>> from sympy.abc import x
1152
+ >>> sech(x)
1153
+ sech(x)
1154
+
1155
+ See Also
1156
+ ========
1157
+
1158
+ sinh, cosh, tanh, coth, csch, asinh, acosh
1159
+ """
1160
+
1161
+ _reciprocal_of = cosh
1162
+ _is_even = True
1163
+
1164
+ def fdiff(self, argindex=1):
1165
+ if argindex == 1:
1166
+ return - tanh(self.args[0])*sech(self.args[0])
1167
+ else:
1168
+ raise ArgumentIndexError(self, argindex)
1169
+
1170
+ @staticmethod
1171
+ @cacheit
1172
+ def taylor_term(n, x, *previous_terms):
1173
+ if n < 0 or n % 2 == 1:
1174
+ return S.Zero
1175
+ else:
1176
+ x = sympify(x)
1177
+ return euler(n) / factorial(n) * x**(n)
1178
+
1179
+ def _eval_rewrite_as_cos(self, arg, **kwargs):
1180
+ return 1 / cos(I * arg)
1181
+
1182
+ def _eval_rewrite_as_sec(self, arg, **kwargs):
1183
+ return sec(I * arg)
1184
+
1185
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
1186
+ return I / sinh(arg + I * pi /2)
1187
+
1188
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
1189
+ return 1 / cosh(arg)
1190
+
1191
+ def _eval_is_positive(self):
1192
+ if self.args[0].is_extended_real:
1193
+ return True
1194
+
1195
+
1196
+ ###############################################################################
1197
+ ############################# HYPERBOLIC INVERSES #############################
1198
+ ###############################################################################
1199
+
1200
+ class InverseHyperbolicFunction(Function):
1201
+ """Base class for inverse hyperbolic functions."""
1202
+
1203
+ pass
1204
+
1205
+
1206
+ class asinh(InverseHyperbolicFunction):
1207
+ """
1208
+ ``asinh(x)`` is the inverse hyperbolic sine of ``x``.
1209
+
1210
+ The inverse hyperbolic sine function.
1211
+
1212
+ Examples
1213
+ ========
1214
+
1215
+ >>> from sympy import asinh
1216
+ >>> from sympy.abc import x
1217
+ >>> asinh(x).diff(x)
1218
+ 1/sqrt(x**2 + 1)
1219
+ >>> asinh(1)
1220
+ log(1 + sqrt(2))
1221
+
1222
+ See Also
1223
+ ========
1224
+
1225
+ acosh, atanh, sinh
1226
+ """
1227
+
1228
+ def fdiff(self, argindex=1):
1229
+ if argindex == 1:
1230
+ return 1/sqrt(self.args[0]**2 + 1)
1231
+ else:
1232
+ raise ArgumentIndexError(self, argindex)
1233
+
1234
+ @classmethod
1235
+ def eval(cls, arg):
1236
+ if arg.is_Number:
1237
+ if arg is S.NaN:
1238
+ return S.NaN
1239
+ elif arg is S.Infinity:
1240
+ return S.Infinity
1241
+ elif arg is S.NegativeInfinity:
1242
+ return S.NegativeInfinity
1243
+ elif arg.is_zero:
1244
+ return S.Zero
1245
+ elif arg is S.One:
1246
+ return log(sqrt(2) + 1)
1247
+ elif arg is S.NegativeOne:
1248
+ return log(sqrt(2) - 1)
1249
+ elif arg.is_negative:
1250
+ return -cls(-arg)
1251
+ else:
1252
+ if arg is S.ComplexInfinity:
1253
+ return S.ComplexInfinity
1254
+
1255
+ if arg.is_zero:
1256
+ return S.Zero
1257
+
1258
+ i_coeff = _imaginary_unit_as_coefficient(arg)
1259
+
1260
+ if i_coeff is not None:
1261
+ return I * asin(i_coeff)
1262
+ else:
1263
+ if arg.could_extract_minus_sign():
1264
+ return -cls(-arg)
1265
+
1266
+ if isinstance(arg, sinh) and arg.args[0].is_number:
1267
+ z = arg.args[0]
1268
+ if z.is_real:
1269
+ return z
1270
+ r, i = match_real_imag(z)
1271
+ if r is not None and i is not None:
1272
+ f = floor((i + pi/2)/pi)
1273
+ m = z - I*pi*f
1274
+ even = f.is_even
1275
+ if even is True:
1276
+ return m
1277
+ elif even is False:
1278
+ return -m
1279
+
1280
+ @staticmethod
1281
+ @cacheit
1282
+ def taylor_term(n, x, *previous_terms):
1283
+ if n < 0 or n % 2 == 0:
1284
+ return S.Zero
1285
+ else:
1286
+ x = sympify(x)
1287
+ if len(previous_terms) >= 2 and n > 2:
1288
+ p = previous_terms[-2]
1289
+ return -p * (n - 2)**2/(n*(n - 1)) * x**2
1290
+ else:
1291
+ k = (n - 1) // 2
1292
+ R = RisingFactorial(S.Half, k)
1293
+ F = factorial(k)
1294
+ return S.NegativeOne**k * R / F * x**n / n
1295
+
1296
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # asinh
1297
+ arg = self.args[0]
1298
+ x0 = arg.subs(x, 0).cancel()
1299
+ if x0.is_zero:
1300
+ return arg.as_leading_term(x)
1301
+ # Handling branch points
1302
+ if x0 in (-I, I, S.ComplexInfinity):
1303
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1304
+ # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
1305
+ if (1 + x0**2).is_negative:
1306
+ ndir = arg.dir(x, cdir if cdir else 1)
1307
+ if re(ndir).is_positive:
1308
+ if im(x0).is_negative:
1309
+ return -self.func(x0) - I*pi
1310
+ elif re(ndir).is_negative:
1311
+ if im(x0).is_positive:
1312
+ return -self.func(x0) + I*pi
1313
+ else:
1314
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1315
+ return self.func(x0)
1316
+
1317
+ def _eval_nseries(self, x, n, logx, cdir=0): # asinh
1318
+ arg = self.args[0]
1319
+ arg0 = arg.subs(x, 0)
1320
+
1321
+ # Handling branch points
1322
+ if arg0 in (I, -I):
1323
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1324
+
1325
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1326
+ if arg0 is S.ComplexInfinity:
1327
+ return res
1328
+
1329
+ # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
1330
+ if (1 + arg0**2).is_negative:
1331
+ ndir = arg.dir(x, cdir if cdir else 1)
1332
+ if re(ndir).is_positive:
1333
+ if im(arg0).is_negative:
1334
+ return -res - I*pi
1335
+ elif re(ndir).is_negative:
1336
+ if im(arg0).is_positive:
1337
+ return -res + I*pi
1338
+ else:
1339
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1340
+ return res
1341
+
1342
+ def _eval_rewrite_as_log(self, x, **kwargs):
1343
+ return log(x + sqrt(x**2 + 1))
1344
+
1345
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1346
+
1347
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
1348
+ return atanh(x/sqrt(1 + x**2))
1349
+
1350
+ def _eval_rewrite_as_acosh(self, x, **kwargs):
1351
+ ix = I*x
1352
+ return I*(sqrt(1 - ix)/sqrt(ix - 1) * acosh(ix) - pi/2)
1353
+
1354
+ def _eval_rewrite_as_asin(self, x, **kwargs):
1355
+ return -I * asin(I * x)
1356
+
1357
+ def _eval_rewrite_as_acos(self, x, **kwargs):
1358
+ return I * acos(I * x) - I*pi/2
1359
+
1360
+ def inverse(self, argindex=1):
1361
+ """
1362
+ Returns the inverse of this function.
1363
+ """
1364
+ return sinh
1365
+
1366
+ def _eval_is_zero(self):
1367
+ return self.args[0].is_zero
1368
+
1369
+
1370
+ class acosh(InverseHyperbolicFunction):
1371
+ """
1372
+ ``acosh(x)`` is the inverse hyperbolic cosine of ``x``.
1373
+
1374
+ The inverse hyperbolic cosine function.
1375
+
1376
+ Examples
1377
+ ========
1378
+
1379
+ >>> from sympy import acosh
1380
+ >>> from sympy.abc import x
1381
+ >>> acosh(x).diff(x)
1382
+ 1/(sqrt(x - 1)*sqrt(x + 1))
1383
+ >>> acosh(1)
1384
+ 0
1385
+
1386
+ See Also
1387
+ ========
1388
+
1389
+ asinh, atanh, cosh
1390
+ """
1391
+
1392
+ def fdiff(self, argindex=1):
1393
+ if argindex == 1:
1394
+ arg = self.args[0]
1395
+ return 1/(sqrt(arg - 1)*sqrt(arg + 1))
1396
+ else:
1397
+ raise ArgumentIndexError(self, argindex)
1398
+
1399
+ @classmethod
1400
+ def eval(cls, arg):
1401
+ if arg.is_Number:
1402
+ if arg is S.NaN:
1403
+ return S.NaN
1404
+ elif arg is S.Infinity:
1405
+ return S.Infinity
1406
+ elif arg is S.NegativeInfinity:
1407
+ return S.Infinity
1408
+ elif arg.is_zero:
1409
+ return pi*I / 2
1410
+ elif arg is S.One:
1411
+ return S.Zero
1412
+ elif arg is S.NegativeOne:
1413
+ return pi*I
1414
+
1415
+ if arg.is_number:
1416
+ cst_table = _acosh_table()
1417
+
1418
+ if arg in cst_table:
1419
+ if arg.is_extended_real:
1420
+ return cst_table[arg]*I
1421
+ return cst_table[arg]
1422
+
1423
+ if arg is S.ComplexInfinity:
1424
+ return S.ComplexInfinity
1425
+ if arg == I*S.Infinity:
1426
+ return S.Infinity + I*pi/2
1427
+ if arg == -I*S.Infinity:
1428
+ return S.Infinity - I*pi/2
1429
+
1430
+ if arg.is_zero:
1431
+ return pi*I*S.Half
1432
+
1433
+ if isinstance(arg, cosh) and arg.args[0].is_number:
1434
+ z = arg.args[0]
1435
+ if z.is_real:
1436
+ return Abs(z)
1437
+ r, i = match_real_imag(z)
1438
+ if r is not None and i is not None:
1439
+ f = floor(i/pi)
1440
+ m = z - I*pi*f
1441
+ even = f.is_even
1442
+ if even is True:
1443
+ if r.is_nonnegative:
1444
+ return m
1445
+ elif r.is_negative:
1446
+ return -m
1447
+ elif even is False:
1448
+ m -= I*pi
1449
+ if r.is_nonpositive:
1450
+ return -m
1451
+ elif r.is_positive:
1452
+ return m
1453
+
1454
+ @staticmethod
1455
+ @cacheit
1456
+ def taylor_term(n, x, *previous_terms):
1457
+ if n == 0:
1458
+ return I*pi/2
1459
+ elif n < 0 or n % 2 == 0:
1460
+ return S.Zero
1461
+ else:
1462
+ x = sympify(x)
1463
+ if len(previous_terms) >= 2 and n > 2:
1464
+ p = previous_terms[-2]
1465
+ return p * (n - 2)**2/(n*(n - 1)) * x**2
1466
+ else:
1467
+ k = (n - 1) // 2
1468
+ R = RisingFactorial(S.Half, k)
1469
+ F = factorial(k)
1470
+ return -R / F * I * x**n / n
1471
+
1472
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # acosh
1473
+ arg = self.args[0]
1474
+ x0 = arg.subs(x, 0).cancel()
1475
+ # Handling branch points
1476
+ if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
1477
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1478
+ # Handling points lying on branch cuts (-oo, 1)
1479
+ if (x0 - 1).is_negative:
1480
+ ndir = arg.dir(x, cdir if cdir else 1)
1481
+ if im(ndir).is_negative:
1482
+ if (x0 + 1).is_negative:
1483
+ return self.func(x0) - 2*I*pi
1484
+ return -self.func(x0)
1485
+ elif not im(ndir).is_positive:
1486
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1487
+ return self.func(x0)
1488
+
1489
+ def _eval_nseries(self, x, n, logx, cdir=0): # acosh
1490
+ arg = self.args[0]
1491
+ arg0 = arg.subs(x, 0)
1492
+
1493
+ # Handling branch points
1494
+ if arg0 in (S.One, S.NegativeOne):
1495
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1496
+
1497
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1498
+ if arg0 is S.ComplexInfinity:
1499
+ return res
1500
+
1501
+ # Handling points lying on branch cuts (-oo, 1)
1502
+ if (arg0 - 1).is_negative:
1503
+ ndir = arg.dir(x, cdir if cdir else 1)
1504
+ if im(ndir).is_negative:
1505
+ if (arg0 + 1).is_negative:
1506
+ return res - 2*I*pi
1507
+ return -res
1508
+ elif not im(ndir).is_positive:
1509
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1510
+ return res
1511
+
1512
+ def _eval_rewrite_as_log(self, x, **kwargs):
1513
+ return log(x + sqrt(x + 1) * sqrt(x - 1))
1514
+
1515
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1516
+
1517
+ def _eval_rewrite_as_acos(self, x, **kwargs):
1518
+ return sqrt(x - 1)/sqrt(1 - x) * acos(x)
1519
+
1520
+ def _eval_rewrite_as_asin(self, x, **kwargs):
1521
+ return sqrt(x - 1)/sqrt(1 - x) * (pi/2 - asin(x))
1522
+
1523
+ def _eval_rewrite_as_asinh(self, x, **kwargs):
1524
+ return sqrt(x - 1)/sqrt(1 - x) * (pi/2 + I*asinh(I*x))
1525
+
1526
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
1527
+ sxm1 = sqrt(x - 1)
1528
+ s1mx = sqrt(1 - x)
1529
+ sx2m1 = sqrt(x**2 - 1)
1530
+ return (pi/2*sxm1/s1mx*(1 - x * sqrt(1/x**2)) +
1531
+ sxm1*sqrt(x + 1)/sx2m1 * atanh(sx2m1/x))
1532
+
1533
+ def inverse(self, argindex=1):
1534
+ """
1535
+ Returns the inverse of this function.
1536
+ """
1537
+ return cosh
1538
+
1539
+ def _eval_is_zero(self):
1540
+ if (self.args[0] - 1).is_zero:
1541
+ return True
1542
+
1543
+
1544
+ class atanh(InverseHyperbolicFunction):
1545
+ """
1546
+ ``atanh(x)`` is the inverse hyperbolic tangent of ``x``.
1547
+
1548
+ The inverse hyperbolic tangent function.
1549
+
1550
+ Examples
1551
+ ========
1552
+
1553
+ >>> from sympy import atanh
1554
+ >>> from sympy.abc import x
1555
+ >>> atanh(x).diff(x)
1556
+ 1/(1 - x**2)
1557
+
1558
+ See Also
1559
+ ========
1560
+
1561
+ asinh, acosh, tanh
1562
+ """
1563
+
1564
+ def fdiff(self, argindex=1):
1565
+ if argindex == 1:
1566
+ return 1/(1 - self.args[0]**2)
1567
+ else:
1568
+ raise ArgumentIndexError(self, argindex)
1569
+
1570
+ @classmethod
1571
+ def eval(cls, arg):
1572
+ if arg.is_Number:
1573
+ if arg is S.NaN:
1574
+ return S.NaN
1575
+ elif arg.is_zero:
1576
+ return S.Zero
1577
+ elif arg is S.One:
1578
+ return S.Infinity
1579
+ elif arg is S.NegativeOne:
1580
+ return S.NegativeInfinity
1581
+ elif arg is S.Infinity:
1582
+ return -I * atan(arg)
1583
+ elif arg is S.NegativeInfinity:
1584
+ return I * atan(-arg)
1585
+ elif arg.is_negative:
1586
+ return -cls(-arg)
1587
+ else:
1588
+ if arg is S.ComplexInfinity:
1589
+ from sympy.calculus.accumulationbounds import AccumBounds
1590
+ return I*AccumBounds(-pi/2, pi/2)
1591
+
1592
+ i_coeff = _imaginary_unit_as_coefficient(arg)
1593
+
1594
+ if i_coeff is not None:
1595
+ return I * atan(i_coeff)
1596
+ else:
1597
+ if arg.could_extract_minus_sign():
1598
+ return -cls(-arg)
1599
+
1600
+ if arg.is_zero:
1601
+ return S.Zero
1602
+
1603
+ if isinstance(arg, tanh) and arg.args[0].is_number:
1604
+ z = arg.args[0]
1605
+ if z.is_real:
1606
+ return z
1607
+ r, i = match_real_imag(z)
1608
+ if r is not None and i is not None:
1609
+ f = floor(2*i/pi)
1610
+ even = f.is_even
1611
+ m = z - I*f*pi/2
1612
+ if even is True:
1613
+ return m
1614
+ elif even is False:
1615
+ return m - I*pi/2
1616
+
1617
+ @staticmethod
1618
+ @cacheit
1619
+ def taylor_term(n, x, *previous_terms):
1620
+ if n < 0 or n % 2 == 0:
1621
+ return S.Zero
1622
+ else:
1623
+ x = sympify(x)
1624
+ return x**n / n
1625
+
1626
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # atanh
1627
+ arg = self.args[0]
1628
+ x0 = arg.subs(x, 0).cancel()
1629
+ if x0.is_zero:
1630
+ return arg.as_leading_term(x)
1631
+ # Handling branch points
1632
+ if x0 in (-S.One, S.One, S.ComplexInfinity):
1633
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1634
+ # Handling points lying on branch cuts (-oo, -1] U [1, oo)
1635
+ if (1 - x0**2).is_negative:
1636
+ ndir = arg.dir(x, cdir if cdir else 1)
1637
+ if im(ndir).is_negative:
1638
+ if x0.is_negative:
1639
+ return self.func(x0) - I*pi
1640
+ elif im(ndir).is_positive:
1641
+ if x0.is_positive:
1642
+ return self.func(x0) + I*pi
1643
+ else:
1644
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1645
+ return self.func(x0)
1646
+
1647
+ def _eval_nseries(self, x, n, logx, cdir=0): # atanh
1648
+ arg = self.args[0]
1649
+ arg0 = arg.subs(x, 0)
1650
+
1651
+ # Handling branch points
1652
+ if arg0 in (S.One, S.NegativeOne):
1653
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1654
+
1655
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1656
+ if arg0 is S.ComplexInfinity:
1657
+ return res
1658
+
1659
+ # Handling points lying on branch cuts (-oo, -1] U [1, oo)
1660
+ if (1 - arg0**2).is_negative:
1661
+ ndir = arg.dir(x, cdir if cdir else 1)
1662
+ if im(ndir).is_negative:
1663
+ if arg0.is_negative:
1664
+ return res - I*pi
1665
+ elif im(ndir).is_positive:
1666
+ if arg0.is_positive:
1667
+ return res + I*pi
1668
+ else:
1669
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1670
+ return res
1671
+
1672
+ def _eval_rewrite_as_log(self, x, **kwargs):
1673
+ return (log(1 + x) - log(1 - x)) / 2
1674
+
1675
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1676
+
1677
+ def _eval_rewrite_as_asinh(self, x, **kwargs):
1678
+ f = sqrt(1/(x**2 - 1))
1679
+ return (pi*x/(2*sqrt(-x**2)) -
1680
+ sqrt(-x)*sqrt(1 - x**2)/sqrt(x)*f*asinh(f))
1681
+
1682
+ def _eval_is_zero(self):
1683
+ if self.args[0].is_zero:
1684
+ return True
1685
+
1686
+ def _eval_is_imaginary(self):
1687
+ return self.args[0].is_imaginary
1688
+
1689
+ def inverse(self, argindex=1):
1690
+ """
1691
+ Returns the inverse of this function.
1692
+ """
1693
+ return tanh
1694
+
1695
+
1696
+ class acoth(InverseHyperbolicFunction):
1697
+ """
1698
+ ``acoth(x)`` is the inverse hyperbolic cotangent of ``x``.
1699
+
1700
+ The inverse hyperbolic cotangent function.
1701
+
1702
+ Examples
1703
+ ========
1704
+
1705
+ >>> from sympy import acoth
1706
+ >>> from sympy.abc import x
1707
+ >>> acoth(x).diff(x)
1708
+ 1/(1 - x**2)
1709
+
1710
+ See Also
1711
+ ========
1712
+
1713
+ asinh, acosh, coth
1714
+ """
1715
+
1716
+ def fdiff(self, argindex=1):
1717
+ if argindex == 1:
1718
+ return 1/(1 - self.args[0]**2)
1719
+ else:
1720
+ raise ArgumentIndexError(self, argindex)
1721
+
1722
+ @classmethod
1723
+ def eval(cls, arg):
1724
+ if arg.is_Number:
1725
+ if arg is S.NaN:
1726
+ return S.NaN
1727
+ elif arg is S.Infinity:
1728
+ return S.Zero
1729
+ elif arg is S.NegativeInfinity:
1730
+ return S.Zero
1731
+ elif arg.is_zero:
1732
+ return pi*I / 2
1733
+ elif arg is S.One:
1734
+ return S.Infinity
1735
+ elif arg is S.NegativeOne:
1736
+ return S.NegativeInfinity
1737
+ elif arg.is_negative:
1738
+ return -cls(-arg)
1739
+ else:
1740
+ if arg is S.ComplexInfinity:
1741
+ return S.Zero
1742
+
1743
+ i_coeff = _imaginary_unit_as_coefficient(arg)
1744
+
1745
+ if i_coeff is not None:
1746
+ return -I * acot(i_coeff)
1747
+ else:
1748
+ if arg.could_extract_minus_sign():
1749
+ return -cls(-arg)
1750
+
1751
+ if arg.is_zero:
1752
+ return pi*I*S.Half
1753
+
1754
+ @staticmethod
1755
+ @cacheit
1756
+ def taylor_term(n, x, *previous_terms):
1757
+ if n == 0:
1758
+ return -I*pi/2
1759
+ elif n < 0 or n % 2 == 0:
1760
+ return S.Zero
1761
+ else:
1762
+ x = sympify(x)
1763
+ return x**n / n
1764
+
1765
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # acoth
1766
+ arg = self.args[0]
1767
+ x0 = arg.subs(x, 0).cancel()
1768
+ if x0 is S.ComplexInfinity:
1769
+ return (1/arg).as_leading_term(x)
1770
+ # Handling branch points
1771
+ if x0 in (-S.One, S.One, S.Zero):
1772
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1773
+ # Handling points lying on branch cuts [-1, 1]
1774
+ if x0.is_real and (1 - x0**2).is_positive:
1775
+ ndir = arg.dir(x, cdir if cdir else 1)
1776
+ if im(ndir).is_negative:
1777
+ if x0.is_positive:
1778
+ return self.func(x0) + I*pi
1779
+ elif im(ndir).is_positive:
1780
+ if x0.is_negative:
1781
+ return self.func(x0) - I*pi
1782
+ else:
1783
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1784
+ return self.func(x0)
1785
+
1786
+ def _eval_nseries(self, x, n, logx, cdir=0): # acoth
1787
+ arg = self.args[0]
1788
+ arg0 = arg.subs(x, 0)
1789
+
1790
+ # Handling branch points
1791
+ if arg0 in (S.One, S.NegativeOne):
1792
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1793
+
1794
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1795
+ if arg0 is S.ComplexInfinity:
1796
+ return res
1797
+
1798
+ # Handling points lying on branch cuts [-1, 1]
1799
+ if arg0.is_real and (1 - arg0**2).is_positive:
1800
+ ndir = arg.dir(x, cdir if cdir else 1)
1801
+ if im(ndir).is_negative:
1802
+ if arg0.is_positive:
1803
+ return res + I*pi
1804
+ elif im(ndir).is_positive:
1805
+ if arg0.is_negative:
1806
+ return res - I*pi
1807
+ else:
1808
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1809
+ return res
1810
+
1811
+ def _eval_rewrite_as_log(self, x, **kwargs):
1812
+ return (log(1 + 1/x) - log(1 - 1/x)) / 2
1813
+
1814
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1815
+
1816
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
1817
+ return atanh(1/x)
1818
+
1819
+ def _eval_rewrite_as_asinh(self, x, **kwargs):
1820
+ return (pi*I/2*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(1 + 1/x)*sqrt(x/(x + 1))) +
1821
+ x*sqrt(1/x**2)*asinh(sqrt(1/(x**2 - 1))))
1822
+
1823
+ def inverse(self, argindex=1):
1824
+ """
1825
+ Returns the inverse of this function.
1826
+ """
1827
+ return coth
1828
+
1829
+
1830
+ class asech(InverseHyperbolicFunction):
1831
+ """
1832
+ ``asech(x)`` is the inverse hyperbolic secant of ``x``.
1833
+
1834
+ The inverse hyperbolic secant function.
1835
+
1836
+ Examples
1837
+ ========
1838
+
1839
+ >>> from sympy import asech, sqrt, S
1840
+ >>> from sympy.abc import x
1841
+ >>> asech(x).diff(x)
1842
+ -1/(x*sqrt(1 - x**2))
1843
+ >>> asech(1).diff(x)
1844
+ 0
1845
+ >>> asech(1)
1846
+ 0
1847
+ >>> asech(S(2))
1848
+ I*pi/3
1849
+ >>> asech(-sqrt(2))
1850
+ 3*I*pi/4
1851
+ >>> asech((sqrt(6) - sqrt(2)))
1852
+ I*pi/12
1853
+
1854
+ See Also
1855
+ ========
1856
+
1857
+ asinh, atanh, cosh, acoth
1858
+
1859
+ References
1860
+ ==========
1861
+
1862
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
1863
+ .. [2] https://dlmf.nist.gov/4.37
1864
+ .. [3] https://functions.wolfram.com/ElementaryFunctions/ArcSech/
1865
+
1866
+ """
1867
+
1868
+ def fdiff(self, argindex=1):
1869
+ if argindex == 1:
1870
+ z = self.args[0]
1871
+ return -1/(z*sqrt(1 - z**2))
1872
+ else:
1873
+ raise ArgumentIndexError(self, argindex)
1874
+
1875
+ @classmethod
1876
+ def eval(cls, arg):
1877
+ if arg.is_Number:
1878
+ if arg is S.NaN:
1879
+ return S.NaN
1880
+ elif arg is S.Infinity:
1881
+ return pi*I / 2
1882
+ elif arg is S.NegativeInfinity:
1883
+ return pi*I / 2
1884
+ elif arg.is_zero:
1885
+ return S.Infinity
1886
+ elif arg is S.One:
1887
+ return S.Zero
1888
+ elif arg is S.NegativeOne:
1889
+ return pi*I
1890
+
1891
+ if arg.is_number:
1892
+ cst_table = _asech_table()
1893
+
1894
+ if arg in cst_table:
1895
+ if arg.is_extended_real:
1896
+ return cst_table[arg]*I
1897
+ return cst_table[arg]
1898
+
1899
+ if arg is S.ComplexInfinity:
1900
+ from sympy.calculus.accumulationbounds import AccumBounds
1901
+ return I*AccumBounds(-pi/2, pi/2)
1902
+
1903
+ if arg.is_zero:
1904
+ return S.Infinity
1905
+
1906
+ @staticmethod
1907
+ @cacheit
1908
+ def taylor_term(n, x, *previous_terms):
1909
+ if n == 0:
1910
+ return log(2 / x)
1911
+ elif n < 0 or n % 2 == 1:
1912
+ return S.Zero
1913
+ else:
1914
+ x = sympify(x)
1915
+ if len(previous_terms) > 2 and n > 2:
1916
+ p = previous_terms[-2]
1917
+ return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
1918
+ else:
1919
+ k = n // 2
1920
+ R = RisingFactorial(S.Half, k) * n
1921
+ F = factorial(k) * n // 2 * n // 2
1922
+ return -1 * R / F * x**n / 4
1923
+
1924
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # asech
1925
+ arg = self.args[0]
1926
+ x0 = arg.subs(x, 0).cancel()
1927
+ # Handling branch points
1928
+ if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
1929
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1930
+ # Handling points lying on branch cuts (-oo, 0] U (1, oo)
1931
+ if x0.is_negative or (1 - x0).is_negative:
1932
+ ndir = arg.dir(x, cdir if cdir else 1)
1933
+ if im(ndir).is_positive:
1934
+ if x0.is_positive or (x0 + 1).is_negative:
1935
+ return -self.func(x0)
1936
+ return self.func(x0) - 2*I*pi
1937
+ elif not im(ndir).is_negative:
1938
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1939
+ return self.func(x0)
1940
+
1941
+ def _eval_nseries(self, x, n, logx, cdir=0): # asech
1942
+ from sympy.series.order import O
1943
+ arg = self.args[0]
1944
+ arg0 = arg.subs(x, 0)
1945
+
1946
+ # Handling branch points
1947
+ if arg0 is S.One:
1948
+ t = Dummy('t', positive=True)
1949
+ ser = asech(S.One - t**2).rewrite(log).nseries(t, 0, 2*n)
1950
+ arg1 = S.One - self.args[0]
1951
+ f = arg1.as_leading_term(x)
1952
+ g = (arg1 - f)/ f
1953
+ if not g.is_meromorphic(x, 0): # cannot be expanded
1954
+ return O(1) if n == 0 else O(sqrt(x))
1955
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
1956
+ res = (res1.removeO()*sqrt(f)).expand()
1957
+ return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
1958
+
1959
+ if arg0 is S.NegativeOne:
1960
+ t = Dummy('t', positive=True)
1961
+ ser = asech(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n)
1962
+ arg1 = S.One + self.args[0]
1963
+ f = arg1.as_leading_term(x)
1964
+ g = (arg1 - f)/ f
1965
+ if not g.is_meromorphic(x, 0): # cannot be expanded
1966
+ return O(1) if n == 0 else I*pi + O(sqrt(x))
1967
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
1968
+ res = (res1.removeO()*sqrt(f)).expand()
1969
+ return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
1970
+
1971
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1972
+ if arg0 is S.ComplexInfinity:
1973
+ return res
1974
+
1975
+ # Handling points lying on branch cuts (-oo, 0] U (1, oo)
1976
+ if arg0.is_negative or (1 - arg0).is_negative:
1977
+ ndir = arg.dir(x, cdir if cdir else 1)
1978
+ if im(ndir).is_positive:
1979
+ if arg0.is_positive or (arg0 + 1).is_negative:
1980
+ return -res
1981
+ return res - 2*I*pi
1982
+ elif not im(ndir).is_negative:
1983
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1984
+ return res
1985
+
1986
+ def inverse(self, argindex=1):
1987
+ """
1988
+ Returns the inverse of this function.
1989
+ """
1990
+ return sech
1991
+
1992
+ def _eval_rewrite_as_log(self, arg, **kwargs):
1993
+ return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1))
1994
+
1995
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1996
+
1997
+ def _eval_rewrite_as_acosh(self, arg, **kwargs):
1998
+ return acosh(1/arg)
1999
+
2000
+ def _eval_rewrite_as_asinh(self, arg, **kwargs):
2001
+ return sqrt(1/arg - 1)/sqrt(1 - 1/arg)*(I*asinh(I/arg)
2002
+ + pi*S.Half)
2003
+
2004
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
2005
+ return (I*pi*(1 - sqrt(x)*sqrt(1/x) - I/2*sqrt(-x)/sqrt(x) - I/2*sqrt(x**2)/sqrt(-x**2))
2006
+ + sqrt(1/(x + 1))*sqrt(x + 1)*atanh(sqrt(1 - x**2)))
2007
+
2008
+ def _eval_rewrite_as_acsch(self, x, **kwargs):
2009
+ return sqrt(1/x - 1)/sqrt(1 - 1/x)*(pi/2 - I*acsch(I*x))
2010
+
2011
+
2012
+ class acsch(InverseHyperbolicFunction):
2013
+ """
2014
+ ``acsch(x)`` is the inverse hyperbolic cosecant of ``x``.
2015
+
2016
+ The inverse hyperbolic cosecant function.
2017
+
2018
+ Examples
2019
+ ========
2020
+
2021
+ >>> from sympy import acsch, sqrt, I
2022
+ >>> from sympy.abc import x
2023
+ >>> acsch(x).diff(x)
2024
+ -1/(x**2*sqrt(1 + x**(-2)))
2025
+ >>> acsch(1).diff(x)
2026
+ 0
2027
+ >>> acsch(1)
2028
+ log(1 + sqrt(2))
2029
+ >>> acsch(I)
2030
+ -I*pi/2
2031
+ >>> acsch(-2*I)
2032
+ I*pi/6
2033
+ >>> acsch(I*(sqrt(6) - sqrt(2)))
2034
+ -5*I*pi/12
2035
+
2036
+ See Also
2037
+ ========
2038
+
2039
+ asinh
2040
+
2041
+ References
2042
+ ==========
2043
+
2044
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
2045
+ .. [2] https://dlmf.nist.gov/4.37
2046
+ .. [3] https://functions.wolfram.com/ElementaryFunctions/ArcCsch/
2047
+
2048
+ """
2049
+
2050
+ def fdiff(self, argindex=1):
2051
+ if argindex == 1:
2052
+ z = self.args[0]
2053
+ return -1/(z**2*sqrt(1 + 1/z**2))
2054
+ else:
2055
+ raise ArgumentIndexError(self, argindex)
2056
+
2057
+ @classmethod
2058
+ def eval(cls, arg):
2059
+ if arg.is_Number:
2060
+ if arg is S.NaN:
2061
+ return S.NaN
2062
+ elif arg is S.Infinity:
2063
+ return S.Zero
2064
+ elif arg is S.NegativeInfinity:
2065
+ return S.Zero
2066
+ elif arg.is_zero:
2067
+ return S.ComplexInfinity
2068
+ elif arg is S.One:
2069
+ return log(1 + sqrt(2))
2070
+ elif arg is S.NegativeOne:
2071
+ return - log(1 + sqrt(2))
2072
+
2073
+ if arg.is_number:
2074
+ cst_table = _acsch_table()
2075
+
2076
+ if arg in cst_table:
2077
+ return cst_table[arg]*I
2078
+
2079
+ if arg is S.ComplexInfinity:
2080
+ return S.Zero
2081
+
2082
+ if arg.is_infinite:
2083
+ return S.Zero
2084
+
2085
+ if arg.is_zero:
2086
+ return S.ComplexInfinity
2087
+
2088
+ if arg.could_extract_minus_sign():
2089
+ return -cls(-arg)
2090
+
2091
+ @staticmethod
2092
+ @cacheit
2093
+ def taylor_term(n, x, *previous_terms):
2094
+ if n == 0:
2095
+ return log(2 / x)
2096
+ elif n < 0 or n % 2 == 1:
2097
+ return S.Zero
2098
+ else:
2099
+ x = sympify(x)
2100
+ if len(previous_terms) > 2 and n > 2:
2101
+ p = previous_terms[-2]
2102
+ return -p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
2103
+ else:
2104
+ k = n // 2
2105
+ R = RisingFactorial(S.Half, k) * n
2106
+ F = factorial(k) * n // 2 * n // 2
2107
+ return S.NegativeOne**(k +1) * R / F * x**n / 4
2108
+
2109
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsch
2110
+ arg = self.args[0]
2111
+ x0 = arg.subs(x, 0).cancel()
2112
+ # Handling branch points
2113
+ if x0 in (-I, I, S.Zero):
2114
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
2115
+ if x0 is S.ComplexInfinity:
2116
+ return (1/arg).as_leading_term(x)
2117
+ # Handling points lying on branch cuts (-I, I)
2118
+ if x0.is_imaginary and (1 + x0**2).is_positive:
2119
+ ndir = arg.dir(x, cdir if cdir else 1)
2120
+ if re(ndir).is_positive:
2121
+ if im(x0).is_positive:
2122
+ return -self.func(x0) - I*pi
2123
+ elif re(ndir).is_negative:
2124
+ if im(x0).is_negative:
2125
+ return -self.func(x0) + I*pi
2126
+ else:
2127
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
2128
+ return self.func(x0)
2129
+
2130
+ def _eval_nseries(self, x, n, logx, cdir=0): # acsch
2131
+ from sympy.series.order import O
2132
+ arg = self.args[0]
2133
+ arg0 = arg.subs(x, 0)
2134
+
2135
+ # Handling branch points
2136
+ if arg0 is I:
2137
+ t = Dummy('t', positive=True)
2138
+ ser = acsch(I + t**2).rewrite(log).nseries(t, 0, 2*n)
2139
+ arg1 = -I + self.args[0]
2140
+ f = arg1.as_leading_term(x)
2141
+ g = (arg1 - f)/ f
2142
+ if not g.is_meromorphic(x, 0): # cannot be expanded
2143
+ return O(1) if n == 0 else -I*pi/2 + O(sqrt(x))
2144
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
2145
+ res = (res1.removeO()*sqrt(f)).expand()
2146
+ res = ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
2147
+ return res
2148
+
2149
+ if arg0 == S.NegativeOne*I:
2150
+ t = Dummy('t', positive=True)
2151
+ ser = acsch(-I + t**2).rewrite(log).nseries(t, 0, 2*n)
2152
+ arg1 = I + self.args[0]
2153
+ f = arg1.as_leading_term(x)
2154
+ g = (arg1 - f)/ f
2155
+ if not g.is_meromorphic(x, 0): # cannot be expanded
2156
+ return O(1) if n == 0 else I*pi/2 + O(sqrt(x))
2157
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
2158
+ res = (res1.removeO()*sqrt(f)).expand()
2159
+ return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
2160
+
2161
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
2162
+ if arg0 is S.ComplexInfinity:
2163
+ return res
2164
+
2165
+ # Handling points lying on branch cuts (-I, I)
2166
+ if arg0.is_imaginary and (1 + arg0**2).is_positive:
2167
+ ndir = self.args[0].dir(x, cdir if cdir else 1)
2168
+ if re(ndir).is_positive:
2169
+ if im(arg0).is_positive:
2170
+ return -res - I*pi
2171
+ elif re(ndir).is_negative:
2172
+ if im(arg0).is_negative:
2173
+ return -res + I*pi
2174
+ else:
2175
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
2176
+ return res
2177
+
2178
+ def inverse(self, argindex=1):
2179
+ """
2180
+ Returns the inverse of this function.
2181
+ """
2182
+ return csch
2183
+
2184
+ def _eval_rewrite_as_log(self, arg, **kwargs):
2185
+ return log(1/arg + sqrt(1/arg**2 + 1))
2186
+
2187
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
2188
+
2189
+ def _eval_rewrite_as_asinh(self, arg, **kwargs):
2190
+ return asinh(1/arg)
2191
+
2192
+ def _eval_rewrite_as_acosh(self, arg, **kwargs):
2193
+ return I*(sqrt(1 - I/arg)/sqrt(I/arg - 1)*
2194
+ acosh(I/arg) - pi*S.Half)
2195
+
2196
+ def _eval_rewrite_as_atanh(self, arg, **kwargs):
2197
+ arg2 = arg**2
2198
+ arg2p1 = arg2 + 1
2199
+ return sqrt(-arg2)/arg*(pi*S.Half -
2200
+ sqrt(-arg2p1**2)/arg2p1*atanh(sqrt(arg2p1)))
2201
+
2202
+ def _eval_is_zero(self):
2203
+ return self.args[0].is_infinite
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Function, S, sympify, NumberKind
2
+ from sympy.utilities.iterables import sift
3
+ from sympy.core.add import Add
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.operations import LatticeOp, ShortCircuit
6
+ from sympy.core.function import (Application, Lambda,
7
+ ArgumentIndexError)
8
+ from sympy.core.expr import Expr
9
+ from sympy.core.exprtools import factor_terms
10
+ from sympy.core.mod import Mod
11
+ from sympy.core.mul import Mul
12
+ from sympy.core.numbers import Rational
13
+ from sympy.core.power import Pow
14
+ from sympy.core.relational import Eq, Relational
15
+ from sympy.core.singleton import Singleton
16
+ from sympy.core.sorting import ordered
17
+ from sympy.core.symbol import Dummy
18
+ from sympy.core.rules import Transform
19
+ from sympy.core.logic import fuzzy_and, fuzzy_or, _torf
20
+ from sympy.core.traversal import walk
21
+ from sympy.core.numbers import Integer
22
+ from sympy.logic.boolalg import And, Or
23
+
24
+
25
+ def _minmax_as_Piecewise(op, *args):
26
+ # helper for Min/Max rewrite as Piecewise
27
+ from sympy.functions.elementary.piecewise import Piecewise
28
+ ec = []
29
+ for i, a in enumerate(args):
30
+ c = [Relational(a, args[j], op) for j in range(i + 1, len(args))]
31
+ ec.append((a, And(*c)))
32
+ return Piecewise(*ec)
33
+
34
+
35
+ class IdentityFunction(Lambda, metaclass=Singleton):
36
+ """
37
+ The identity function
38
+
39
+ Examples
40
+ ========
41
+
42
+ >>> from sympy import Id, Symbol
43
+ >>> x = Symbol('x')
44
+ >>> Id(x)
45
+ x
46
+
47
+ """
48
+
49
+ _symbol = Dummy('x')
50
+
51
+ @property
52
+ def signature(self):
53
+ return Tuple(self._symbol)
54
+
55
+ @property
56
+ def expr(self):
57
+ return self._symbol
58
+
59
+
60
+ Id = S.IdentityFunction
61
+
62
+ ###############################################################################
63
+ ############################# ROOT and SQUARE ROOT FUNCTION ###################
64
+ ###############################################################################
65
+
66
+
67
+ def sqrt(arg, evaluate=None):
68
+ """Returns the principal square root.
69
+
70
+ Parameters
71
+ ==========
72
+
73
+ evaluate : bool, optional
74
+ The parameter determines if the expression should be evaluated.
75
+ If ``None``, its value is taken from
76
+ ``global_parameters.evaluate``.
77
+
78
+ Examples
79
+ ========
80
+
81
+ >>> from sympy import sqrt, Symbol, S
82
+ >>> x = Symbol('x')
83
+
84
+ >>> sqrt(x)
85
+ sqrt(x)
86
+
87
+ >>> sqrt(x)**2
88
+ x
89
+
90
+ Note that sqrt(x**2) does not simplify to x.
91
+
92
+ >>> sqrt(x**2)
93
+ sqrt(x**2)
94
+
95
+ This is because the two are not equal to each other in general.
96
+ For example, consider x == -1:
97
+
98
+ >>> from sympy import Eq
99
+ >>> Eq(sqrt(x**2), x).subs(x, -1)
100
+ False
101
+
102
+ This is because sqrt computes the principal square root, so the square may
103
+ put the argument in a different branch. This identity does hold if x is
104
+ positive:
105
+
106
+ >>> y = Symbol('y', positive=True)
107
+ >>> sqrt(y**2)
108
+ y
109
+
110
+ You can force this simplification by using the powdenest() function with
111
+ the force option set to True:
112
+
113
+ >>> from sympy import powdenest
114
+ >>> sqrt(x**2)
115
+ sqrt(x**2)
116
+ >>> powdenest(sqrt(x**2), force=True)
117
+ x
118
+
119
+ To get both branches of the square root you can use the rootof function:
120
+
121
+ >>> from sympy import rootof
122
+
123
+ >>> [rootof(x**2-3,i) for i in (0,1)]
124
+ [-sqrt(3), sqrt(3)]
125
+
126
+ Although ``sqrt`` is printed, there is no ``sqrt`` function so looking for
127
+ ``sqrt`` in an expression will fail:
128
+
129
+ >>> from sympy.utilities.misc import func_name
130
+ >>> func_name(sqrt(x))
131
+ 'Pow'
132
+ >>> sqrt(x).has(sqrt)
133
+ False
134
+
135
+ To find ``sqrt`` look for ``Pow`` with an exponent of ``1/2``:
136
+
137
+ >>> (x + 1/sqrt(x)).find(lambda i: i.is_Pow and abs(i.exp) is S.Half)
138
+ {1/sqrt(x)}
139
+
140
+ See Also
141
+ ========
142
+
143
+ sympy.polys.rootoftools.rootof, root, real_root
144
+
145
+ References
146
+ ==========
147
+
148
+ .. [1] https://en.wikipedia.org/wiki/Square_root
149
+ .. [2] https://en.wikipedia.org/wiki/Principal_value
150
+ """
151
+ # arg = sympify(arg) is handled by Pow
152
+ return Pow(arg, S.Half, evaluate=evaluate)
153
+
154
+
155
+ def cbrt(arg, evaluate=None):
156
+ """Returns the principal cube root.
157
+
158
+ Parameters
159
+ ==========
160
+
161
+ evaluate : bool, optional
162
+ The parameter determines if the expression should be evaluated.
163
+ If ``None``, its value is taken from
164
+ ``global_parameters.evaluate``.
165
+
166
+ Examples
167
+ ========
168
+
169
+ >>> from sympy import cbrt, Symbol
170
+ >>> x = Symbol('x')
171
+
172
+ >>> cbrt(x)
173
+ x**(1/3)
174
+
175
+ >>> cbrt(x)**3
176
+ x
177
+
178
+ Note that cbrt(x**3) does not simplify to x.
179
+
180
+ >>> cbrt(x**3)
181
+ (x**3)**(1/3)
182
+
183
+ This is because the two are not equal to each other in general.
184
+ For example, consider `x == -1`:
185
+
186
+ >>> from sympy import Eq
187
+ >>> Eq(cbrt(x**3), x).subs(x, -1)
188
+ False
189
+
190
+ This is because cbrt computes the principal cube root, this
191
+ identity does hold if `x` is positive:
192
+
193
+ >>> y = Symbol('y', positive=True)
194
+ >>> cbrt(y**3)
195
+ y
196
+
197
+ See Also
198
+ ========
199
+
200
+ sympy.polys.rootoftools.rootof, root, real_root
201
+
202
+ References
203
+ ==========
204
+
205
+ .. [1] https://en.wikipedia.org/wiki/Cube_root
206
+ .. [2] https://en.wikipedia.org/wiki/Principal_value
207
+
208
+ """
209
+ return Pow(arg, Rational(1, 3), evaluate=evaluate)
210
+
211
+
212
+ def root(arg, n, k=0, evaluate=None):
213
+ r"""Returns the *k*-th *n*-th root of ``arg``.
214
+
215
+ Parameters
216
+ ==========
217
+
218
+ k : int, optional
219
+ Should be an integer in $\{0, 1, ..., n-1\}$.
220
+ Defaults to the principal root if $0$.
221
+
222
+ evaluate : bool, optional
223
+ The parameter determines if the expression should be evaluated.
224
+ If ``None``, its value is taken from
225
+ ``global_parameters.evaluate``.
226
+
227
+ Examples
228
+ ========
229
+
230
+ >>> from sympy import root, Rational
231
+ >>> from sympy.abc import x, n
232
+
233
+ >>> root(x, 2)
234
+ sqrt(x)
235
+
236
+ >>> root(x, 3)
237
+ x**(1/3)
238
+
239
+ >>> root(x, n)
240
+ x**(1/n)
241
+
242
+ >>> root(x, -Rational(2, 3))
243
+ x**(-3/2)
244
+
245
+ To get the k-th n-th root, specify k:
246
+
247
+ >>> root(-2, 3, 2)
248
+ -(-1)**(2/3)*2**(1/3)
249
+
250
+ To get all n n-th roots you can use the rootof function.
251
+ The following examples show the roots of unity for n
252
+ equal 2, 3 and 4:
253
+
254
+ >>> from sympy import rootof
255
+
256
+ >>> [rootof(x**2 - 1, i) for i in range(2)]
257
+ [-1, 1]
258
+
259
+ >>> [rootof(x**3 - 1,i) for i in range(3)]
260
+ [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
261
+
262
+ >>> [rootof(x**4 - 1,i) for i in range(4)]
263
+ [-1, 1, -I, I]
264
+
265
+ SymPy, like other symbolic algebra systems, returns the
266
+ complex root of negative numbers. This is the principal
267
+ root and differs from the text-book result that one might
268
+ be expecting. For example, the cube root of -8 does not
269
+ come back as -2:
270
+
271
+ >>> root(-8, 3)
272
+ 2*(-1)**(1/3)
273
+
274
+ The real_root function can be used to either make the principal
275
+ result real (or simply to return the real root directly):
276
+
277
+ >>> from sympy import real_root
278
+ >>> real_root(_)
279
+ -2
280
+ >>> real_root(-32, 5)
281
+ -2
282
+
283
+ Alternatively, the n//2-th n-th root of a negative number can be
284
+ computed with root:
285
+
286
+ >>> root(-32, 5, 5//2)
287
+ -2
288
+
289
+ See Also
290
+ ========
291
+
292
+ sympy.polys.rootoftools.rootof
293
+ sympy.core.power.integer_nthroot
294
+ sqrt, real_root
295
+
296
+ References
297
+ ==========
298
+
299
+ .. [1] https://en.wikipedia.org/wiki/Square_root
300
+ .. [2] https://en.wikipedia.org/wiki/Real_root
301
+ .. [3] https://en.wikipedia.org/wiki/Root_of_unity
302
+ .. [4] https://en.wikipedia.org/wiki/Principal_value
303
+ .. [5] https://mathworld.wolfram.com/CubeRoot.html
304
+
305
+ """
306
+ n = sympify(n)
307
+ if k:
308
+ return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate)
309
+ return Pow(arg, 1/n, evaluate=evaluate)
310
+
311
+
312
+ def real_root(arg, n=None, evaluate=None):
313
+ r"""Return the real *n*'th-root of *arg* if possible.
314
+
315
+ Parameters
316
+ ==========
317
+
318
+ n : int or None, optional
319
+ If *n* is ``None``, then all instances of
320
+ $(-n)^{1/\text{odd}}$ will be changed to $-n^{1/\text{odd}}$.
321
+ This will only create a real root of a principal root.
322
+ The presence of other factors may cause the result to not be
323
+ real.
324
+
325
+ evaluate : bool, optional
326
+ The parameter determines if the expression should be evaluated.
327
+ If ``None``, its value is taken from
328
+ ``global_parameters.evaluate``.
329
+
330
+ Examples
331
+ ========
332
+
333
+ >>> from sympy import root, real_root
334
+
335
+ >>> real_root(-8, 3)
336
+ -2
337
+ >>> root(-8, 3)
338
+ 2*(-1)**(1/3)
339
+ >>> real_root(_)
340
+ -2
341
+
342
+ If one creates a non-principal root and applies real_root, the
343
+ result will not be real (so use with caution):
344
+
345
+ >>> root(-8, 3, 2)
346
+ -2*(-1)**(2/3)
347
+ >>> real_root(_)
348
+ -2*(-1)**(2/3)
349
+
350
+ See Also
351
+ ========
352
+
353
+ sympy.polys.rootoftools.rootof
354
+ sympy.core.power.integer_nthroot
355
+ root, sqrt
356
+ """
357
+ from sympy.functions.elementary.complexes import Abs, im, sign
358
+ from sympy.functions.elementary.piecewise import Piecewise
359
+ if n is not None:
360
+ return Piecewise(
361
+ (root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
362
+ (Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),
363
+ And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
364
+ (root(arg, n, evaluate=evaluate), True))
365
+ rv = sympify(arg)
366
+ n1pow = Transform(lambda x: -(-x.base)**x.exp,
367
+ lambda x:
368
+ x.is_Pow and
369
+ x.base.is_negative and
370
+ x.exp.is_Rational and
371
+ x.exp.p == 1 and x.exp.q % 2)
372
+ return rv.xreplace(n1pow)
373
+
374
+ ###############################################################################
375
+ ############################# MINIMUM and MAXIMUM #############################
376
+ ###############################################################################
377
+
378
+
379
+ class MinMaxBase(Expr, LatticeOp):
380
+ def __new__(cls, *args, **assumptions):
381
+ from sympy.core.parameters import global_parameters
382
+ evaluate = assumptions.pop('evaluate', global_parameters.evaluate)
383
+ args = (sympify(arg) for arg in args)
384
+
385
+ # first standard filter, for cls.zero and cls.identity
386
+ # also reshape Max(a, Max(b, c)) to Max(a, b, c)
387
+
388
+ if evaluate:
389
+ try:
390
+ args = frozenset(cls._new_args_filter(args))
391
+ except ShortCircuit:
392
+ return cls.zero
393
+ # remove redundant args that are easily identified
394
+ args = cls._collapse_arguments(args, **assumptions)
395
+ # find local zeros
396
+ args = cls._find_localzeros(args, **assumptions)
397
+ args = frozenset(args)
398
+
399
+ if not args:
400
+ return cls.identity
401
+
402
+ if len(args) == 1:
403
+ return list(args).pop()
404
+
405
+ # base creation
406
+ obj = Expr.__new__(cls, *ordered(args), **assumptions)
407
+ obj._argset = args
408
+ return obj
409
+
410
+ @classmethod
411
+ def _collapse_arguments(cls, args, **assumptions):
412
+ """Remove redundant args.
413
+
414
+ Examples
415
+ ========
416
+
417
+ >>> from sympy import Min, Max
418
+ >>> from sympy.abc import a, b, c, d, e
419
+
420
+ Any arg in parent that appears in any
421
+ parent-like function in any of the flat args
422
+ of parent can be removed from that sub-arg:
423
+
424
+ >>> Min(a, Max(b, Min(a, c, d)))
425
+ Min(a, Max(b, Min(c, d)))
426
+
427
+ If the arg of parent appears in an opposite-than parent
428
+ function in any of the flat args of parent that function
429
+ can be replaced with the arg:
430
+
431
+ >>> Min(a, Max(b, Min(c, d, Max(a, e))))
432
+ Min(a, Max(b, Min(a, c, d)))
433
+ """
434
+ if not args:
435
+ return args
436
+ args = list(ordered(args))
437
+ if cls == Min:
438
+ other = Max
439
+ else:
440
+ other = Min
441
+
442
+ # find global comparable max of Max and min of Min if a new
443
+ # value is being introduced in these args at position 0 of
444
+ # the ordered args
445
+ if args[0].is_number:
446
+ sifted = mins, maxs = [], []
447
+ for i in args:
448
+ for v in walk(i, Min, Max):
449
+ if v.args[0].is_comparable:
450
+ sifted[isinstance(v, Max)].append(v)
451
+ small = Min.identity
452
+ for i in mins:
453
+ v = i.args[0]
454
+ if v.is_number and (v < small) == True:
455
+ small = v
456
+ big = Max.identity
457
+ for i in maxs:
458
+ v = i.args[0]
459
+ if v.is_number and (v > big) == True:
460
+ big = v
461
+ # at the point when this function is called from __new__,
462
+ # there may be more than one numeric arg present since
463
+ # local zeros have not been handled yet, so look through
464
+ # more than the first arg
465
+ if cls == Min:
466
+ for arg in args:
467
+ if not arg.is_number:
468
+ break
469
+ if (arg < small) == True:
470
+ small = arg
471
+ elif cls == Max:
472
+ for arg in args:
473
+ if not arg.is_number:
474
+ break
475
+ if (arg > big) == True:
476
+ big = arg
477
+ T = None
478
+ if cls == Min:
479
+ if small != Min.identity:
480
+ other = Max
481
+ T = small
482
+ elif big != Max.identity:
483
+ other = Min
484
+ T = big
485
+ if T is not None:
486
+ # remove numerical redundancy
487
+ for i in range(len(args)):
488
+ a = args[i]
489
+ if isinstance(a, other):
490
+ a0 = a.args[0]
491
+ if ((a0 > T) if other == Max else (a0 < T)) == True:
492
+ args[i] = cls.identity
493
+
494
+ # remove redundant symbolic args
495
+ def do(ai, a):
496
+ if not isinstance(ai, (Min, Max)):
497
+ return ai
498
+ cond = a in ai.args
499
+ if not cond:
500
+ return ai.func(*[do(i, a) for i in ai.args],
501
+ evaluate=False)
502
+ if isinstance(ai, cls):
503
+ return ai.func(*[do(i, a) for i in ai.args if i != a],
504
+ evaluate=False)
505
+ return a
506
+ for i, a in enumerate(args):
507
+ args[i + 1:] = [do(ai, a) for ai in args[i + 1:]]
508
+
509
+ # factor out common elements as for
510
+ # Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
511
+ # and vice versa when swapping Min/Max -- do this only for the
512
+ # easy case where all functions contain something in common;
513
+ # trying to find some optimal subset of args to modify takes
514
+ # too long
515
+
516
+ def factor_minmax(args):
517
+ is_other = lambda arg: isinstance(arg, other)
518
+ other_args, remaining_args = sift(args, is_other, binary=True)
519
+ if not other_args:
520
+ return args
521
+
522
+ # Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
523
+ arg_sets = [set(arg.args) for arg in other_args]
524
+ common = set.intersection(*arg_sets)
525
+ if not common:
526
+ return args
527
+
528
+ new_other_args = list(common)
529
+ arg_sets_diff = [arg_set - common for arg_set in arg_sets]
530
+
531
+ # If any set is empty after removing common then all can be
532
+ # discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
533
+ if all(arg_sets_diff):
534
+ other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
535
+ new_other_args.append(cls(*other_args_diff, evaluate=False))
536
+
537
+ other_args_factored = other(*new_other_args, evaluate=False)
538
+ return remaining_args + [other_args_factored]
539
+
540
+ if len(args) > 1:
541
+ args = factor_minmax(args)
542
+
543
+ return args
544
+
545
+ @classmethod
546
+ def _new_args_filter(cls, arg_sequence):
547
+ """
548
+ Generator filtering args.
549
+
550
+ first standard filter, for cls.zero and cls.identity.
551
+ Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
552
+ and check arguments for comparability
553
+ """
554
+ for arg in arg_sequence:
555
+ # pre-filter, checking comparability of arguments
556
+ if not isinstance(arg, Expr) or arg.is_extended_real is False or (
557
+ arg.is_number and
558
+ not arg.is_comparable):
559
+ raise ValueError("The argument '%s' is not comparable." % arg)
560
+
561
+ if arg == cls.zero:
562
+ raise ShortCircuit(arg)
563
+ elif arg == cls.identity:
564
+ continue
565
+ elif arg.func == cls:
566
+ yield from arg.args
567
+ else:
568
+ yield arg
569
+
570
+ @classmethod
571
+ def _find_localzeros(cls, values, **options):
572
+ """
573
+ Sequentially allocate values to localzeros.
574
+
575
+ When a value is identified as being more extreme than another member it
576
+ replaces that member; if this is never true, then the value is simply
577
+ appended to the localzeros.
578
+ """
579
+ localzeros = set()
580
+ for v in values:
581
+ is_newzero = True
582
+ localzeros_ = list(localzeros)
583
+ for z in localzeros_:
584
+ if id(v) == id(z):
585
+ is_newzero = False
586
+ else:
587
+ con = cls._is_connected(v, z)
588
+ if con:
589
+ is_newzero = False
590
+ if con is True or con == cls:
591
+ localzeros.remove(z)
592
+ localzeros.update([v])
593
+ if is_newzero:
594
+ localzeros.update([v])
595
+ return localzeros
596
+
597
+ @classmethod
598
+ def _is_connected(cls, x, y):
599
+ """
600
+ Check if x and y are connected somehow.
601
+ """
602
+ for i in range(2):
603
+ if x == y:
604
+ return True
605
+ t, f = Max, Min
606
+ for op in "><":
607
+ for j in range(2):
608
+ try:
609
+ if op == ">":
610
+ v = x >= y
611
+ else:
612
+ v = x <= y
613
+ except TypeError:
614
+ return False # non-real arg
615
+ if not v.is_Relational:
616
+ return t if v else f
617
+ t, f = f, t
618
+ x, y = y, x
619
+ x, y = y, x # run next pass with reversed order relative to start
620
+ # simplification can be expensive, so be conservative
621
+ # in what is attempted
622
+ x = factor_terms(x - y)
623
+ y = S.Zero
624
+
625
+ return False
626
+
627
+ def _eval_derivative(self, s):
628
+ # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
629
+ i = 0
630
+ l = []
631
+ for a in self.args:
632
+ i += 1
633
+ da = a.diff(s)
634
+ if da.is_zero:
635
+ continue
636
+ try:
637
+ df = self.fdiff(i)
638
+ except ArgumentIndexError:
639
+ df = Function.fdiff(self, i)
640
+ l.append(df * da)
641
+ return Add(*l)
642
+
643
+ def _eval_rewrite_as_Abs(self, *args, **kwargs):
644
+ from sympy.functions.elementary.complexes import Abs
645
+ s = (args[0] + self.func(*args[1:]))/2
646
+ d = abs(args[0] - self.func(*args[1:]))/2
647
+ return (s + d if isinstance(self, Max) else s - d).rewrite(Abs)
648
+
649
+ def evalf(self, n=15, **options):
650
+ return self.func(*[a.evalf(n, **options) for a in self.args])
651
+
652
+ def n(self, *args, **kwargs):
653
+ return self.evalf(*args, **kwargs)
654
+
655
+ _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args)
656
+ _eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args)
657
+ _eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args)
658
+ _eval_is_complex = lambda s: _torf(i.is_complex for i in s.args)
659
+ _eval_is_composite = lambda s: _torf(i.is_composite for i in s.args)
660
+ _eval_is_even = lambda s: _torf(i.is_even for i in s.args)
661
+ _eval_is_finite = lambda s: _torf(i.is_finite for i in s.args)
662
+ _eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args)
663
+ _eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args)
664
+ _eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args)
665
+ _eval_is_integer = lambda s: _torf(i.is_integer for i in s.args)
666
+ _eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args)
667
+ _eval_is_negative = lambda s: _torf(i.is_negative for i in s.args)
668
+ _eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args)
669
+ _eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args)
670
+ _eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args)
671
+ _eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args)
672
+ _eval_is_odd = lambda s: _torf(i.is_odd for i in s.args)
673
+ _eval_is_polar = lambda s: _torf(i.is_polar for i in s.args)
674
+ _eval_is_positive = lambda s: _torf(i.is_positive for i in s.args)
675
+ _eval_is_prime = lambda s: _torf(i.is_prime for i in s.args)
676
+ _eval_is_rational = lambda s: _torf(i.is_rational for i in s.args)
677
+ _eval_is_real = lambda s: _torf(i.is_real for i in s.args)
678
+ _eval_is_extended_real = lambda s: _torf(i.is_extended_real for i in s.args)
679
+ _eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args)
680
+ _eval_is_zero = lambda s: _torf(i.is_zero for i in s.args)
681
+
682
+
683
+ class Max(MinMaxBase, Application):
684
+ r"""
685
+ Return, if possible, the maximum value of the list.
686
+
687
+ When number of arguments is equal one, then
688
+ return this argument.
689
+
690
+ When number of arguments is equal two, then
691
+ return, if possible, the value from (a, b) that is $\ge$ the other.
692
+
693
+ In common case, when the length of list greater than 2, the task
694
+ is more complicated. Return only the arguments, which are greater
695
+ than others, if it is possible to determine directional relation.
696
+
697
+ If is not possible to determine such a relation, return a partially
698
+ evaluated result.
699
+
700
+ Assumptions are used to make the decision too.
701
+
702
+ Also, only comparable arguments are permitted.
703
+
704
+ It is named ``Max`` and not ``max`` to avoid conflicts
705
+ with the built-in function ``max``.
706
+
707
+
708
+ Examples
709
+ ========
710
+
711
+ >>> from sympy import Max, Symbol, oo
712
+ >>> from sympy.abc import x, y, z
713
+ >>> p = Symbol('p', positive=True)
714
+ >>> n = Symbol('n', negative=True)
715
+
716
+ >>> Max(x, -2)
717
+ Max(-2, x)
718
+ >>> Max(x, -2).subs(x, 3)
719
+ 3
720
+ >>> Max(p, -2)
721
+ p
722
+ >>> Max(x, y)
723
+ Max(x, y)
724
+ >>> Max(x, y) == Max(y, x)
725
+ True
726
+ >>> Max(x, Max(y, z))
727
+ Max(x, y, z)
728
+ >>> Max(n, 8, p, 7, -oo)
729
+ Max(8, p)
730
+ >>> Max (1, x, oo)
731
+ oo
732
+
733
+ * Algorithm
734
+
735
+ The task can be considered as searching of supremums in the
736
+ directed complete partial orders [1]_.
737
+
738
+ The source values are sequentially allocated by the isolated subsets
739
+ in which supremums are searched and result as Max arguments.
740
+
741
+ If the resulted supremum is single, then it is returned.
742
+
743
+ The isolated subsets are the sets of values which are only the comparable
744
+ with each other in the current set. E.g. natural numbers are comparable with
745
+ each other, but not comparable with the `x` symbol. Another example: the
746
+ symbol `x` with negative assumption is comparable with a natural number.
747
+
748
+ Also there are "least" elements, which are comparable with all others,
749
+ and have a zero property (maximum or minimum for all elements).
750
+ For example, in case of $\infty$, the allocation operation is terminated
751
+ and only this value is returned.
752
+
753
+ Assumption:
754
+ - if $A > B > C$ then $A > C$
755
+ - if $A = B$ then $B$ can be removed
756
+
757
+ References
758
+ ==========
759
+
760
+ .. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order
761
+ .. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29
762
+
763
+ See Also
764
+ ========
765
+
766
+ Min : find minimum values
767
+ """
768
+ zero = S.Infinity
769
+ identity = S.NegativeInfinity
770
+
771
+ def fdiff( self, argindex ):
772
+ from sympy.functions.special.delta_functions import Heaviside
773
+ n = len(self.args)
774
+ if 0 < argindex and argindex <= n:
775
+ argindex -= 1
776
+ if n == 2:
777
+ return Heaviside(self.args[argindex] - self.args[1 - argindex])
778
+ newargs = tuple([self.args[i] for i in range(n) if i != argindex])
779
+ return Heaviside(self.args[argindex] - Max(*newargs))
780
+ else:
781
+ raise ArgumentIndexError(self, argindex)
782
+
783
+ def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
784
+ from sympy.functions.special.delta_functions import Heaviside
785
+ return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \
786
+ for j in args])
787
+
788
+ def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
789
+ return _minmax_as_Piecewise('>=', *args)
790
+
791
+ def _eval_is_positive(self):
792
+ return fuzzy_or(a.is_positive for a in self.args)
793
+
794
+ def _eval_is_nonnegative(self):
795
+ return fuzzy_or(a.is_nonnegative for a in self.args)
796
+
797
+ def _eval_is_negative(self):
798
+ return fuzzy_and(a.is_negative for a in self.args)
799
+
800
+
801
+ class Min(MinMaxBase, Application):
802
+ """
803
+ Return, if possible, the minimum value of the list.
804
+ It is named ``Min`` and not ``min`` to avoid conflicts
805
+ with the built-in function ``min``.
806
+
807
+ Examples
808
+ ========
809
+
810
+ >>> from sympy import Min, Symbol, oo
811
+ >>> from sympy.abc import x, y
812
+ >>> p = Symbol('p', positive=True)
813
+ >>> n = Symbol('n', negative=True)
814
+
815
+ >>> Min(x, -2)
816
+ Min(-2, x)
817
+ >>> Min(x, -2).subs(x, 3)
818
+ -2
819
+ >>> Min(p, -3)
820
+ -3
821
+ >>> Min(x, y)
822
+ Min(x, y)
823
+ >>> Min(n, 8, p, -7, p, oo)
824
+ Min(-7, n)
825
+
826
+ See Also
827
+ ========
828
+
829
+ Max : find maximum values
830
+ """
831
+ zero = S.NegativeInfinity
832
+ identity = S.Infinity
833
+
834
+ def fdiff( self, argindex ):
835
+ from sympy.functions.special.delta_functions import Heaviside
836
+ n = len(self.args)
837
+ if 0 < argindex and argindex <= n:
838
+ argindex -= 1
839
+ if n == 2:
840
+ return Heaviside( self.args[1-argindex] - self.args[argindex] )
841
+ newargs = tuple([ self.args[i] for i in range(n) if i != argindex])
842
+ return Heaviside( Min(*newargs) - self.args[argindex] )
843
+ else:
844
+ raise ArgumentIndexError(self, argindex)
845
+
846
+ def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
847
+ from sympy.functions.special.delta_functions import Heaviside
848
+ return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \
849
+ for j in args])
850
+
851
+ def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
852
+ return _minmax_as_Piecewise('<=', *args)
853
+
854
+ def _eval_is_positive(self):
855
+ return fuzzy_and(a.is_positive for a in self.args)
856
+
857
+ def _eval_is_nonnegative(self):
858
+ return fuzzy_and(a.is_nonnegative for a in self.args)
859
+
860
+ def _eval_is_negative(self):
861
+ return fuzzy_or(a.is_negative for a in self.args)
862
+
863
+
864
+ class Rem(Function):
865
+ """Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite
866
+ and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign
867
+ as the divisor.
868
+
869
+ Parameters
870
+ ==========
871
+
872
+ p : Expr
873
+ Dividend.
874
+
875
+ q : Expr
876
+ Divisor.
877
+
878
+ Notes
879
+ =====
880
+
881
+ ``Rem`` corresponds to the ``%`` operator in C.
882
+
883
+ Examples
884
+ ========
885
+
886
+ >>> from sympy.abc import x, y
887
+ >>> from sympy import Rem
888
+ >>> Rem(x**3, y)
889
+ Rem(x**3, y)
890
+ >>> Rem(x**3, y).subs({x: -5, y: 3})
891
+ -2
892
+
893
+ See Also
894
+ ========
895
+
896
+ Mod
897
+ """
898
+ kind = NumberKind
899
+
900
+ @classmethod
901
+ def eval(cls, p, q):
902
+ """Return the function remainder if both p, q are numbers and q is not
903
+ zero.
904
+ """
905
+
906
+ if q.is_zero:
907
+ raise ZeroDivisionError("Division by zero")
908
+ if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
909
+ return S.NaN
910
+ if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
911
+ return S.Zero
912
+
913
+ if q.is_Number:
914
+ if p.is_Number:
915
+ return p - Integer(p/q)*q
env-llmeval/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py ADDED
@@ -0,0 +1,1506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, Function, diff, Tuple, Dummy, Mul
2
+ from sympy.core.basic import Basic, as_Basic
3
+ from sympy.core.numbers import Rational, NumberSymbol, _illegal
4
+ from sympy.core.parameters import global_parameters
5
+ from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational,
6
+ _canonical, _canonical_coeff)
7
+ from sympy.core.sorting import ordered
8
+ from sympy.functions.elementary.miscellaneous import Max, Min
9
+ from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not,
10
+ true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and)
11
+ from sympy.utilities.iterables import uniq, sift, common_prefix
12
+ from sympy.utilities.misc import filldedent, func_name
13
+
14
+ from itertools import product
15
+
16
+ Undefined = S.NaN # Piecewise()
17
+
18
+ class ExprCondPair(Tuple):
19
+ """Represents an expression, condition pair."""
20
+
21
+ def __new__(cls, expr, cond):
22
+ expr = as_Basic(expr)
23
+ if cond == True:
24
+ return Tuple.__new__(cls, expr, true)
25
+ elif cond == False:
26
+ return Tuple.__new__(cls, expr, false)
27
+ elif isinstance(cond, Basic) and cond.has(Piecewise):
28
+ cond = piecewise_fold(cond)
29
+ if isinstance(cond, Piecewise):
30
+ cond = cond.rewrite(ITE)
31
+
32
+ if not isinstance(cond, Boolean):
33
+ raise TypeError(filldedent('''
34
+ Second argument must be a Boolean,
35
+ not `%s`''' % func_name(cond)))
36
+ return Tuple.__new__(cls, expr, cond)
37
+
38
+ @property
39
+ def expr(self):
40
+ """
41
+ Returns the expression of this pair.
42
+ """
43
+ return self.args[0]
44
+
45
+ @property
46
+ def cond(self):
47
+ """
48
+ Returns the condition of this pair.
49
+ """
50
+ return self.args[1]
51
+
52
+ @property
53
+ def is_commutative(self):
54
+ return self.expr.is_commutative
55
+
56
+ def __iter__(self):
57
+ yield self.expr
58
+ yield self.cond
59
+
60
+ def _eval_simplify(self, **kwargs):
61
+ return self.func(*[a.simplify(**kwargs) for a in self.args])
62
+
63
+
64
+ class Piecewise(Function):
65
+ """
66
+ Represents a piecewise function.
67
+
68
+ Usage:
69
+
70
+ Piecewise( (expr,cond), (expr,cond), ... )
71
+ - Each argument is a 2-tuple defining an expression and condition
72
+ - The conds are evaluated in turn returning the first that is True.
73
+ If any of the evaluated conds are not explicitly False,
74
+ e.g. ``x < 1``, the function is returned in symbolic form.
75
+ - If the function is evaluated at a place where all conditions are False,
76
+ nan will be returned.
77
+ - Pairs where the cond is explicitly False, will be removed and no pair
78
+ appearing after a True condition will ever be retained. If a single
79
+ pair with a True condition remains, it will be returned, even when
80
+ evaluation is False.
81
+
82
+ Examples
83
+ ========
84
+
85
+ >>> from sympy import Piecewise, log, piecewise_fold
86
+ >>> from sympy.abc import x, y
87
+ >>> f = x**2
88
+ >>> g = log(x)
89
+ >>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
90
+ >>> p.subs(x,1)
91
+ 1
92
+ >>> p.subs(x,5)
93
+ log(5)
94
+
95
+ Booleans can contain Piecewise elements:
96
+
97
+ >>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
98
+ Piecewise((2, x < 0), (3, True)) < y
99
+
100
+ The folded version of this results in a Piecewise whose
101
+ expressions are Booleans:
102
+
103
+ >>> folded_cond = piecewise_fold(cond); folded_cond
104
+ Piecewise((2 < y, x < 0), (3 < y, True))
105
+
106
+ When a Boolean containing Piecewise (like cond) or a Piecewise
107
+ with Boolean expressions (like folded_cond) is used as a condition,
108
+ it is converted to an equivalent :class:`~.ITE` object:
109
+
110
+ >>> Piecewise((1, folded_cond))
111
+ Piecewise((1, ITE(x < 0, y > 2, y > 3)))
112
+
113
+ When a condition is an ``ITE``, it will be converted to a simplified
114
+ Boolean expression:
115
+
116
+ >>> piecewise_fold(_)
117
+ Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
118
+
119
+ See Also
120
+ ========
121
+
122
+ piecewise_fold
123
+ piecewise_exclusive
124
+ ITE
125
+ """
126
+
127
+ nargs = None
128
+ is_Piecewise = True
129
+
130
+ def __new__(cls, *args, **options):
131
+ if len(args) == 0:
132
+ raise TypeError("At least one (expr, cond) pair expected.")
133
+ # (Try to) sympify args first
134
+ newargs = []
135
+ for ec in args:
136
+ # ec could be a ExprCondPair or a tuple
137
+ pair = ExprCondPair(*getattr(ec, 'args', ec))
138
+ cond = pair.cond
139
+ if cond is false:
140
+ continue
141
+ newargs.append(pair)
142
+ if cond is true:
143
+ break
144
+
145
+ eval = options.pop('evaluate', global_parameters.evaluate)
146
+ if eval:
147
+ r = cls.eval(*newargs)
148
+ if r is not None:
149
+ return r
150
+ elif len(newargs) == 1 and newargs[0].cond == True:
151
+ return newargs[0].expr
152
+
153
+ return Basic.__new__(cls, *newargs, **options)
154
+
155
+ @classmethod
156
+ def eval(cls, *_args):
157
+ """Either return a modified version of the args or, if no
158
+ modifications were made, return None.
159
+
160
+ Modifications that are made here:
161
+
162
+ 1. relationals are made canonical
163
+ 2. any False conditions are dropped
164
+ 3. any repeat of a previous condition is ignored
165
+ 4. any args past one with a true condition are dropped
166
+
167
+ If there are no args left, nan will be returned.
168
+ If there is a single arg with a True condition, its
169
+ corresponding expression will be returned.
170
+
171
+ EXAMPLES
172
+ ========
173
+
174
+ >>> from sympy import Piecewise
175
+ >>> from sympy.abc import x
176
+ >>> cond = -x < -1
177
+ >>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)]
178
+ >>> Piecewise(*args, evaluate=False)
179
+ Piecewise((1, -x < -1), (4, -x < -1), (2, True))
180
+ >>> Piecewise(*args)
181
+ Piecewise((1, x > 1), (2, True))
182
+ """
183
+ if not _args:
184
+ return Undefined
185
+
186
+ if len(_args) == 1 and _args[0][-1] == True:
187
+ return _args[0][0]
188
+
189
+ newargs = _piecewise_collapse_arguments(_args)
190
+
191
+ # some conditions may have been redundant
192
+ missing = len(newargs) != len(_args)
193
+ # some conditions may have changed
194
+ same = all(a == b for a, b in zip(newargs, _args))
195
+ # if either change happened we return the expr with the
196
+ # updated args
197
+ if not newargs:
198
+ raise ValueError(filldedent('''
199
+ There are no conditions (or none that
200
+ are not trivially false) to define an
201
+ expression.'''))
202
+ if missing or not same:
203
+ return cls(*newargs)
204
+
205
+ def doit(self, **hints):
206
+ """
207
+ Evaluate this piecewise function.
208
+ """
209
+ newargs = []
210
+ for e, c in self.args:
211
+ if hints.get('deep', True):
212
+ if isinstance(e, Basic):
213
+ newe = e.doit(**hints)
214
+ if newe != self:
215
+ e = newe
216
+ if isinstance(c, Basic):
217
+ c = c.doit(**hints)
218
+ newargs.append((e, c))
219
+ return self.func(*newargs)
220
+
221
+ def _eval_simplify(self, **kwargs):
222
+ return piecewise_simplify(self, **kwargs)
223
+
224
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
225
+ for e, c in self.args:
226
+ if c == True or c.subs(x, 0) == True:
227
+ return e.as_leading_term(x)
228
+
229
+ def _eval_adjoint(self):
230
+ return self.func(*[(e.adjoint(), c) for e, c in self.args])
231
+
232
+ def _eval_conjugate(self):
233
+ return self.func(*[(e.conjugate(), c) for e, c in self.args])
234
+
235
+ def _eval_derivative(self, x):
236
+ return self.func(*[(diff(e, x), c) for e, c in self.args])
237
+
238
+ def _eval_evalf(self, prec):
239
+ return self.func(*[(e._evalf(prec), c) for e, c in self.args])
240
+
241
+ def _eval_is_meromorphic(self, x, a):
242
+ # Conditions often implicitly assume that the argument is real.
243
+ # Hence, there needs to be some check for as_set.
244
+ if not a.is_real:
245
+ return None
246
+
247
+ # Then, scan ExprCondPairs in the given order to find a piece that would contain a,
248
+ # possibly as a boundary point.
249
+ for e, c in self.args:
250
+ cond = c.subs(x, a)
251
+
252
+ if cond.is_Relational:
253
+ return None
254
+ if a in c.as_set().boundary:
255
+ return None
256
+ # Apply expression if a is an interior point of the domain of e.
257
+ if cond:
258
+ return e._eval_is_meromorphic(x, a)
259
+
260
+ def piecewise_integrate(self, x, **kwargs):
261
+ """Return the Piecewise with each expression being
262
+ replaced with its antiderivative. To obtain a continuous
263
+ antiderivative, use the :func:`~.integrate` function or method.
264
+
265
+ Examples
266
+ ========
267
+
268
+ >>> from sympy import Piecewise
269
+ >>> from sympy.abc import x
270
+ >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
271
+ >>> p.piecewise_integrate(x)
272
+ Piecewise((0, x < 0), (x, x < 1), (2*x, True))
273
+
274
+ Note that this does not give a continuous function, e.g.
275
+ at x = 1 the 3rd condition applies and the antiderivative
276
+ there is 2*x so the value of the antiderivative is 2:
277
+
278
+ >>> anti = _
279
+ >>> anti.subs(x, 1)
280
+ 2
281
+
282
+ The continuous derivative accounts for the integral *up to*
283
+ the point of interest, however:
284
+
285
+ >>> p.integrate(x)
286
+ Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
287
+ >>> _.subs(x, 1)
288
+ 1
289
+
290
+ See Also
291
+ ========
292
+ Piecewise._eval_integral
293
+ """
294
+ from sympy.integrals import integrate
295
+ return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
296
+
297
+ def _handle_irel(self, x, handler):
298
+ """Return either None (if the conditions of self depend only on x) else
299
+ a Piecewise expression whose expressions (handled by the handler that
300
+ was passed) are paired with the governing x-independent relationals,
301
+ e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
302
+ Piecewise(
303
+ (handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
304
+ (handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
305
+ (handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
306
+ (handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
307
+ """
308
+ # identify governing relationals
309
+ rel = self.atoms(Relational)
310
+ irel = list(ordered([r for r in rel if x not in r.free_symbols
311
+ and r not in (S.true, S.false)]))
312
+ if irel:
313
+ args = {}
314
+ exprinorder = []
315
+ for truth in product((1, 0), repeat=len(irel)):
316
+ reps = dict(zip(irel, truth))
317
+ # only store the true conditions since the false are implied
318
+ # when they appear lower in the Piecewise args
319
+ if 1 not in truth:
320
+ cond = None # flag this one so it doesn't get combined
321
+ else:
322
+ andargs = Tuple(*[i for i in reps if reps[i]])
323
+ free = list(andargs.free_symbols)
324
+ if len(free) == 1:
325
+ from sympy.solvers.inequalities import (
326
+ reduce_inequalities, _solve_inequality)
327
+ try:
328
+ t = reduce_inequalities(andargs, free[0])
329
+ # ValueError when there are potentially
330
+ # nonvanishing imaginary parts
331
+ except (ValueError, NotImplementedError):
332
+ # at least isolate free symbol on left
333
+ t = And(*[_solve_inequality(
334
+ a, free[0], linear=True)
335
+ for a in andargs])
336
+ else:
337
+ t = And(*andargs)
338
+ if t is S.false:
339
+ continue # an impossible combination
340
+ cond = t
341
+ expr = handler(self.xreplace(reps))
342
+ if isinstance(expr, self.func) and len(expr.args) == 1:
343
+ expr, econd = expr.args[0]
344
+ cond = And(econd, True if cond is None else cond)
345
+ # the ec pairs are being collected since all possibilities
346
+ # are being enumerated, but don't put the last one in since
347
+ # its expr might match a previous expression and it
348
+ # must appear last in the args
349
+ if cond is not None:
350
+ args.setdefault(expr, []).append(cond)
351
+ # but since we only store the true conditions we must maintain
352
+ # the order so that the expression with the most true values
353
+ # comes first
354
+ exprinorder.append(expr)
355
+ # convert collected conditions as args of Or
356
+ for k in args:
357
+ args[k] = Or(*args[k])
358
+ # take them in the order obtained
359
+ args = [(e, args[e]) for e in uniq(exprinorder)]
360
+ # add in the last arg
361
+ args.append((expr, True))
362
+ return Piecewise(*args)
363
+
364
+ def _eval_integral(self, x, _first=True, **kwargs):
365
+ """Return the indefinite integral of the
366
+ Piecewise such that subsequent substitution of x with a
367
+ value will give the value of the integral (not including
368
+ the constant of integration) up to that point. To only
369
+ integrate the individual parts of Piecewise, use the
370
+ ``piecewise_integrate`` method.
371
+
372
+ Examples
373
+ ========
374
+
375
+ >>> from sympy import Piecewise
376
+ >>> from sympy.abc import x
377
+ >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
378
+ >>> p.integrate(x)
379
+ Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
380
+ >>> p.piecewise_integrate(x)
381
+ Piecewise((0, x < 0), (x, x < 1), (2*x, True))
382
+
383
+ See Also
384
+ ========
385
+ Piecewise.piecewise_integrate
386
+ """
387
+ from sympy.integrals.integrals import integrate
388
+
389
+ if _first:
390
+ def handler(ipw):
391
+ if isinstance(ipw, self.func):
392
+ return ipw._eval_integral(x, _first=False, **kwargs)
393
+ else:
394
+ return ipw.integrate(x, **kwargs)
395
+ irv = self._handle_irel(x, handler)
396
+ if irv is not None:
397
+ return irv
398
+
399
+ # handle a Piecewise from -oo to oo with and no x-independent relationals
400
+ # -----------------------------------------------------------------------
401
+ ok, abei = self._intervals(x)
402
+ if not ok:
403
+ from sympy.integrals.integrals import Integral
404
+ return Integral(self, x) # unevaluated
405
+
406
+ pieces = [(a, b) for a, b, _, _ in abei]
407
+ oo = S.Infinity
408
+ done = [(-oo, oo, -1)]
409
+ for k, p in enumerate(pieces):
410
+ if p == (-oo, oo):
411
+ # all undone intervals will get this key
412
+ for j, (a, b, i) in enumerate(done):
413
+ if i == -1:
414
+ done[j] = a, b, k
415
+ break # nothing else to consider
416
+ N = len(done) - 1
417
+ for j, (a, b, i) in enumerate(reversed(done)):
418
+ if i == -1:
419
+ j = N - j
420
+ done[j: j + 1] = _clip(p, (a, b), k)
421
+ done = [(a, b, i) for a, b, i in done if a != b]
422
+
423
+ # append an arg if there is a hole so a reference to
424
+ # argument -1 will give Undefined
425
+ if any(i == -1 for (a, b, i) in done):
426
+ abei.append((-oo, oo, Undefined, -1))
427
+
428
+ # return the sum of the intervals
429
+ args = []
430
+ sum = None
431
+ for a, b, i in done:
432
+ anti = integrate(abei[i][-2], x, **kwargs)
433
+ if sum is None:
434
+ sum = anti
435
+ else:
436
+ sum = sum.subs(x, a)
437
+ e = anti._eval_interval(x, a, x)
438
+ if sum.has(*_illegal) or e.has(*_illegal):
439
+ sum = anti
440
+ else:
441
+ sum += e
442
+ # see if we know whether b is contained in original
443
+ # condition
444
+ if b is S.Infinity:
445
+ cond = True
446
+ elif self.args[abei[i][-1]].cond.subs(x, b) == False:
447
+ cond = (x < b)
448
+ else:
449
+ cond = (x <= b)
450
+ args.append((sum, cond))
451
+ return Piecewise(*args)
452
+
453
+ def _eval_interval(self, sym, a, b, _first=True):
454
+ """Evaluates the function along the sym in a given interval [a, b]"""
455
+ # FIXME: Currently complex intervals are not supported. A possible
456
+ # replacement algorithm, discussed in issue 5227, can be found in the
457
+ # following papers;
458
+ # http://portal.acm.org/citation.cfm?id=281649
459
+ # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
460
+
461
+ if a is None or b is None:
462
+ # In this case, it is just simple substitution
463
+ return super()._eval_interval(sym, a, b)
464
+ else:
465
+ x, lo, hi = map(as_Basic, (sym, a, b))
466
+
467
+ if _first: # get only x-dependent relationals
468
+ def handler(ipw):
469
+ if isinstance(ipw, self.func):
470
+ return ipw._eval_interval(x, lo, hi, _first=None)
471
+ else:
472
+ return ipw._eval_interval(x, lo, hi)
473
+ irv = self._handle_irel(x, handler)
474
+ if irv is not None:
475
+ return irv
476
+
477
+ if (lo < hi) is S.false or (
478
+ lo is S.Infinity or hi is S.NegativeInfinity):
479
+ rv = self._eval_interval(x, hi, lo, _first=False)
480
+ if isinstance(rv, Piecewise):
481
+ rv = Piecewise(*[(-e, c) for e, c in rv.args])
482
+ else:
483
+ rv = -rv
484
+ return rv
485
+
486
+ if (lo < hi) is S.true or (
487
+ hi is S.Infinity or lo is S.NegativeInfinity):
488
+ pass
489
+ else:
490
+ _a = Dummy('lo')
491
+ _b = Dummy('hi')
492
+ a = lo if lo.is_comparable else _a
493
+ b = hi if hi.is_comparable else _b
494
+ pos = self._eval_interval(x, a, b, _first=False)
495
+ if a == _a and b == _b:
496
+ # it's purely symbolic so just swap lo and hi and
497
+ # change the sign to get the value for when lo > hi
498
+ neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
499
+ pos.xreplace({_a: lo, _b: hi}))
500
+ else:
501
+ # at least one of the bounds was comparable, so allow
502
+ # _eval_interval to use that information when computing
503
+ # the interval with lo and hi reversed
504
+ neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
505
+ pos.xreplace({_a: lo, _b: hi}))
506
+
507
+ # allow simplification based on ordering of lo and hi
508
+ p = Dummy('', positive=True)
509
+ if lo.is_Symbol:
510
+ pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
511
+ neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
512
+ elif hi.is_Symbol:
513
+ pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
514
+ neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
515
+ # evaluate limits that may have unevaluate Min/Max
516
+ touch = lambda _: _.replace(
517
+ lambda x: isinstance(x, (Min, Max)),
518
+ lambda x: x.func(*x.args))
519
+ neg = touch(neg)
520
+ pos = touch(pos)
521
+ # assemble return expression; make the first condition be Lt
522
+ # b/c then the first expression will look the same whether
523
+ # the lo or hi limit is symbolic
524
+ if a == _a: # the lower limit was symbolic
525
+ rv = Piecewise(
526
+ (pos,
527
+ lo < hi),
528
+ (neg,
529
+ True))
530
+ else:
531
+ rv = Piecewise(
532
+ (neg,
533
+ hi < lo),
534
+ (pos,
535
+ True))
536
+
537
+ if rv == Undefined:
538
+ raise ValueError("Can't integrate across undefined region.")
539
+ if any(isinstance(i, Piecewise) for i in (pos, neg)):
540
+ rv = piecewise_fold(rv)
541
+ return rv
542
+
543
+ # handle a Piecewise with lo <= hi and no x-independent relationals
544
+ # -----------------------------------------------------------------
545
+ ok, abei = self._intervals(x)
546
+ if not ok:
547
+ from sympy.integrals.integrals import Integral
548
+ # not being able to do the interval of f(x) can
549
+ # be stated as not being able to do the integral
550
+ # of f'(x) over the same range
551
+ return Integral(self.diff(x), (x, lo, hi)) # unevaluated
552
+
553
+ pieces = [(a, b) for a, b, _, _ in abei]
554
+ done = [(lo, hi, -1)]
555
+ oo = S.Infinity
556
+ for k, p in enumerate(pieces):
557
+ if p[:2] == (-oo, oo):
558
+ # all undone intervals will get this key
559
+ for j, (a, b, i) in enumerate(done):
560
+ if i == -1:
561
+ done[j] = a, b, k
562
+ break # nothing else to consider
563
+ N = len(done) - 1
564
+ for j, (a, b, i) in enumerate(reversed(done)):
565
+ if i == -1:
566
+ j = N - j
567
+ done[j: j + 1] = _clip(p, (a, b), k)
568
+ done = [(a, b, i) for a, b, i in done if a != b]
569
+
570
+ # return the sum of the intervals
571
+ sum = S.Zero
572
+ upto = None
573
+ for a, b, i in done:
574
+ if i == -1:
575
+ if upto is None:
576
+ return Undefined
577
+ # TODO simplify hi <= upto
578
+ return Piecewise((sum, hi <= upto), (Undefined, True))
579
+ sum += abei[i][-2]._eval_interval(x, a, b)
580
+ upto = b
581
+ return sum
582
+
583
+ def _intervals(self, sym, err_on_Eq=False):
584
+ r"""Return a bool and a message (when bool is False), else a
585
+ list of unique tuples, (a, b, e, i), where a and b
586
+ are the lower and upper bounds in which the expression e of
587
+ argument i in self is defined and $a < b$ (when involving
588
+ numbers) or $a \le b$ when involving symbols.
589
+
590
+ If there are any relationals not involving sym, or any
591
+ relational cannot be solved for sym, the bool will be False
592
+ a message be given as the second return value. The calling
593
+ routine should have removed such relationals before calling
594
+ this routine.
595
+
596
+ The evaluated conditions will be returned as ranges.
597
+ Discontinuous ranges will be returned separately with
598
+ identical expressions. The first condition that evaluates to
599
+ True will be returned as the last tuple with a, b = -oo, oo.
600
+ """
601
+ from sympy.solvers.inequalities import _solve_inequality
602
+
603
+ assert isinstance(self, Piecewise)
604
+
605
+ def nonsymfail(cond):
606
+ return False, filldedent('''
607
+ A condition not involving
608
+ %s appeared: %s''' % (sym, cond))
609
+
610
+ def _solve_relational(r):
611
+ if sym not in r.free_symbols:
612
+ return nonsymfail(r)
613
+ try:
614
+ rv = _solve_inequality(r, sym)
615
+ except NotImplementedError:
616
+ return False, 'Unable to solve relational %s for %s.' % (r, sym)
617
+ if isinstance(rv, Relational):
618
+ free = rv.args[1].free_symbols
619
+ if rv.args[0] != sym or sym in free:
620
+ return False, 'Unable to solve relational %s for %s.' % (r, sym)
621
+ if rv.rel_op == '==':
622
+ # this equality has been affirmed to have the form
623
+ # Eq(sym, rhs) where rhs is sym-free; it represents
624
+ # a zero-width interval which will be ignored
625
+ # whether it is an isolated condition or contained
626
+ # within an And or an Or
627
+ rv = S.false
628
+ elif rv.rel_op == '!=':
629
+ try:
630
+ rv = Or(sym < rv.rhs, sym > rv.rhs)
631
+ except TypeError:
632
+ # e.g. x != I ==> all real x satisfy
633
+ rv = S.true
634
+ elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
635
+ rv = S.true
636
+ return True, rv
637
+
638
+ args = list(self.args)
639
+ # make self canonical wrt Relationals
640
+ keys = self.atoms(Relational)
641
+ reps = {}
642
+ for r in keys:
643
+ ok, s = _solve_relational(r)
644
+ if ok != True:
645
+ return False, ok
646
+ reps[r] = s
647
+ # process args individually so if any evaluate, their position
648
+ # in the original Piecewise will be known
649
+ args = [i.xreplace(reps) for i in self.args]
650
+
651
+ # precondition args
652
+ expr_cond = []
653
+ default = idefault = None
654
+ for i, (expr, cond) in enumerate(args):
655
+ if cond is S.false:
656
+ continue
657
+ if cond is S.true:
658
+ default = expr
659
+ idefault = i
660
+ break
661
+ if isinstance(cond, Eq):
662
+ # unanticipated condition, but it is here in case a
663
+ # replacement caused an Eq to appear
664
+ if err_on_Eq:
665
+ return False, 'encountered Eq condition: %s' % cond
666
+ continue # zero width interval
667
+
668
+ cond = to_cnf(cond)
669
+ if isinstance(cond, And):
670
+ cond = distribute_or_over_and(cond)
671
+
672
+ if isinstance(cond, Or):
673
+ expr_cond.extend(
674
+ [(i, expr, o) for o in cond.args
675
+ if not isinstance(o, Eq)])
676
+ elif cond is not S.false:
677
+ expr_cond.append((i, expr, cond))
678
+ elif cond is S.true:
679
+ default = expr
680
+ idefault = i
681
+ break
682
+
683
+ # determine intervals represented by conditions
684
+ int_expr = []
685
+ for iarg, expr, cond in expr_cond:
686
+ if isinstance(cond, And):
687
+ lower = S.NegativeInfinity
688
+ upper = S.Infinity
689
+ exclude = []
690
+ for cond2 in cond.args:
691
+ if not isinstance(cond2, Relational):
692
+ return False, 'expecting only Relationals'
693
+ if isinstance(cond2, Eq):
694
+ lower = upper # ignore
695
+ if err_on_Eq:
696
+ return False, 'encountered secondary Eq condition'
697
+ break
698
+ elif isinstance(cond2, Ne):
699
+ l, r = cond2.args
700
+ if l == sym:
701
+ exclude.append(r)
702
+ elif r == sym:
703
+ exclude.append(l)
704
+ else:
705
+ return nonsymfail(cond2)
706
+ continue
707
+ elif cond2.lts == sym:
708
+ upper = Min(cond2.gts, upper)
709
+ elif cond2.gts == sym:
710
+ lower = Max(cond2.lts, lower)
711
+ else:
712
+ return nonsymfail(cond2) # should never get here
713
+ if exclude:
714
+ exclude = list(ordered(exclude))
715
+ newcond = []
716
+ for i, e in enumerate(exclude):
717
+ if e < lower == True or e > upper == True:
718
+ continue
719
+ if not newcond:
720
+ newcond.append((None, lower)) # add a primer
721
+ newcond.append((newcond[-1][1], e))
722
+ newcond.append((newcond[-1][1], upper))
723
+ newcond.pop(0) # remove the primer
724
+ expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond])
725
+ continue
726
+ elif isinstance(cond, Relational) and cond.rel_op != '!=':
727
+ lower, upper = cond.lts, cond.gts # part 1: initialize with givens
728
+ if cond.lts == sym: # part 1a: expand the side ...
729
+ lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
730
+ elif cond.gts == sym: # part 1a: ... that can be expanded
731
+ upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
732
+ else:
733
+ return nonsymfail(cond)
734
+ else:
735
+ return False, 'unrecognized condition: %s' % cond
736
+
737
+ lower, upper = lower, Max(lower, upper)
738
+ if err_on_Eq and lower == upper:
739
+ return False, 'encountered Eq condition'
740
+ if (lower >= upper) is not S.true:
741
+ int_expr.append((lower, upper, expr, iarg))
742
+
743
+ if default is not None:
744
+ int_expr.append(
745
+ (S.NegativeInfinity, S.Infinity, default, idefault))
746
+
747
+ return True, list(uniq(int_expr))
748
+
749
+ def _eval_nseries(self, x, n, logx, cdir=0):
750
+ args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
751
+ return self.func(*args)
752
+
753
+ def _eval_power(self, s):
754
+ return self.func(*[(e**s, c) for e, c in self.args])
755
+
756
+ def _eval_subs(self, old, new):
757
+ # this is strictly not necessary, but we can keep track
758
+ # of whether True or False conditions arise and be
759
+ # somewhat more efficient by avoiding other substitutions
760
+ # and avoiding invalid conditions that appear after a
761
+ # True condition
762
+ args = list(self.args)
763
+ args_exist = False
764
+ for i, (e, c) in enumerate(args):
765
+ c = c._subs(old, new)
766
+ if c != False:
767
+ args_exist = True
768
+ e = e._subs(old, new)
769
+ args[i] = (e, c)
770
+ if c == True:
771
+ break
772
+ if not args_exist:
773
+ args = ((Undefined, True),)
774
+ return self.func(*args)
775
+
776
+ def _eval_transpose(self):
777
+ return self.func(*[(e.transpose(), c) for e, c in self.args])
778
+
779
+ def _eval_template_is_attr(self, is_attr):
780
+ b = None
781
+ for expr, _ in self.args:
782
+ a = getattr(expr, is_attr)
783
+ if a is None:
784
+ return
785
+ if b is None:
786
+ b = a
787
+ elif b is not a:
788
+ return
789
+ return b
790
+
791
+ _eval_is_finite = lambda self: self._eval_template_is_attr(
792
+ 'is_finite')
793
+ _eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
794
+ _eval_is_even = lambda self: self._eval_template_is_attr('is_even')
795
+ _eval_is_imaginary = lambda self: self._eval_template_is_attr(
796
+ 'is_imaginary')
797
+ _eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
798
+ _eval_is_irrational = lambda self: self._eval_template_is_attr(
799
+ 'is_irrational')
800
+ _eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
801
+ _eval_is_nonnegative = lambda self: self._eval_template_is_attr(
802
+ 'is_nonnegative')
803
+ _eval_is_nonpositive = lambda self: self._eval_template_is_attr(
804
+ 'is_nonpositive')
805
+ _eval_is_nonzero = lambda self: self._eval_template_is_attr(
806
+ 'is_nonzero')
807
+ _eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
808
+ _eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
809
+ _eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
810
+ _eval_is_extended_real = lambda self: self._eval_template_is_attr(
811
+ 'is_extended_real')
812
+ _eval_is_extended_positive = lambda self: self._eval_template_is_attr(
813
+ 'is_extended_positive')
814
+ _eval_is_extended_negative = lambda self: self._eval_template_is_attr(
815
+ 'is_extended_negative')
816
+ _eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
817
+ 'is_extended_nonzero')
818
+ _eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
819
+ 'is_extended_nonpositive')
820
+ _eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
821
+ 'is_extended_nonnegative')
822
+ _eval_is_real = lambda self: self._eval_template_is_attr('is_real')
823
+ _eval_is_zero = lambda self: self._eval_template_is_attr(
824
+ 'is_zero')
825
+
826
+ @classmethod
827
+ def __eval_cond(cls, cond):
828
+ """Return the truth value of the condition."""
829
+ if cond == True:
830
+ return True
831
+ if isinstance(cond, Eq):
832
+ try:
833
+ diff = cond.lhs - cond.rhs
834
+ if diff.is_commutative:
835
+ return diff.is_zero
836
+ except TypeError:
837
+ pass
838
+
839
+ def as_expr_set_pairs(self, domain=None):
840
+ """Return tuples for each argument of self that give
841
+ the expression and the interval in which it is valid
842
+ which is contained within the given domain.
843
+ If a condition cannot be converted to a set, an error
844
+ will be raised. The variable of the conditions is
845
+ assumed to be real; sets of real values are returned.
846
+
847
+ Examples
848
+ ========
849
+
850
+ >>> from sympy import Piecewise, Interval
851
+ >>> from sympy.abc import x
852
+ >>> p = Piecewise(
853
+ ... (1, x < 2),
854
+ ... (2,(x > 0) & (x < 4)),
855
+ ... (3, True))
856
+ >>> p.as_expr_set_pairs()
857
+ [(1, Interval.open(-oo, 2)),
858
+ (2, Interval.Ropen(2, 4)),
859
+ (3, Interval(4, oo))]
860
+ >>> p.as_expr_set_pairs(Interval(0, 3))
861
+ [(1, Interval.Ropen(0, 2)),
862
+ (2, Interval(2, 3))]
863
+ """
864
+ if domain is None:
865
+ domain = S.Reals
866
+ exp_sets = []
867
+ U = domain
868
+ complex = not domain.is_subset(S.Reals)
869
+ cond_free = set()
870
+ for expr, cond in self.args:
871
+ cond_free |= cond.free_symbols
872
+ if len(cond_free) > 1:
873
+ raise NotImplementedError(filldedent('''
874
+ multivariate conditions are not handled.'''))
875
+ if complex:
876
+ for i in cond.atoms(Relational):
877
+ if not isinstance(i, (Eq, Ne)):
878
+ raise ValueError(filldedent('''
879
+ Inequalities in the complex domain are
880
+ not supported. Try the real domain by
881
+ setting domain=S.Reals'''))
882
+ cond_int = U.intersect(cond.as_set())
883
+ U = U - cond_int
884
+ if cond_int != S.EmptySet:
885
+ exp_sets.append((expr, cond_int))
886
+ return exp_sets
887
+
888
+ def _eval_rewrite_as_ITE(self, *args, **kwargs):
889
+ byfree = {}
890
+ args = list(args)
891
+ default = any(c == True for b, c in args)
892
+ for i, (b, c) in enumerate(args):
893
+ if not isinstance(b, Boolean) and b != True:
894
+ raise TypeError(filldedent('''
895
+ Expecting Boolean or bool but got `%s`
896
+ ''' % func_name(b)))
897
+ if c == True:
898
+ break
899
+ # loop over independent conditions for this b
900
+ for c in c.args if isinstance(c, Or) else [c]:
901
+ free = c.free_symbols
902
+ x = free.pop()
903
+ try:
904
+ byfree[x] = byfree.setdefault(
905
+ x, S.EmptySet).union(c.as_set())
906
+ except NotImplementedError:
907
+ if not default:
908
+ raise NotImplementedError(filldedent('''
909
+ A method to determine whether a multivariate
910
+ conditional is consistent with a complete coverage
911
+ of all variables has not been implemented so the
912
+ rewrite is being stopped after encountering `%s`.
913
+ This error would not occur if a default expression
914
+ like `(foo, True)` were given.
915
+ ''' % c))
916
+ if byfree[x] in (S.UniversalSet, S.Reals):
917
+ # collapse the ith condition to True and break
918
+ args[i] = list(args[i])
919
+ c = args[i][1] = True
920
+ break
921
+ if c == True:
922
+ break
923
+ if c != True:
924
+ raise ValueError(filldedent('''
925
+ Conditions must cover all reals or a final default
926
+ condition `(foo, True)` must be given.
927
+ '''))
928
+ last, _ = args[i] # ignore all past ith arg
929
+ for a, c in reversed(args[:i]):
930
+ last = ITE(c, a, last)
931
+ return _canonical(last)
932
+
933
+ def _eval_rewrite_as_KroneckerDelta(self, *args):
934
+ from sympy.functions.special.tensor_functions import KroneckerDelta
935
+
936
+ rules = {
937
+ And: [False, False],
938
+ Or: [True, True],
939
+ Not: [True, False],
940
+ Eq: [None, None],
941
+ Ne: [None, None]
942
+ }
943
+
944
+ class UnrecognizedCondition(Exception):
945
+ pass
946
+
947
+ def rewrite(cond):
948
+ if isinstance(cond, Eq):
949
+ return KroneckerDelta(*cond.args)
950
+ if isinstance(cond, Ne):
951
+ return 1 - KroneckerDelta(*cond.args)
952
+
953
+ cls, args = type(cond), cond.args
954
+ if cls not in rules:
955
+ raise UnrecognizedCondition(cls)
956
+
957
+ b1, b2 = rules[cls]
958
+ k = Mul(*[1 - rewrite(c) for c in args]) if b1 else Mul(*[rewrite(c) for c in args])
959
+
960
+ if b2:
961
+ return 1 - k
962
+ return k
963
+
964
+ conditions = []
965
+ true_value = None
966
+ for value, cond in args:
967
+ if type(cond) in rules:
968
+ conditions.append((value, cond))
969
+ elif cond is S.true:
970
+ if true_value is None:
971
+ true_value = value
972
+ else:
973
+ return
974
+
975
+ if true_value is not None:
976
+ result = true_value
977
+
978
+ for value, cond in conditions[::-1]:
979
+ try:
980
+ k = rewrite(cond)
981
+ result = k * value + (1 - k) * result
982
+ except UnrecognizedCondition:
983
+ return
984
+
985
+ return result
986
+
987
+
988
+ def piecewise_fold(expr, evaluate=True):
989
+ """
990
+ Takes an expression containing a piecewise function and returns the
991
+ expression in piecewise form. In addition, any ITE conditions are
992
+ rewritten in negation normal form and simplified.
993
+
994
+ The final Piecewise is evaluated (default) but if the raw form
995
+ is desired, send ``evaluate=False``; if trivial evaluation is
996
+ desired, send ``evaluate=None`` and duplicate conditions and
997
+ processing of True and False will be handled.
998
+
999
+ Examples
1000
+ ========
1001
+
1002
+ >>> from sympy import Piecewise, piecewise_fold, S
1003
+ >>> from sympy.abc import x
1004
+ >>> p = Piecewise((x, x < 1), (1, S(1) <= x))
1005
+ >>> piecewise_fold(x*p)
1006
+ Piecewise((x**2, x < 1), (x, True))
1007
+
1008
+ See Also
1009
+ ========
1010
+
1011
+ Piecewise
1012
+ piecewise_exclusive
1013
+ """
1014
+ if not isinstance(expr, Basic) or not expr.has(Piecewise):
1015
+ return expr
1016
+
1017
+ new_args = []
1018
+ if isinstance(expr, (ExprCondPair, Piecewise)):
1019
+ for e, c in expr.args:
1020
+ if not isinstance(e, Piecewise):
1021
+ e = piecewise_fold(e)
1022
+ # we don't keep Piecewise in condition because
1023
+ # it has to be checked to see that it's complete
1024
+ # and we convert it to ITE at that time
1025
+ assert not c.has(Piecewise) # pragma: no cover
1026
+ if isinstance(c, ITE):
1027
+ c = c.to_nnf()
1028
+ c = simplify_logic(c, form='cnf')
1029
+ if isinstance(e, Piecewise):
1030
+ new_args.extend([(piecewise_fold(ei), And(ci, c))
1031
+ for ei, ci in e.args])
1032
+ else:
1033
+ new_args.append((e, c))
1034
+ else:
1035
+ # Given
1036
+ # P1 = Piecewise((e11, c1), (e12, c2), A)
1037
+ # P2 = Piecewise((e21, c1), (e22, c2), B)
1038
+ # ...
1039
+ # the folding of f(P1, P2) is trivially
1040
+ # Piecewise(
1041
+ # (f(e11, e21), c1),
1042
+ # (f(e12, e22), c2),
1043
+ # (f(Piecewise(A), Piecewise(B)), True))
1044
+ # Certain objects end up rewriting themselves as thus, so
1045
+ # we do that grouping before the more generic folding.
1046
+ # The following applies this idea when f = Add or f = Mul
1047
+ # (and the expression is commutative).
1048
+ if expr.is_Add or expr.is_Mul and expr.is_commutative:
1049
+ p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
1050
+ pc = sift(p, lambda x: tuple([c for e,c in x.args]))
1051
+ for c in list(ordered(pc)):
1052
+ if len(pc[c]) > 1:
1053
+ pargs = [list(i.args) for i in pc[c]]
1054
+ # the first one is the same; there may be more
1055
+ com = common_prefix(*[
1056
+ [i.cond for i in j] for j in pargs])
1057
+ n = len(com)
1058
+ collected = []
1059
+ for i in range(n):
1060
+ collected.append((
1061
+ expr.func(*[ai[i].expr for ai in pargs]),
1062
+ com[i]))
1063
+ remains = []
1064
+ for a in pargs:
1065
+ if n == len(a): # no more args
1066
+ continue
1067
+ if a[n].cond == True: # no longer Piecewise
1068
+ remains.append(a[n].expr)
1069
+ else: # restore the remaining Piecewise
1070
+ remains.append(
1071
+ Piecewise(*a[n:], evaluate=False))
1072
+ if remains:
1073
+ collected.append((expr.func(*remains), True))
1074
+ args.append(Piecewise(*collected, evaluate=False))
1075
+ continue
1076
+ args.extend(pc[c])
1077
+ else:
1078
+ args = expr.args
1079
+ # fold
1080
+ folded = list(map(piecewise_fold, args))
1081
+ for ec in product(*[
1082
+ (i.args if isinstance(i, Piecewise) else
1083
+ [(i, true)]) for i in folded]):
1084
+ e, c = zip(*ec)
1085
+ new_args.append((expr.func(*e), And(*c)))
1086
+
1087
+ if evaluate is None:
1088
+ # don't return duplicate conditions, otherwise don't evaluate
1089
+ new_args = list(reversed([(e, c) for c, e in {
1090
+ c: e for e, c in reversed(new_args)}.items()]))
1091
+ rv = Piecewise(*new_args, evaluate=evaluate)
1092
+ if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True:
1093
+ return rv.args[0].expr
1094
+ if any(s.expr.has(Piecewise) for p in rv.atoms(Piecewise) for s in p.args):
1095
+ return piecewise_fold(rv)
1096
+ return rv
1097
+
1098
+
1099
+ def _clip(A, B, k):
1100
+ """Return interval B as intervals that are covered by A (keyed
1101
+ to k) and all other intervals of B not covered by A keyed to -1.
1102
+
1103
+ The reference point of each interval is the rhs; if the lhs is
1104
+ greater than the rhs then an interval of zero width interval will
1105
+ result, e.g. (4, 1) is treated like (1, 1).
1106
+
1107
+ Examples
1108
+ ========
1109
+
1110
+ >>> from sympy.functions.elementary.piecewise import _clip
1111
+ >>> from sympy import Tuple
1112
+ >>> A = Tuple(1, 3)
1113
+ >>> B = Tuple(2, 4)
1114
+ >>> _clip(A, B, 0)
1115
+ [(2, 3, 0), (3, 4, -1)]
1116
+
1117
+ Interpretation: interval portion (2, 3) of interval (2, 4) is
1118
+ covered by interval (1, 3) and is keyed to 0 as requested;
1119
+ interval (3, 4) was not covered by (1, 3) and is keyed to -1.
1120
+ """
1121
+ a, b = B
1122
+ c, d = A
1123
+ c, d = Min(Max(c, a), b), Min(Max(d, a), b)
1124
+ a, b = Min(a, b), b
1125
+ p = []
1126
+ if a != c:
1127
+ p.append((a, c, -1))
1128
+ else:
1129
+ pass
1130
+ if c != d:
1131
+ p.append((c, d, k))
1132
+ else:
1133
+ pass
1134
+ if b != d:
1135
+ if d == c and p and p[-1][-1] == -1:
1136
+ p[-1] = p[-1][0], b, -1
1137
+ else:
1138
+ p.append((d, b, -1))
1139
+ else:
1140
+ pass
1141
+
1142
+ return p
1143
+
1144
+
1145
+ def piecewise_simplify_arguments(expr, **kwargs):
1146
+ from sympy.simplify.simplify import simplify
1147
+
1148
+ # simplify conditions
1149
+ f1 = expr.args[0].cond.free_symbols
1150
+ args = None
1151
+ if len(f1) == 1 and not expr.atoms(Eq):
1152
+ x = f1.pop()
1153
+ # this won't return intervals involving Eq
1154
+ # and it won't handle symbols treated as
1155
+ # booleans
1156
+ ok, abe_ = expr._intervals(x, err_on_Eq=True)
1157
+ def include(c, x, a):
1158
+ "return True if c.subs(x, a) is True, else False"
1159
+ try:
1160
+ return c.subs(x, a) == True
1161
+ except TypeError:
1162
+ return False
1163
+ if ok:
1164
+ args = []
1165
+ covered = S.EmptySet
1166
+ from sympy.sets.sets import Interval
1167
+ for a, b, e, i in abe_:
1168
+ c = expr.args[i].cond
1169
+ incl_a = include(c, x, a)
1170
+ incl_b = include(c, x, b)
1171
+ iv = Interval(a, b, not incl_a, not incl_b)
1172
+ cset = iv - covered
1173
+ if not cset:
1174
+ continue
1175
+ if incl_a and incl_b:
1176
+ if a.is_infinite and b.is_infinite:
1177
+ c = S.true
1178
+ elif b.is_infinite:
1179
+ c = (x >= a)
1180
+ elif a in covered or a.is_infinite:
1181
+ c = (x <= b)
1182
+ else:
1183
+ c = And(a <= x, x <= b)
1184
+ elif incl_a:
1185
+ if a in covered or a.is_infinite:
1186
+ c = (x < b)
1187
+ else:
1188
+ c = And(a <= x, x < b)
1189
+ elif incl_b:
1190
+ if b.is_infinite:
1191
+ c = (x > a)
1192
+ else:
1193
+ c = (x <= b)
1194
+ else:
1195
+ if a in covered:
1196
+ c = (x < b)
1197
+ else:
1198
+ c = And(a < x, x < b)
1199
+ covered |= iv
1200
+ if a is S.NegativeInfinity and incl_a:
1201
+ covered |= {S.NegativeInfinity}
1202
+ if b is S.Infinity and incl_b:
1203
+ covered |= {S.Infinity}
1204
+ args.append((e, c))
1205
+ if not S.Reals.is_subset(covered):
1206
+ args.append((Undefined, True))
1207
+ if args is None:
1208
+ args = list(expr.args)
1209
+ for i in range(len(args)):
1210
+ e, c = args[i]
1211
+ if isinstance(c, Basic):
1212
+ c = simplify(c, **kwargs)
1213
+ args[i] = (e, c)
1214
+
1215
+ # simplify expressions
1216
+ doit = kwargs.pop('doit', None)
1217
+ for i in range(len(args)):
1218
+ e, c = args[i]
1219
+ if isinstance(e, Basic):
1220
+ # Skip doit to avoid growth at every call for some integrals
1221
+ # and sums, see sympy/sympy#17165
1222
+ newe = simplify(e, doit=False, **kwargs)
1223
+ if newe != e:
1224
+ e = newe
1225
+ args[i] = (e, c)
1226
+
1227
+ # restore kwargs flag
1228
+ if doit is not None:
1229
+ kwargs['doit'] = doit
1230
+
1231
+ return Piecewise(*args)
1232
+
1233
+
1234
+ def _piecewise_collapse_arguments(_args):
1235
+ newargs = [] # the unevaluated conditions
1236
+ current_cond = set() # the conditions up to a given e, c pair
1237
+ for expr, cond in _args:
1238
+ cond = cond.replace(
1239
+ lambda _: _.is_Relational, _canonical_coeff)
1240
+ # Check here if expr is a Piecewise and collapse if one of
1241
+ # the conds in expr matches cond. This allows the collapsing
1242
+ # of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
1243
+ # This is important when using piecewise_fold to simplify
1244
+ # multiple Piecewise instances having the same conds.
1245
+ # Eventually, this code should be able to collapse Piecewise's
1246
+ # having different intervals, but this will probably require
1247
+ # using the new assumptions.
1248
+ if isinstance(expr, Piecewise):
1249
+ unmatching = []
1250
+ for i, (e, c) in enumerate(expr.args):
1251
+ if c in current_cond:
1252
+ # this would already have triggered
1253
+ continue
1254
+ if c == cond:
1255
+ if c != True:
1256
+ # nothing past this condition will ever
1257
+ # trigger and only those args before this
1258
+ # that didn't match a previous condition
1259
+ # could possibly trigger
1260
+ if unmatching:
1261
+ expr = Piecewise(*(
1262
+ unmatching + [(e, c)]))
1263
+ else:
1264
+ expr = e
1265
+ break
1266
+ else:
1267
+ unmatching.append((e, c))
1268
+
1269
+ # check for condition repeats
1270
+ got = False
1271
+ # -- if an And contains a condition that was
1272
+ # already encountered, then the And will be
1273
+ # False: if the previous condition was False
1274
+ # then the And will be False and if the previous
1275
+ # condition is True then then we wouldn't get to
1276
+ # this point. In either case, we can skip this condition.
1277
+ for i in ([cond] +
1278
+ (list(cond.args) if isinstance(cond, And) else
1279
+ [])):
1280
+ if i in current_cond:
1281
+ got = True
1282
+ break
1283
+ if got:
1284
+ continue
1285
+
1286
+ # -- if not(c) is already in current_cond then c is
1287
+ # a redundant condition in an And. This does not
1288
+ # apply to Or, however: (e1, c), (e2, Or(~c, d))
1289
+ # is not (e1, c), (e2, d) because if c and d are
1290
+ # both False this would give no results when the
1291
+ # true answer should be (e2, True)
1292
+ if isinstance(cond, And):
1293
+ nonredundant = []
1294
+ for c in cond.args:
1295
+ if isinstance(c, Relational):
1296
+ if c.negated.canonical in current_cond:
1297
+ continue
1298
+ # if a strict inequality appears after
1299
+ # a non-strict one, then the condition is
1300
+ # redundant
1301
+ if isinstance(c, (Lt, Gt)) and (
1302
+ c.weak in current_cond):
1303
+ cond = False
1304
+ break
1305
+ nonredundant.append(c)
1306
+ else:
1307
+ cond = cond.func(*nonredundant)
1308
+ elif isinstance(cond, Relational):
1309
+ if cond.negated.canonical in current_cond:
1310
+ cond = S.true
1311
+
1312
+ current_cond.add(cond)
1313
+
1314
+ # collect successive e,c pairs when exprs or cond match
1315
+ if newargs:
1316
+ if newargs[-1].expr == expr:
1317
+ orcond = Or(cond, newargs[-1].cond)
1318
+ if isinstance(orcond, (And, Or)):
1319
+ orcond = distribute_and_over_or(orcond)
1320
+ newargs[-1] = ExprCondPair(expr, orcond)
1321
+ continue
1322
+ elif newargs[-1].cond == cond:
1323
+ continue
1324
+ newargs.append(ExprCondPair(expr, cond))
1325
+ return newargs
1326
+
1327
+
1328
+ _blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
1329
+ getattr(e.rhs, '_diff_wrt', None) or
1330
+ isinstance(e.rhs, (Rational, NumberSymbol)))
1331
+
1332
+
1333
+ def piecewise_simplify(expr, **kwargs):
1334
+ expr = piecewise_simplify_arguments(expr, **kwargs)
1335
+ if not isinstance(expr, Piecewise):
1336
+ return expr
1337
+ args = list(expr.args)
1338
+
1339
+ args = _piecewise_simplify_eq_and(args)
1340
+ args = _piecewise_simplify_equal_to_next_segment(args)
1341
+ return Piecewise(*args)
1342
+
1343
+
1344
+ def _piecewise_simplify_equal_to_next_segment(args):
1345
+ """
1346
+ See if expressions valid for an Equal expression happens to evaluate
1347
+ to the same function as in the next piecewise segment, see:
1348
+ https://github.com/sympy/sympy/issues/8458
1349
+ """
1350
+ prevexpr = None
1351
+ for i, (expr, cond) in reversed(list(enumerate(args))):
1352
+ if prevexpr is not None:
1353
+ if isinstance(cond, And):
1354
+ eqs, other = sift(cond.args,
1355
+ lambda i: isinstance(i, Eq), binary=True)
1356
+ elif isinstance(cond, Eq):
1357
+ eqs, other = [cond], []
1358
+ else:
1359
+ eqs = other = []
1360
+ _prevexpr = prevexpr
1361
+ _expr = expr
1362
+ if eqs and not other:
1363
+ eqs = list(ordered(eqs))
1364
+ for e in eqs:
1365
+ # allow 2 args to collapse into 1 for any e
1366
+ # otherwise limit simplification to only simple-arg
1367
+ # Eq instances
1368
+ if len(args) == 2 or _blessed(e):
1369
+ _prevexpr = _prevexpr.subs(*e.args)
1370
+ _expr = _expr.subs(*e.args)
1371
+ # Did it evaluate to the same?
1372
+ if _prevexpr == _expr:
1373
+ # Set the expression for the Not equal section to the same
1374
+ # as the next. These will be merged when creating the new
1375
+ # Piecewise
1376
+ args[i] = args[i].func(args[i + 1][0], cond)
1377
+ else:
1378
+ # Update the expression that we compare against
1379
+ prevexpr = expr
1380
+ else:
1381
+ prevexpr = expr
1382
+ return args
1383
+
1384
+
1385
+ def _piecewise_simplify_eq_and(args):
1386
+ """
1387
+ Try to simplify conditions and the expression for
1388
+ equalities that are part of the condition, e.g.
1389
+ Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
1390
+ -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
1391
+ """
1392
+ for i, (expr, cond) in enumerate(args):
1393
+ if isinstance(cond, And):
1394
+ eqs, other = sift(cond.args,
1395
+ lambda i: isinstance(i, Eq), binary=True)
1396
+ elif isinstance(cond, Eq):
1397
+ eqs, other = [cond], []
1398
+ else:
1399
+ eqs = other = []
1400
+ if eqs:
1401
+ eqs = list(ordered(eqs))
1402
+ for j, e in enumerate(eqs):
1403
+ # these blessed lhs objects behave like Symbols
1404
+ # and the rhs are simple replacements for the "symbols"
1405
+ if _blessed(e):
1406
+ expr = expr.subs(*e.args)
1407
+ eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
1408
+ other = [ei.subs(*e.args) for ei in other]
1409
+ cond = And(*(eqs + other))
1410
+ args[i] = args[i].func(expr, cond)
1411
+ return args
1412
+
1413
+
1414
+ def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
1415
+ """
1416
+ Rewrite :class:`Piecewise` with mutually exclusive conditions.
1417
+
1418
+ Explanation
1419
+ ===========
1420
+
1421
+ SymPy represents the conditions of a :class:`Piecewise` in an
1422
+ "if-elif"-fashion, allowing more than one condition to be simultaneously
1423
+ True. The interpretation is that the first condition that is True is the
1424
+ case that holds. While this is a useful representation computationally it
1425
+ is not how a piecewise formula is typically shown in a mathematical text.
1426
+ The :func:`piecewise_exclusive` function can be used to rewrite any
1427
+ :class:`Piecewise` with more typical mutually exclusive conditions.
1428
+
1429
+ Note that further manipulation of the resulting :class:`Piecewise`, e.g.
1430
+ simplifying it, will most likely make it non-exclusive. Hence, this is
1431
+ primarily a function to be used in conjunction with printing the Piecewise
1432
+ or if one would like to reorder the expression-condition pairs.
1433
+
1434
+ If it is not possible to determine that all possibilities are covered by
1435
+ the different cases of the :class:`Piecewise` then a final
1436
+ :class:`~sympy.core.numbers.NaN` case will be included explicitly. This
1437
+ can be prevented by passing ``skip_nan=True``.
1438
+
1439
+ Examples
1440
+ ========
1441
+
1442
+ >>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
1443
+ >>> x = Symbol('x', real=True)
1444
+ >>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
1445
+ >>> piecewise_exclusive(p)
1446
+ Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
1447
+ >>> piecewise_exclusive(Piecewise((2, x > 1)))
1448
+ Piecewise((2, x > 1), (nan, x <= 1))
1449
+ >>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
1450
+ Piecewise((2, x > 1))
1451
+
1452
+ Parameters
1453
+ ==========
1454
+
1455
+ expr: a SymPy expression.
1456
+ Any :class:`Piecewise` in the expression will be rewritten.
1457
+ skip_nan: ``bool`` (default ``False``)
1458
+ If ``skip_nan`` is set to ``True`` then a final
1459
+ :class:`~sympy.core.numbers.NaN` case will not be included.
1460
+ deep: ``bool`` (default ``True``)
1461
+ If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
1462
+ any :class:`Piecewise` subexpressions in ``expr`` rather than just
1463
+ rewriting ``expr`` itself.
1464
+
1465
+ Returns
1466
+ =======
1467
+
1468
+ An expression equivalent to ``expr`` but where all :class:`Piecewise` have
1469
+ been rewritten with mutually exclusive conditions.
1470
+
1471
+ See Also
1472
+ ========
1473
+
1474
+ Piecewise
1475
+ piecewise_fold
1476
+ """
1477
+
1478
+ def make_exclusive(*pwargs):
1479
+
1480
+ cumcond = false
1481
+ newargs = []
1482
+
1483
+ # Handle the first n-1 cases
1484
+ for expr_i, cond_i in pwargs[:-1]:
1485
+ cancond = And(cond_i, Not(cumcond)).simplify()
1486
+ cumcond = Or(cond_i, cumcond).simplify()
1487
+ newargs.append((expr_i, cancond))
1488
+
1489
+ # For the nth case defer simplification of cumcond
1490
+ expr_n, cond_n = pwargs[-1]
1491
+ cancond_n = And(cond_n, Not(cumcond)).simplify()
1492
+ newargs.append((expr_n, cancond_n))
1493
+
1494
+ if not skip_nan:
1495
+ cumcond = Or(cond_n, cumcond).simplify()
1496
+ if cumcond is not true:
1497
+ newargs.append((Undefined, Not(cumcond).simplify()))
1498
+
1499
+ return Piecewise(*newargs, evaluate=False)
1500
+
1501
+ if deep:
1502
+ return expr.replace(Piecewise, make_exclusive)
1503
+ elif isinstance(expr, Piecewise):
1504
+ return make_exclusive(*expr.args)
1505
+ else:
1506
+ return expr
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'TWave',
3
+
4
+ 'RayTransferMatrix', 'FreeSpace', 'FlatRefraction', 'CurvedRefraction',
5
+ 'FlatMirror', 'CurvedMirror', 'ThinLens', 'GeometricRay', 'BeamParameter',
6
+ 'waist2rayleigh', 'rayleigh2waist', 'geometric_conj_ab',
7
+ 'geometric_conj_af', 'geometric_conj_bf', 'gaussian_conj',
8
+ 'conjugate_gauss_beams',
9
+
10
+ 'Medium',
11
+
12
+ 'refraction_angle', 'deviation', 'fresnel_coefficients', 'brewster_angle',
13
+ 'critical_angle', 'lens_makers_formula', 'mirror_formula', 'lens_formula',
14
+ 'hyperfocal_distance', 'transverse_magnification',
15
+
16
+ 'jones_vector', 'stokes_vector', 'jones_2_stokes', 'linear_polarizer',
17
+ 'phase_retarder', 'half_wave_retarder', 'quarter_wave_retarder',
18
+ 'transmissive_filter', 'reflective_filter', 'mueller_matrix',
19
+ 'polarizing_beam_splitter',
20
+ ]
21
+ from .waves import TWave
22
+
23
+ from .gaussopt import (RayTransferMatrix, FreeSpace, FlatRefraction,
24
+ CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay,
25
+ BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,
26
+ geometric_conj_af, geometric_conj_bf, gaussian_conj,
27
+ conjugate_gauss_beams)
28
+
29
+ from .medium import Medium
30
+
31
+ from .utils import (refraction_angle, deviation, fresnel_coefficients,
32
+ brewster_angle, critical_angle, lens_makers_formula, mirror_formula,
33
+ lens_formula, hyperfocal_distance, transverse_magnification)
34
+
35
+ from .polarization import (jones_vector, stokes_vector, jones_2_stokes,
36
+ linear_polarizer, phase_retarder, half_wave_retarder,
37
+ quarter_wave_retarder, transmissive_filter, reflective_filter,
38
+ mueller_matrix, polarizing_beam_splitter)
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.51 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/gaussopt.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/medium.cpython-310.pyc ADDED
Binary file (7.52 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/polarization.cpython-310.pyc ADDED
Binary file (22.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/utils.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/waves.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py ADDED
@@ -0,0 +1,923 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gaussian optics.
3
+
4
+ The module implements:
5
+
6
+ - Ray transfer matrices for geometrical and gaussian optics.
7
+
8
+ See RayTransferMatrix, GeometricRay and BeamParameter
9
+
10
+ - Conjugation relations for geometrical and gaussian optics.
11
+
12
+ See geometric_conj*, gauss_conj and conjugate_gauss_beams
13
+
14
+ The conventions for the distances are as follows:
15
+
16
+ focal distance
17
+ positive for convergent lenses
18
+ object distance
19
+ positive for real objects
20
+ image distance
21
+ positive for real images
22
+ """
23
+
24
+ __all__ = [
25
+ 'RayTransferMatrix',
26
+ 'FreeSpace',
27
+ 'FlatRefraction',
28
+ 'CurvedRefraction',
29
+ 'FlatMirror',
30
+ 'CurvedMirror',
31
+ 'ThinLens',
32
+ 'GeometricRay',
33
+ 'BeamParameter',
34
+ 'waist2rayleigh',
35
+ 'rayleigh2waist',
36
+ 'geometric_conj_ab',
37
+ 'geometric_conj_af',
38
+ 'geometric_conj_bf',
39
+ 'gaussian_conj',
40
+ 'conjugate_gauss_beams',
41
+ ]
42
+
43
+
44
+ from sympy.core.expr import Expr
45
+ from sympy.core.numbers import (I, pi)
46
+ from sympy.core.sympify import sympify
47
+ from sympy.functions.elementary.complexes import (im, re)
48
+ from sympy.functions.elementary.miscellaneous import sqrt
49
+ from sympy.functions.elementary.trigonometric import atan2
50
+ from sympy.matrices.dense import Matrix, MutableDenseMatrix
51
+ from sympy.polys.rationaltools import together
52
+ from sympy.utilities.misc import filldedent
53
+
54
+ ###
55
+ # A, B, C, D matrices
56
+ ###
57
+
58
+
59
+ class RayTransferMatrix(MutableDenseMatrix):
60
+ """
61
+ Base class for a Ray Transfer Matrix.
62
+
63
+ It should be used if there is not already a more specific subclass mentioned
64
+ in See Also.
65
+
66
+ Parameters
67
+ ==========
68
+
69
+ parameters :
70
+ A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
71
+
72
+ Examples
73
+ ========
74
+
75
+ >>> from sympy.physics.optics import RayTransferMatrix, ThinLens
76
+ >>> from sympy import Symbol, Matrix
77
+
78
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
79
+ >>> mat
80
+ Matrix([
81
+ [1, 2],
82
+ [3, 4]])
83
+
84
+ >>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
85
+ Matrix([
86
+ [1, 2],
87
+ [3, 4]])
88
+
89
+ >>> mat.A
90
+ 1
91
+
92
+ >>> f = Symbol('f')
93
+ >>> lens = ThinLens(f)
94
+ >>> lens
95
+ Matrix([
96
+ [ 1, 0],
97
+ [-1/f, 1]])
98
+
99
+ >>> lens.C
100
+ -1/f
101
+
102
+ See Also
103
+ ========
104
+
105
+ GeometricRay, BeamParameter,
106
+ FreeSpace, FlatRefraction, CurvedRefraction,
107
+ FlatMirror, CurvedMirror, ThinLens
108
+
109
+ References
110
+ ==========
111
+
112
+ .. [1] https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
113
+ """
114
+
115
+ def __new__(cls, *args):
116
+
117
+ if len(args) == 4:
118
+ temp = ((args[0], args[1]), (args[2], args[3]))
119
+ elif len(args) == 1 \
120
+ and isinstance(args[0], Matrix) \
121
+ and args[0].shape == (2, 2):
122
+ temp = args[0]
123
+ else:
124
+ raise ValueError(filldedent('''
125
+ Expecting 2x2 Matrix or the 4 elements of
126
+ the Matrix but got %s''' % str(args)))
127
+ return Matrix.__new__(cls, temp)
128
+
129
+ def __mul__(self, other):
130
+ if isinstance(other, RayTransferMatrix):
131
+ return RayTransferMatrix(Matrix.__mul__(self, other))
132
+ elif isinstance(other, GeometricRay):
133
+ return GeometricRay(Matrix.__mul__(self, other))
134
+ elif isinstance(other, BeamParameter):
135
+ temp = self*Matrix(((other.q,), (1,)))
136
+ q = (temp[0]/temp[1]).expand(complex=True)
137
+ return BeamParameter(other.wavelen,
138
+ together(re(q)),
139
+ z_r=together(im(q)))
140
+ else:
141
+ return Matrix.__mul__(self, other)
142
+
143
+ @property
144
+ def A(self):
145
+ """
146
+ The A parameter of the Matrix.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.physics.optics import RayTransferMatrix
152
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
153
+ >>> mat.A
154
+ 1
155
+ """
156
+ return self[0, 0]
157
+
158
+ @property
159
+ def B(self):
160
+ """
161
+ The B parameter of the Matrix.
162
+
163
+ Examples
164
+ ========
165
+
166
+ >>> from sympy.physics.optics import RayTransferMatrix
167
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
168
+ >>> mat.B
169
+ 2
170
+ """
171
+ return self[0, 1]
172
+
173
+ @property
174
+ def C(self):
175
+ """
176
+ The C parameter of the Matrix.
177
+
178
+ Examples
179
+ ========
180
+
181
+ >>> from sympy.physics.optics import RayTransferMatrix
182
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
183
+ >>> mat.C
184
+ 3
185
+ """
186
+ return self[1, 0]
187
+
188
+ @property
189
+ def D(self):
190
+ """
191
+ The D parameter of the Matrix.
192
+
193
+ Examples
194
+ ========
195
+
196
+ >>> from sympy.physics.optics import RayTransferMatrix
197
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
198
+ >>> mat.D
199
+ 4
200
+ """
201
+ return self[1, 1]
202
+
203
+
204
+ class FreeSpace(RayTransferMatrix):
205
+ """
206
+ Ray Transfer Matrix for free space.
207
+
208
+ Parameters
209
+ ==========
210
+
211
+ distance
212
+
213
+ See Also
214
+ ========
215
+
216
+ RayTransferMatrix
217
+
218
+ Examples
219
+ ========
220
+
221
+ >>> from sympy.physics.optics import FreeSpace
222
+ >>> from sympy import symbols
223
+ >>> d = symbols('d')
224
+ >>> FreeSpace(d)
225
+ Matrix([
226
+ [1, d],
227
+ [0, 1]])
228
+ """
229
+ def __new__(cls, d):
230
+ return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
231
+
232
+
233
+ class FlatRefraction(RayTransferMatrix):
234
+ """
235
+ Ray Transfer Matrix for refraction.
236
+
237
+ Parameters
238
+ ==========
239
+
240
+ n1 :
241
+ Refractive index of one medium.
242
+ n2 :
243
+ Refractive index of other medium.
244
+
245
+ See Also
246
+ ========
247
+
248
+ RayTransferMatrix
249
+
250
+ Examples
251
+ ========
252
+
253
+ >>> from sympy.physics.optics import FlatRefraction
254
+ >>> from sympy import symbols
255
+ >>> n1, n2 = symbols('n1 n2')
256
+ >>> FlatRefraction(n1, n2)
257
+ Matrix([
258
+ [1, 0],
259
+ [0, n1/n2]])
260
+ """
261
+ def __new__(cls, n1, n2):
262
+ n1, n2 = map(sympify, (n1, n2))
263
+ return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
264
+
265
+
266
+ class CurvedRefraction(RayTransferMatrix):
267
+ """
268
+ Ray Transfer Matrix for refraction on curved interface.
269
+
270
+ Parameters
271
+ ==========
272
+
273
+ R :
274
+ Radius of curvature (positive for concave).
275
+ n1 :
276
+ Refractive index of one medium.
277
+ n2 :
278
+ Refractive index of other medium.
279
+
280
+ See Also
281
+ ========
282
+
283
+ RayTransferMatrix
284
+
285
+ Examples
286
+ ========
287
+
288
+ >>> from sympy.physics.optics import CurvedRefraction
289
+ >>> from sympy import symbols
290
+ >>> R, n1, n2 = symbols('R n1 n2')
291
+ >>> CurvedRefraction(R, n1, n2)
292
+ Matrix([
293
+ [ 1, 0],
294
+ [(n1 - n2)/(R*n2), n1/n2]])
295
+ """
296
+ def __new__(cls, R, n1, n2):
297
+ R, n1, n2 = map(sympify, (R, n1, n2))
298
+ return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
299
+
300
+
301
+ class FlatMirror(RayTransferMatrix):
302
+ """
303
+ Ray Transfer Matrix for reflection.
304
+
305
+ See Also
306
+ ========
307
+
308
+ RayTransferMatrix
309
+
310
+ Examples
311
+ ========
312
+
313
+ >>> from sympy.physics.optics import FlatMirror
314
+ >>> FlatMirror()
315
+ Matrix([
316
+ [1, 0],
317
+ [0, 1]])
318
+ """
319
+ def __new__(cls):
320
+ return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
321
+
322
+
323
+ class CurvedMirror(RayTransferMatrix):
324
+ """
325
+ Ray Transfer Matrix for reflection from curved surface.
326
+
327
+ Parameters
328
+ ==========
329
+
330
+ R : radius of curvature (positive for concave)
331
+
332
+ See Also
333
+ ========
334
+
335
+ RayTransferMatrix
336
+
337
+ Examples
338
+ ========
339
+
340
+ >>> from sympy.physics.optics import CurvedMirror
341
+ >>> from sympy import symbols
342
+ >>> R = symbols('R')
343
+ >>> CurvedMirror(R)
344
+ Matrix([
345
+ [ 1, 0],
346
+ [-2/R, 1]])
347
+ """
348
+ def __new__(cls, R):
349
+ R = sympify(R)
350
+ return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
351
+
352
+
353
+ class ThinLens(RayTransferMatrix):
354
+ """
355
+ Ray Transfer Matrix for a thin lens.
356
+
357
+ Parameters
358
+ ==========
359
+
360
+ f :
361
+ The focal distance.
362
+
363
+ See Also
364
+ ========
365
+
366
+ RayTransferMatrix
367
+
368
+ Examples
369
+ ========
370
+
371
+ >>> from sympy.physics.optics import ThinLens
372
+ >>> from sympy import symbols
373
+ >>> f = symbols('f')
374
+ >>> ThinLens(f)
375
+ Matrix([
376
+ [ 1, 0],
377
+ [-1/f, 1]])
378
+ """
379
+ def __new__(cls, f):
380
+ f = sympify(f)
381
+ return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
382
+
383
+
384
+ ###
385
+ # Representation for geometric ray
386
+ ###
387
+
388
+ class GeometricRay(MutableDenseMatrix):
389
+ """
390
+ Representation for a geometric ray in the Ray Transfer Matrix formalism.
391
+
392
+ Parameters
393
+ ==========
394
+
395
+ h : height, and
396
+ angle : angle, or
397
+ matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
398
+
399
+ Examples
400
+ ========
401
+
402
+ >>> from sympy.physics.optics import GeometricRay, FreeSpace
403
+ >>> from sympy import symbols, Matrix
404
+ >>> d, h, angle = symbols('d, h, angle')
405
+
406
+ >>> GeometricRay(h, angle)
407
+ Matrix([
408
+ [ h],
409
+ [angle]])
410
+
411
+ >>> FreeSpace(d)*GeometricRay(h, angle)
412
+ Matrix([
413
+ [angle*d + h],
414
+ [ angle]])
415
+
416
+ >>> GeometricRay( Matrix( ((h,), (angle,)) ) )
417
+ Matrix([
418
+ [ h],
419
+ [angle]])
420
+
421
+ See Also
422
+ ========
423
+
424
+ RayTransferMatrix
425
+
426
+ """
427
+
428
+ def __new__(cls, *args):
429
+ if len(args) == 1 and isinstance(args[0], Matrix) \
430
+ and args[0].shape == (2, 1):
431
+ temp = args[0]
432
+ elif len(args) == 2:
433
+ temp = ((args[0],), (args[1],))
434
+ else:
435
+ raise ValueError(filldedent('''
436
+ Expecting 2x1 Matrix or the 2 elements of
437
+ the Matrix but got %s''' % str(args)))
438
+ return Matrix.__new__(cls, temp)
439
+
440
+ @property
441
+ def height(self):
442
+ """
443
+ The distance from the optical axis.
444
+
445
+ Examples
446
+ ========
447
+
448
+ >>> from sympy.physics.optics import GeometricRay
449
+ >>> from sympy import symbols
450
+ >>> h, angle = symbols('h, angle')
451
+ >>> gRay = GeometricRay(h, angle)
452
+ >>> gRay.height
453
+ h
454
+ """
455
+ return self[0]
456
+
457
+ @property
458
+ def angle(self):
459
+ """
460
+ The angle with the optical axis.
461
+
462
+ Examples
463
+ ========
464
+
465
+ >>> from sympy.physics.optics import GeometricRay
466
+ >>> from sympy import symbols
467
+ >>> h, angle = symbols('h, angle')
468
+ >>> gRay = GeometricRay(h, angle)
469
+ >>> gRay.angle
470
+ angle
471
+ """
472
+ return self[1]
473
+
474
+
475
+ ###
476
+ # Representation for gauss beam
477
+ ###
478
+
479
+ class BeamParameter(Expr):
480
+ """
481
+ Representation for a gaussian ray in the Ray Transfer Matrix formalism.
482
+
483
+ Parameters
484
+ ==========
485
+
486
+ wavelen : the wavelength,
487
+ z : the distance to waist, and
488
+ w : the waist, or
489
+ z_r : the rayleigh range.
490
+ n : the refractive index of medium.
491
+
492
+ Examples
493
+ ========
494
+
495
+ >>> from sympy.physics.optics import BeamParameter
496
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
497
+ >>> p.q
498
+ 1 + 1.88679245283019*I*pi
499
+
500
+ >>> p.q.n()
501
+ 1.0 + 5.92753330865999*I
502
+ >>> p.w_0.n()
503
+ 0.00100000000000000
504
+ >>> p.z_r.n()
505
+ 5.92753330865999
506
+
507
+ >>> from sympy.physics.optics import FreeSpace
508
+ >>> fs = FreeSpace(10)
509
+ >>> p1 = fs*p
510
+ >>> p.w.n()
511
+ 0.00101413072159615
512
+ >>> p1.w.n()
513
+ 0.00210803120913829
514
+
515
+ See Also
516
+ ========
517
+
518
+ RayTransferMatrix
519
+
520
+ References
521
+ ==========
522
+
523
+ .. [1] https://en.wikipedia.org/wiki/Complex_beam_parameter
524
+ .. [2] https://en.wikipedia.org/wiki/Gaussian_beam
525
+ """
526
+ #TODO A class Complex may be implemented. The BeamParameter may
527
+ # subclass it. See:
528
+ # https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
529
+
530
+ def __new__(cls, wavelen, z, z_r=None, w=None, n=1):
531
+ wavelen = sympify(wavelen)
532
+ z = sympify(z)
533
+ n = sympify(n)
534
+
535
+ if z_r is not None and w is None:
536
+ z_r = sympify(z_r)
537
+ elif w is not None and z_r is None:
538
+ z_r = waist2rayleigh(sympify(w), wavelen, n)
539
+ elif z_r is None and w is None:
540
+ raise ValueError('Must specify one of w and z_r.')
541
+
542
+ return Expr.__new__(cls, wavelen, z, z_r, n)
543
+
544
+ @property
545
+ def wavelen(self):
546
+ return self.args[0]
547
+
548
+ @property
549
+ def z(self):
550
+ return self.args[1]
551
+
552
+ @property
553
+ def z_r(self):
554
+ return self.args[2]
555
+
556
+ @property
557
+ def n(self):
558
+ return self.args[3]
559
+
560
+ @property
561
+ def q(self):
562
+ """
563
+ The complex parameter representing the beam.
564
+
565
+ Examples
566
+ ========
567
+
568
+ >>> from sympy.physics.optics import BeamParameter
569
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
570
+ >>> p.q
571
+ 1 + 1.88679245283019*I*pi
572
+ """
573
+ return self.z + I*self.z_r
574
+
575
+ @property
576
+ def radius(self):
577
+ """
578
+ The radius of curvature of the phase front.
579
+
580
+ Examples
581
+ ========
582
+
583
+ >>> from sympy.physics.optics import BeamParameter
584
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
585
+ >>> p.radius
586
+ 1 + 3.55998576005696*pi**2
587
+ """
588
+ return self.z*(1 + (self.z_r/self.z)**2)
589
+
590
+ @property
591
+ def w(self):
592
+ """
593
+ The radius of the beam w(z), at any position z along the beam.
594
+ The beam radius at `1/e^2` intensity (axial value).
595
+
596
+ See Also
597
+ ========
598
+
599
+ w_0 :
600
+ The minimal radius of beam.
601
+
602
+ Examples
603
+ ========
604
+
605
+ >>> from sympy.physics.optics import BeamParameter
606
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
607
+ >>> p.w
608
+ 0.001*sqrt(0.2809/pi**2 + 1)
609
+ """
610
+ return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
611
+
612
+ @property
613
+ def w_0(self):
614
+ """
615
+ The minimal radius of beam at `1/e^2` intensity (peak value).
616
+
617
+ See Also
618
+ ========
619
+
620
+ w : the beam radius at `1/e^2` intensity (axial value).
621
+
622
+ Examples
623
+ ========
624
+
625
+ >>> from sympy.physics.optics import BeamParameter
626
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
627
+ >>> p.w_0
628
+ 0.00100000000000000
629
+ """
630
+ return sqrt(self.z_r/(pi*self.n)*self.wavelen)
631
+
632
+ @property
633
+ def divergence(self):
634
+ """
635
+ Half of the total angular spread.
636
+
637
+ Examples
638
+ ========
639
+
640
+ >>> from sympy.physics.optics import BeamParameter
641
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
642
+ >>> p.divergence
643
+ 0.00053/pi
644
+ """
645
+ return self.wavelen/pi/self.w_0
646
+
647
+ @property
648
+ def gouy(self):
649
+ """
650
+ The Gouy phase.
651
+
652
+ Examples
653
+ ========
654
+
655
+ >>> from sympy.physics.optics import BeamParameter
656
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
657
+ >>> p.gouy
658
+ atan(0.53/pi)
659
+ """
660
+ return atan2(self.z, self.z_r)
661
+
662
+ @property
663
+ def waist_approximation_limit(self):
664
+ """
665
+ The minimal waist for which the gauss beam approximation is valid.
666
+
667
+ Explanation
668
+ ===========
669
+
670
+ The gauss beam is a solution to the paraxial equation. For curvatures
671
+ that are too great it is not a valid approximation.
672
+
673
+ Examples
674
+ ========
675
+
676
+ >>> from sympy.physics.optics import BeamParameter
677
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
678
+ >>> p.waist_approximation_limit
679
+ 1.06e-6/pi
680
+ """
681
+ return 2*self.wavelen/pi
682
+
683
+
684
+ ###
685
+ # Utilities
686
+ ###
687
+
688
+ def waist2rayleigh(w, wavelen, n=1):
689
+ """
690
+ Calculate the rayleigh range from the waist of a gaussian beam.
691
+
692
+ See Also
693
+ ========
694
+
695
+ rayleigh2waist, BeamParameter
696
+
697
+ Examples
698
+ ========
699
+
700
+ >>> from sympy.physics.optics import waist2rayleigh
701
+ >>> from sympy import symbols
702
+ >>> w, wavelen = symbols('w wavelen')
703
+ >>> waist2rayleigh(w, wavelen)
704
+ pi*w**2/wavelen
705
+ """
706
+ w, wavelen = map(sympify, (w, wavelen))
707
+ return w**2*n*pi/wavelen
708
+
709
+
710
+ def rayleigh2waist(z_r, wavelen):
711
+ """Calculate the waist from the rayleigh range of a gaussian beam.
712
+
713
+ See Also
714
+ ========
715
+
716
+ waist2rayleigh, BeamParameter
717
+
718
+ Examples
719
+ ========
720
+
721
+ >>> from sympy.physics.optics import rayleigh2waist
722
+ >>> from sympy import symbols
723
+ >>> z_r, wavelen = symbols('z_r wavelen')
724
+ >>> rayleigh2waist(z_r, wavelen)
725
+ sqrt(wavelen*z_r)/sqrt(pi)
726
+ """
727
+ z_r, wavelen = map(sympify, (z_r, wavelen))
728
+ return sqrt(z_r/pi*wavelen)
729
+
730
+
731
+ def geometric_conj_ab(a, b):
732
+ """
733
+ Conjugation relation for geometrical beams under paraxial conditions.
734
+
735
+ Explanation
736
+ ===========
737
+
738
+ Takes the distances to the optical element and returns the needed
739
+ focal distance.
740
+
741
+ See Also
742
+ ========
743
+
744
+ geometric_conj_af, geometric_conj_bf
745
+
746
+ Examples
747
+ ========
748
+
749
+ >>> from sympy.physics.optics import geometric_conj_ab
750
+ >>> from sympy import symbols
751
+ >>> a, b = symbols('a b')
752
+ >>> geometric_conj_ab(a, b)
753
+ a*b/(a + b)
754
+ """
755
+ a, b = map(sympify, (a, b))
756
+ if a.is_infinite or b.is_infinite:
757
+ return a if b.is_infinite else b
758
+ else:
759
+ return a*b/(a + b)
760
+
761
+
762
+ def geometric_conj_af(a, f):
763
+ """
764
+ Conjugation relation for geometrical beams under paraxial conditions.
765
+
766
+ Explanation
767
+ ===========
768
+
769
+ Takes the object distance (for geometric_conj_af) or the image distance
770
+ (for geometric_conj_bf) to the optical element and the focal distance.
771
+ Then it returns the other distance needed for conjugation.
772
+
773
+ See Also
774
+ ========
775
+
776
+ geometric_conj_ab
777
+
778
+ Examples
779
+ ========
780
+
781
+ >>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf
782
+ >>> from sympy import symbols
783
+ >>> a, b, f = symbols('a b f')
784
+ >>> geometric_conj_af(a, f)
785
+ a*f/(a - f)
786
+ >>> geometric_conj_bf(b, f)
787
+ b*f/(b - f)
788
+ """
789
+ a, f = map(sympify, (a, f))
790
+ return -geometric_conj_ab(a, -f)
791
+
792
+ geometric_conj_bf = geometric_conj_af
793
+
794
+
795
+ def gaussian_conj(s_in, z_r_in, f):
796
+ """
797
+ Conjugation relation for gaussian beams.
798
+
799
+ Parameters
800
+ ==========
801
+
802
+ s_in :
803
+ The distance to optical element from the waist.
804
+ z_r_in :
805
+ The rayleigh range of the incident beam.
806
+ f :
807
+ The focal length of the optical element.
808
+
809
+ Returns
810
+ =======
811
+
812
+ a tuple containing (s_out, z_r_out, m)
813
+ s_out :
814
+ The distance between the new waist and the optical element.
815
+ z_r_out :
816
+ The rayleigh range of the emergent beam.
817
+ m :
818
+ The ration between the new and the old waists.
819
+
820
+ Examples
821
+ ========
822
+
823
+ >>> from sympy.physics.optics import gaussian_conj
824
+ >>> from sympy import symbols
825
+ >>> s_in, z_r_in, f = symbols('s_in z_r_in f')
826
+
827
+ >>> gaussian_conj(s_in, z_r_in, f)[0]
828
+ 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
829
+
830
+ >>> gaussian_conj(s_in, z_r_in, f)[1]
831
+ z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
832
+
833
+ >>> gaussian_conj(s_in, z_r_in, f)[2]
834
+ 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
835
+ """
836
+ s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
837
+ s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
838
+ m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
839
+ z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
840
+ return (s_out, z_r_out, m)
841
+
842
+
843
+ def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
844
+ """
845
+ Find the optical setup conjugating the object/image waists.
846
+
847
+ Parameters
848
+ ==========
849
+
850
+ wavelen :
851
+ The wavelength of the beam.
852
+ waist_in and waist_out :
853
+ The waists to be conjugated.
854
+ f :
855
+ The focal distance of the element used in the conjugation.
856
+
857
+ Returns
858
+ =======
859
+
860
+ a tuple containing (s_in, s_out, f)
861
+ s_in :
862
+ The distance before the optical element.
863
+ s_out :
864
+ The distance after the optical element.
865
+ f :
866
+ The focal distance of the optical element.
867
+
868
+ Examples
869
+ ========
870
+
871
+ >>> from sympy.physics.optics import conjugate_gauss_beams
872
+ >>> from sympy import symbols, factor
873
+ >>> l, w_i, w_o, f = symbols('l w_i w_o f')
874
+
875
+ >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
876
+ f*(1 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))
877
+
878
+ >>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
879
+ f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
880
+ pi**2*w_i**4/(f**2*l**2)))/w_i**2
881
+
882
+ >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
883
+ f
884
+ """
885
+ #TODO add the other possible arguments
886
+ wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
887
+ m = waist_out / waist_in
888
+ z = waist2rayleigh(waist_in, wavelen)
889
+ if len(kwargs) != 1:
890
+ raise ValueError("The function expects only one named argument")
891
+ elif 'dist' in kwargs:
892
+ raise NotImplementedError(filldedent('''
893
+ Currently only focal length is supported as a parameter'''))
894
+ elif 'f' in kwargs:
895
+ f = sympify(kwargs['f'])
896
+ s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
897
+ s_out = gaussian_conj(s_in, z, f)[0]
898
+ elif 's_in' in kwargs:
899
+ raise NotImplementedError(filldedent('''
900
+ Currently only focal length is supported as a parameter'''))
901
+ else:
902
+ raise ValueError(filldedent('''
903
+ The functions expects the focal length as a named argument'''))
904
+ return (s_in, s_out, f)
905
+
906
+ #TODO
907
+ #def plot_beam():
908
+ # """Plot the beam radius as it propagates in space."""
909
+ # pass
910
+
911
+ #TODO
912
+ #def plot_beam_conjugation():
913
+ # """
914
+ # Plot the intersection of two beams.
915
+ #
916
+ # Represents the conjugation relation.
917
+ #
918
+ # See Also
919
+ # ========
920
+ #
921
+ # conjugate_gauss_beams
922
+ # """
923
+ # pass
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/medium.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **Contains**
3
+
4
+ * Medium
5
+ """
6
+ from sympy.physics.units import second, meter, kilogram, ampere
7
+
8
+ __all__ = ['Medium']
9
+
10
+ from sympy.core.basic import Basic
11
+ from sympy.core.symbol import Str
12
+ from sympy.core.sympify import _sympify
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.physics.units import speed_of_light, u0, e0
15
+
16
+
17
+ c = speed_of_light.convert_to(meter/second)
18
+ _e0mksa = e0.convert_to(ampere**2*second**4/(kilogram*meter**3))
19
+ _u0mksa = u0.convert_to(meter*kilogram/(ampere**2*second**2))
20
+
21
+
22
+ class Medium(Basic):
23
+
24
+ """
25
+ This class represents an optical medium. The prime reason to implement this is
26
+ to facilitate refraction, Fermat's principle, etc.
27
+
28
+ Explanation
29
+ ===========
30
+
31
+ An optical medium is a material through which electromagnetic waves propagate.
32
+ The permittivity and permeability of the medium define how electromagnetic
33
+ waves propagate in it.
34
+
35
+
36
+ Parameters
37
+ ==========
38
+
39
+ name: string
40
+ The display name of the Medium.
41
+
42
+ permittivity: Sympifyable
43
+ Electric permittivity of the space.
44
+
45
+ permeability: Sympifyable
46
+ Magnetic permeability of the space.
47
+
48
+ n: Sympifyable
49
+ Index of refraction of the medium.
50
+
51
+
52
+ Examples
53
+ ========
54
+
55
+ >>> from sympy.abc import epsilon, mu
56
+ >>> from sympy.physics.optics import Medium
57
+ >>> m1 = Medium('m1')
58
+ >>> m2 = Medium('m2', epsilon, mu)
59
+ >>> m1.intrinsic_impedance
60
+ 149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
61
+ >>> m2.refractive_index
62
+ 299792458*meter*sqrt(epsilon*mu)/second
63
+
64
+
65
+ References
66
+ ==========
67
+
68
+ .. [1] https://en.wikipedia.org/wiki/Optical_medium
69
+
70
+ """
71
+
72
+ def __new__(cls, name, permittivity=None, permeability=None, n=None):
73
+ if not isinstance(name, Str):
74
+ name = Str(name)
75
+
76
+ permittivity = _sympify(permittivity) if permittivity is not None else permittivity
77
+ permeability = _sympify(permeability) if permeability is not None else permeability
78
+ n = _sympify(n) if n is not None else n
79
+
80
+ if n is not None:
81
+ if permittivity is not None and permeability is None:
82
+ permeability = n**2/(c**2*permittivity)
83
+ return MediumPP(name, permittivity, permeability)
84
+ elif permeability is not None and permittivity is None:
85
+ permittivity = n**2/(c**2*permeability)
86
+ return MediumPP(name, permittivity, permeability)
87
+ elif permittivity is not None and permittivity is not None:
88
+ raise ValueError("Specifying all of permittivity, permeability, and n is not allowed")
89
+ else:
90
+ return MediumN(name, n)
91
+ elif permittivity is not None and permeability is not None:
92
+ return MediumPP(name, permittivity, permeability)
93
+ elif permittivity is None and permeability is None:
94
+ return MediumPP(name, _e0mksa, _u0mksa)
95
+ else:
96
+ raise ValueError("Arguments are underspecified. Either specify n or any two of permittivity, "
97
+ "permeability, and n")
98
+
99
+ @property
100
+ def name(self):
101
+ return self.args[0]
102
+
103
+ @property
104
+ def speed(self):
105
+ """
106
+ Returns speed of the electromagnetic wave travelling in the medium.
107
+
108
+ Examples
109
+ ========
110
+
111
+ >>> from sympy.physics.optics import Medium
112
+ >>> m = Medium('m')
113
+ >>> m.speed
114
+ 299792458*meter/second
115
+ >>> m2 = Medium('m2', n=1)
116
+ >>> m.speed == m2.speed
117
+ True
118
+
119
+ """
120
+ return c / self.n
121
+
122
+ @property
123
+ def refractive_index(self):
124
+ """
125
+ Returns refractive index of the medium.
126
+
127
+ Examples
128
+ ========
129
+
130
+ >>> from sympy.physics.optics import Medium
131
+ >>> m = Medium('m')
132
+ >>> m.refractive_index
133
+ 1
134
+
135
+ """
136
+ return (c/self.speed)
137
+
138
+
139
+ class MediumN(Medium):
140
+
141
+ """
142
+ Represents an optical medium for which only the refractive index is known.
143
+ Useful for simple ray optics.
144
+
145
+ This class should never be instantiated directly.
146
+ Instead it should be instantiated indirectly by instantiating Medium with
147
+ only n specified.
148
+
149
+ Examples
150
+ ========
151
+ >>> from sympy.physics.optics import Medium
152
+ >>> m = Medium('m', n=2)
153
+ >>> m
154
+ MediumN(Str('m'), 2)
155
+ """
156
+
157
+ def __new__(cls, name, n):
158
+ obj = super(Medium, cls).__new__(cls, name, n)
159
+ return obj
160
+
161
+ @property
162
+ def n(self):
163
+ return self.args[1]
164
+
165
+
166
+ class MediumPP(Medium):
167
+ """
168
+ Represents an optical medium for which the permittivity and permeability are known.
169
+
170
+ This class should never be instantiated directly. Instead it should be
171
+ instantiated indirectly by instantiating Medium with any two of
172
+ permittivity, permeability, and n specified, or by not specifying any
173
+ of permittivity, permeability, or n, in which case default values for
174
+ permittivity and permeability will be used.
175
+
176
+ Examples
177
+ ========
178
+ >>> from sympy.physics.optics import Medium
179
+ >>> from sympy.abc import epsilon, mu
180
+ >>> m1 = Medium('m1', permittivity=epsilon, permeability=mu)
181
+ >>> m1
182
+ MediumPP(Str('m1'), epsilon, mu)
183
+ >>> m2 = Medium('m2')
184
+ >>> m2
185
+ MediumPP(Str('m2'), 625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3), pi*kilogram*meter/(2500000*ampere**2*second**2))
186
+ """
187
+
188
+
189
+ def __new__(cls, name, permittivity, permeability):
190
+ obj = super(Medium, cls).__new__(cls, name, permittivity, permeability)
191
+ return obj
192
+
193
+ @property
194
+ def intrinsic_impedance(self):
195
+ """
196
+ Returns intrinsic impedance of the medium.
197
+
198
+ Explanation
199
+ ===========
200
+
201
+ The intrinsic impedance of a medium is the ratio of the
202
+ transverse components of the electric and magnetic fields
203
+ of the electromagnetic wave travelling in the medium.
204
+ In a region with no electrical conductivity it simplifies
205
+ to the square root of ratio of magnetic permeability to
206
+ electric permittivity.
207
+
208
+ Examples
209
+ ========
210
+
211
+ >>> from sympy.physics.optics import Medium
212
+ >>> m = Medium('m')
213
+ >>> m.intrinsic_impedance
214
+ 149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
215
+
216
+ """
217
+ return sqrt(self.permeability / self.permittivity)
218
+
219
+ @property
220
+ def permittivity(self):
221
+ """
222
+ Returns electric permittivity of the medium.
223
+
224
+ Examples
225
+ ========
226
+
227
+ >>> from sympy.physics.optics import Medium
228
+ >>> m = Medium('m')
229
+ >>> m.permittivity
230
+ 625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3)
231
+
232
+ """
233
+ return self.args[1]
234
+
235
+ @property
236
+ def permeability(self):
237
+ """
238
+ Returns magnetic permeability of the medium.
239
+
240
+ Examples
241
+ ========
242
+
243
+ >>> from sympy.physics.optics import Medium
244
+ >>> m = Medium('m')
245
+ >>> m.permeability
246
+ pi*kilogram*meter/(2500000*ampere**2*second**2)
247
+
248
+ """
249
+ return self.args[2]
250
+
251
+ @property
252
+ def n(self):
253
+ return c*sqrt(self.permittivity*self.permeability)
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/polarization.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ The module implements routines to model the polarization of optical fields
5
+ and can be used to calculate the effects of polarization optical elements on
6
+ the fields.
7
+
8
+ - Jones vectors.
9
+
10
+ - Stokes vectors.
11
+
12
+ - Jones matrices.
13
+
14
+ - Mueller matrices.
15
+
16
+ Examples
17
+ ========
18
+
19
+ We calculate a generic Jones vector:
20
+
21
+ >>> from sympy import symbols, pprint, zeros, simplify
22
+ >>> from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
23
+ ... half_wave_retarder, polarizing_beam_splitter, jones_2_stokes)
24
+
25
+ >>> psi, chi, p, I0 = symbols("psi, chi, p, I0", real=True)
26
+ >>> x0 = jones_vector(psi, chi)
27
+ >>> pprint(x0, use_unicode=True)
28
+ ⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
29
+ ⎢ ⎥
30
+ ⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
31
+
32
+ And the more general Stokes vector:
33
+
34
+ >>> s0 = stokes_vector(psi, chi, p, I0)
35
+ >>> pprint(s0, use_unicode=True)
36
+ ⎡ I₀ ⎤
37
+ ⎢ ⎥
38
+ ⎢I₀⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
39
+ ⎢ ⎥
40
+ ⎢I₀⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
41
+ ⎢ ⎥
42
+ ⎣ I₀⋅p⋅sin(2⋅χ) ⎦
43
+
44
+ We calculate how the Jones vector is modified by a half-wave plate:
45
+
46
+ >>> alpha = symbols("alpha", real=True)
47
+ >>> HWP = half_wave_retarder(alpha)
48
+ >>> x1 = simplify(HWP*x0)
49
+
50
+ We calculate the very common operation of passing a beam through a half-wave
51
+ plate and then through a polarizing beam-splitter. We do this by putting this
52
+ Jones vector as the first entry of a two-Jones-vector state that is transformed
53
+ by a 4x4 Jones matrix modelling the polarizing beam-splitter to get the
54
+ transmitted and reflected Jones vectors:
55
+
56
+ >>> PBS = polarizing_beam_splitter()
57
+ >>> X1 = zeros(4, 1)
58
+ >>> X1[:2, :] = x1
59
+ >>> X2 = PBS*X1
60
+ >>> transmitted_port = X2[:2, :]
61
+ >>> reflected_port = X2[2:, :]
62
+
63
+ This allows us to calculate how the power in both ports depends on the initial
64
+ polarization:
65
+
66
+ >>> transmitted_power = jones_2_stokes(transmitted_port)[0]
67
+ >>> reflected_power = jones_2_stokes(reflected_port)[0]
68
+ >>> print(transmitted_power)
69
+ cos(-2*alpha + chi + psi)**2/2 + cos(2*alpha + chi - psi)**2/2
70
+
71
+
72
+ >>> print(reflected_power)
73
+ sin(-2*alpha + chi + psi)**2/2 + sin(2*alpha + chi - psi)**2/2
74
+
75
+ Please see the description of the individual functions for further
76
+ details and examples.
77
+
78
+ References
79
+ ==========
80
+
81
+ .. [1] https://en.wikipedia.org/wiki/Jones_calculus
82
+ .. [2] https://en.wikipedia.org/wiki/Mueller_calculus
83
+ .. [3] https://en.wikipedia.org/wiki/Stokes_parameters
84
+
85
+ """
86
+
87
+ from sympy.core.numbers import (I, pi)
88
+ from sympy.functions.elementary.complexes import (Abs, im, re)
89
+ from sympy.functions.elementary.exponential import exp
90
+ from sympy.functions.elementary.miscellaneous import sqrt
91
+ from sympy.functions.elementary.trigonometric import (cos, sin)
92
+ from sympy.matrices.dense import Matrix
93
+ from sympy.simplify.simplify import simplify
94
+ from sympy.physics.quantum import TensorProduct
95
+
96
+
97
+ def jones_vector(psi, chi):
98
+ """A Jones vector corresponding to a polarization ellipse with `psi` tilt,
99
+ and `chi` circularity.
100
+
101
+ Parameters
102
+ ==========
103
+
104
+ psi : numeric type or SymPy Symbol
105
+ The tilt of the polarization relative to the `x` axis.
106
+
107
+ chi : numeric type or SymPy Symbol
108
+ The angle adjacent to the mayor axis of the polarization ellipse.
109
+
110
+
111
+ Returns
112
+ =======
113
+
114
+ Matrix :
115
+ A Jones vector.
116
+
117
+ Examples
118
+ ========
119
+
120
+ The axes on the Poincaré sphere.
121
+
122
+ >>> from sympy import pprint, symbols, pi
123
+ >>> from sympy.physics.optics.polarization import jones_vector
124
+ >>> psi, chi = symbols("psi, chi", real=True)
125
+
126
+ A general Jones vector.
127
+
128
+ >>> pprint(jones_vector(psi, chi), use_unicode=True)
129
+ ⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
130
+ ⎢ ⎥
131
+ ⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
132
+
133
+ Horizontal polarization.
134
+
135
+ >>> pprint(jones_vector(0, 0), use_unicode=True)
136
+ ⎡1⎤
137
+ ⎢ ⎥
138
+ ⎣0⎦
139
+
140
+ Vertical polarization.
141
+
142
+ >>> pprint(jones_vector(pi/2, 0), use_unicode=True)
143
+ ⎡0⎤
144
+ ⎢ ⎥
145
+ ⎣1⎦
146
+
147
+ Diagonal polarization.
148
+
149
+ >>> pprint(jones_vector(pi/4, 0), use_unicode=True)
150
+ ⎡√2⎤
151
+ ⎢──⎥
152
+ ⎢2 ⎥
153
+ ⎢ ⎥
154
+ ⎢√2⎥
155
+ ⎢──⎥
156
+ ⎣2 ⎦
157
+
158
+ Anti-diagonal polarization.
159
+
160
+ >>> pprint(jones_vector(-pi/4, 0), use_unicode=True)
161
+ ⎡ √2 ⎤
162
+ ⎢ ── ⎥
163
+ ⎢ 2 ⎥
164
+ ⎢ ⎥
165
+ ⎢-√2 ⎥
166
+ ⎢────⎥
167
+ ⎣ 2 ⎦
168
+
169
+ Right-hand circular polarization.
170
+
171
+ >>> pprint(jones_vector(0, pi/4), use_unicode=True)
172
+ ⎡ √2 ⎤
173
+ ⎢ ── ⎥
174
+ ⎢ 2 ⎥
175
+ ⎢ ⎥
176
+ ⎢√2⋅ⅈ⎥
177
+ ⎢────⎥
178
+ ⎣ 2 ⎦
179
+
180
+ Left-hand circular polarization.
181
+
182
+ >>> pprint(jones_vector(0, -pi/4), use_unicode=True)
183
+ ⎡ √2 ⎤
184
+ ⎢ ── ⎥
185
+ ⎢ 2 ⎥
186
+ ⎢ ⎥
187
+ ⎢-√2⋅ⅈ ⎥
188
+ ⎢──────⎥
189
+ ⎣ 2 ⎦
190
+
191
+ """
192
+ return Matrix([-I*sin(chi)*sin(psi) + cos(chi)*cos(psi),
193
+ I*sin(chi)*cos(psi) + sin(psi)*cos(chi)])
194
+
195
+
196
+ def stokes_vector(psi, chi, p=1, I=1):
197
+ """A Stokes vector corresponding to a polarization ellipse with ``psi``
198
+ tilt, and ``chi`` circularity.
199
+
200
+ Parameters
201
+ ==========
202
+
203
+ psi : numeric type or SymPy Symbol
204
+ The tilt of the polarization relative to the ``x`` axis.
205
+ chi : numeric type or SymPy Symbol
206
+ The angle adjacent to the mayor axis of the polarization ellipse.
207
+ p : numeric type or SymPy Symbol
208
+ The degree of polarization.
209
+ I : numeric type or SymPy Symbol
210
+ The intensity of the field.
211
+
212
+
213
+ Returns
214
+ =======
215
+
216
+ Matrix :
217
+ A Stokes vector.
218
+
219
+ Examples
220
+ ========
221
+
222
+ The axes on the Poincaré sphere.
223
+
224
+ >>> from sympy import pprint, symbols, pi
225
+ >>> from sympy.physics.optics.polarization import stokes_vector
226
+ >>> psi, chi, p, I = symbols("psi, chi, p, I", real=True)
227
+ >>> pprint(stokes_vector(psi, chi, p, I), use_unicode=True)
228
+ ⎡ I ⎤
229
+ ⎢ ⎥
230
+ ⎢I⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
231
+ ⎢ ⎥
232
+ ⎢I⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
233
+ ⎢ ⎥
234
+ ⎣ I⋅p⋅sin(2⋅χ) ⎦
235
+
236
+
237
+ Horizontal polarization
238
+
239
+ >>> pprint(stokes_vector(0, 0), use_unicode=True)
240
+ ⎡1⎤
241
+ ⎢ ⎥
242
+ ⎢1⎥
243
+ ⎢ ⎥
244
+ ⎢0⎥
245
+ ⎢ ⎥
246
+ ⎣0⎦
247
+
248
+ Vertical polarization
249
+
250
+ >>> pprint(stokes_vector(pi/2, 0), use_unicode=True)
251
+ ⎡1 ⎤
252
+ ⎢ ⎥
253
+ ⎢-1⎥
254
+ ⎢ ⎥
255
+ ⎢0 ⎥
256
+ ⎢ ⎥
257
+ ⎣0 ⎦
258
+
259
+ Diagonal polarization
260
+
261
+ >>> pprint(stokes_vector(pi/4, 0), use_unicode=True)
262
+ ⎡1⎤
263
+ ⎢ ⎥
264
+ ⎢0⎥
265
+ ⎢ ⎥
266
+ ⎢1⎥
267
+ ⎢ ⎥
268
+ ⎣0⎦
269
+
270
+ Anti-diagonal polarization
271
+
272
+ >>> pprint(stokes_vector(-pi/4, 0), use_unicode=True)
273
+ ⎡1 ⎤
274
+ ⎢ ⎥
275
+ ⎢0 ⎥
276
+ ⎢ ⎥
277
+ ⎢-1⎥
278
+ ⎢ ⎥
279
+ ⎣0 ⎦
280
+
281
+ Right-hand circular polarization
282
+
283
+ >>> pprint(stokes_vector(0, pi/4), use_unicode=True)
284
+ ⎡1⎤
285
+ ⎢ ⎥
286
+ ⎢0⎥
287
+ ⎢ ⎥
288
+ ⎢0⎥
289
+ ⎢ ⎥
290
+ ⎣1⎦
291
+
292
+ Left-hand circular polarization
293
+
294
+ >>> pprint(stokes_vector(0, -pi/4), use_unicode=True)
295
+ ⎡1 ⎤
296
+ ⎢ ⎥
297
+ ⎢0 ⎥
298
+ ⎢ ⎥
299
+ ⎢0 ⎥
300
+ ⎢ ⎥
301
+ ⎣-1⎦
302
+
303
+ Unpolarized light
304
+
305
+ >>> pprint(stokes_vector(0, 0, 0), use_unicode=True)
306
+ ⎡1⎤
307
+ ⎢ ⎥
308
+ ⎢0⎥
309
+ ⎢ ⎥
310
+ ⎢0⎥
311
+ ⎢ ⎥
312
+ ⎣0⎦
313
+
314
+ """
315
+ S0 = I
316
+ S1 = I*p*cos(2*psi)*cos(2*chi)
317
+ S2 = I*p*sin(2*psi)*cos(2*chi)
318
+ S3 = I*p*sin(2*chi)
319
+ return Matrix([S0, S1, S2, S3])
320
+
321
+
322
+ def jones_2_stokes(e):
323
+ """Return the Stokes vector for a Jones vector ``e``.
324
+
325
+ Parameters
326
+ ==========
327
+
328
+ e : SymPy Matrix
329
+ A Jones vector.
330
+
331
+ Returns
332
+ =======
333
+
334
+ SymPy Matrix
335
+ A Jones vector.
336
+
337
+ Examples
338
+ ========
339
+
340
+ The axes on the Poincaré sphere.
341
+
342
+ >>> from sympy import pprint, pi
343
+ >>> from sympy.physics.optics.polarization import jones_vector
344
+ >>> from sympy.physics.optics.polarization import jones_2_stokes
345
+ >>> H = jones_vector(0, 0)
346
+ >>> V = jones_vector(pi/2, 0)
347
+ >>> D = jones_vector(pi/4, 0)
348
+ >>> A = jones_vector(-pi/4, 0)
349
+ >>> R = jones_vector(0, pi/4)
350
+ >>> L = jones_vector(0, -pi/4)
351
+ >>> pprint([jones_2_stokes(e) for e in [H, V, D, A, R, L]],
352
+ ... use_unicode=True)
353
+ ⎡⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤⎤
354
+ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
355
+ ⎢⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥ ⎢0⎥ ⎢0 ⎥⎥
356
+ ⎢⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥⎥
357
+ ⎢⎢0⎥ ⎢0 ⎥ ⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥⎥
358
+ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
359
+ ⎣⎣0⎦ ⎣0 ⎦ ⎣0⎦ ⎣0 ⎦ ⎣1⎦ ⎣-1⎦⎦
360
+
361
+ """
362
+ ex, ey = e
363
+ return Matrix([Abs(ex)**2 + Abs(ey)**2,
364
+ Abs(ex)**2 - Abs(ey)**2,
365
+ 2*re(ex*ey.conjugate()),
366
+ -2*im(ex*ey.conjugate())])
367
+
368
+
369
+ def linear_polarizer(theta=0):
370
+ """A linear polarizer Jones matrix with transmission axis at
371
+ an angle ``theta``.
372
+
373
+ Parameters
374
+ ==========
375
+
376
+ theta : numeric type or SymPy Symbol
377
+ The angle of the transmission axis relative to the horizontal plane.
378
+
379
+ Returns
380
+ =======
381
+
382
+ SymPy Matrix
383
+ A Jones matrix representing the polarizer.
384
+
385
+ Examples
386
+ ========
387
+
388
+ A generic polarizer.
389
+
390
+ >>> from sympy import pprint, symbols
391
+ >>> from sympy.physics.optics.polarization import linear_polarizer
392
+ >>> theta = symbols("theta", real=True)
393
+ >>> J = linear_polarizer(theta)
394
+ >>> pprint(J, use_unicode=True)
395
+ ⎡ 2 ⎤
396
+ ⎢ cos (θ) sin(θ)⋅cos(θ)⎥
397
+ ⎢ ⎥
398
+ ⎢ 2 ⎥
399
+ ⎣sin(θ)⋅cos(θ) sin (θ) ⎦
400
+
401
+
402
+ """
403
+ M = Matrix([[cos(theta)**2, sin(theta)*cos(theta)],
404
+ [sin(theta)*cos(theta), sin(theta)**2]])
405
+ return M
406
+
407
+
408
+ def phase_retarder(theta=0, delta=0):
409
+ """A phase retarder Jones matrix with retardance ``delta`` at angle ``theta``.
410
+
411
+ Parameters
412
+ ==========
413
+
414
+ theta : numeric type or SymPy Symbol
415
+ The angle of the fast axis relative to the horizontal plane.
416
+ delta : numeric type or SymPy Symbol
417
+ The phase difference between the fast and slow axes of the
418
+ transmitted light.
419
+
420
+ Returns
421
+ =======
422
+
423
+ SymPy Matrix :
424
+ A Jones matrix representing the retarder.
425
+
426
+ Examples
427
+ ========
428
+
429
+ A generic retarder.
430
+
431
+ >>> from sympy import pprint, symbols
432
+ >>> from sympy.physics.optics.polarization import phase_retarder
433
+ >>> theta, delta = symbols("theta, delta", real=True)
434
+ >>> R = phase_retarder(theta, delta)
435
+ >>> pprint(R, use_unicode=True)
436
+ ⎡ -ⅈ⋅δ -ⅈ⋅δ ⎤
437
+ ⎢ ───── ───── ⎥
438
+ ⎢⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎛ ⅈ⋅δ⎞ 2 ⎥
439
+ ⎢⎝ℯ ⋅sin (θ) + cos (θ)⎠⋅ℯ ⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ)⎥
440
+ ⎢ ⎥
441
+ ⎢ -ⅈ⋅δ -ⅈ⋅δ ⎥
442
+ ⎢ ───── ─────⎥
443
+ ⎢⎛ ⅈ⋅δ⎞ 2 ⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎥
444
+ ⎣⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝ℯ ⋅cos (θ) + sin (θ)⎠⋅ℯ ⎦
445
+
446
+ """
447
+ R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2,
448
+ (1-exp(I*delta))*cos(theta)*sin(theta)],
449
+ [(1-exp(I*delta))*cos(theta)*sin(theta),
450
+ sin(theta)**2 + exp(I*delta)*cos(theta)**2]])
451
+ return R*exp(-I*delta/2)
452
+
453
+
454
+ def half_wave_retarder(theta):
455
+ """A half-wave retarder Jones matrix at angle ``theta``.
456
+
457
+ Parameters
458
+ ==========
459
+
460
+ theta : numeric type or SymPy Symbol
461
+ The angle of the fast axis relative to the horizontal plane.
462
+
463
+ Returns
464
+ =======
465
+
466
+ SymPy Matrix
467
+ A Jones matrix representing the retarder.
468
+
469
+ Examples
470
+ ========
471
+
472
+ A generic half-wave plate.
473
+
474
+ >>> from sympy import pprint, symbols
475
+ >>> from sympy.physics.optics.polarization import half_wave_retarder
476
+ >>> theta= symbols("theta", real=True)
477
+ >>> HWP = half_wave_retarder(theta)
478
+ >>> pprint(HWP, use_unicode=True)
479
+ ⎡ ⎛ 2 2 ⎞ ⎤
480
+ ⎢-ⅈ⋅⎝- sin (θ) + cos (θ)⎠ -2⋅ⅈ⋅sin(θ)⋅cos(θ) ⎥
481
+ ⎢ ⎥
482
+ ⎢ ⎛ 2 2 ⎞⎥
483
+ ⎣ -2⋅ⅈ⋅sin(θ)⋅cos(θ) -ⅈ⋅⎝sin (θ) - cos (θ)⎠⎦
484
+
485
+ """
486
+ return phase_retarder(theta, pi)
487
+
488
+
489
+ def quarter_wave_retarder(theta):
490
+ """A quarter-wave retarder Jones matrix at angle ``theta``.
491
+
492
+ Parameters
493
+ ==========
494
+
495
+ theta : numeric type or SymPy Symbol
496
+ The angle of the fast axis relative to the horizontal plane.
497
+
498
+ Returns
499
+ =======
500
+
501
+ SymPy Matrix
502
+ A Jones matrix representing the retarder.
503
+
504
+ Examples
505
+ ========
506
+
507
+ A generic quarter-wave plate.
508
+
509
+ >>> from sympy import pprint, symbols
510
+ >>> from sympy.physics.optics.polarization import quarter_wave_retarder
511
+ >>> theta= symbols("theta", real=True)
512
+ >>> QWP = quarter_wave_retarder(theta)
513
+ >>> pprint(QWP, use_unicode=True)
514
+ ⎡ -ⅈ⋅π -ⅈ⋅π ⎤
515
+ ⎢ ───── ───── ⎥
516
+ ⎢⎛ 2 2 ⎞ 4 4 ⎥
517
+ ⎢⎝ⅈ⋅sin (θ) + cos (θ)⎠⋅ℯ (1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ)⎥
518
+ ⎢ ⎥
519
+ ⎢ -ⅈ⋅π -ⅈ⋅π ⎥
520
+ ⎢ ───── ─────⎥
521
+ ⎢ 4 ⎛ 2 2 ⎞ 4 ⎥
522
+ ⎣(1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝sin (θ) + ⅈ⋅cos (θ)⎠⋅ℯ ⎦
523
+
524
+ """
525
+ return phase_retarder(theta, pi/2)
526
+
527
+
528
+ def transmissive_filter(T):
529
+ """An attenuator Jones matrix with transmittance ``T``.
530
+
531
+ Parameters
532
+ ==========
533
+
534
+ T : numeric type or SymPy Symbol
535
+ The transmittance of the attenuator.
536
+
537
+ Returns
538
+ =======
539
+
540
+ SymPy Matrix
541
+ A Jones matrix representing the filter.
542
+
543
+ Examples
544
+ ========
545
+
546
+ A generic filter.
547
+
548
+ >>> from sympy import pprint, symbols
549
+ >>> from sympy.physics.optics.polarization import transmissive_filter
550
+ >>> T = symbols("T", real=True)
551
+ >>> NDF = transmissive_filter(T)
552
+ >>> pprint(NDF, use_unicode=True)
553
+ ⎡√T 0 ⎤
554
+ ⎢ ⎥
555
+ ⎣0 √T⎦
556
+
557
+ """
558
+ return Matrix([[sqrt(T), 0], [0, sqrt(T)]])
559
+
560
+
561
+ def reflective_filter(R):
562
+ """A reflective filter Jones matrix with reflectance ``R``.
563
+
564
+ Parameters
565
+ ==========
566
+
567
+ R : numeric type or SymPy Symbol
568
+ The reflectance of the filter.
569
+
570
+ Returns
571
+ =======
572
+
573
+ SymPy Matrix
574
+ A Jones matrix representing the filter.
575
+
576
+ Examples
577
+ ========
578
+
579
+ A generic filter.
580
+
581
+ >>> from sympy import pprint, symbols
582
+ >>> from sympy.physics.optics.polarization import reflective_filter
583
+ >>> R = symbols("R", real=True)
584
+ >>> pprint(reflective_filter(R), use_unicode=True)
585
+ ⎡√R 0 ⎤
586
+ ⎢ ⎥
587
+ ⎣0 -√R⎦
588
+
589
+ """
590
+ return Matrix([[sqrt(R), 0], [0, -sqrt(R)]])
591
+
592
+
593
+ def mueller_matrix(J):
594
+ """The Mueller matrix corresponding to Jones matrix `J`.
595
+
596
+ Parameters
597
+ ==========
598
+
599
+ J : SymPy Matrix
600
+ A Jones matrix.
601
+
602
+ Returns
603
+ =======
604
+
605
+ SymPy Matrix
606
+ The corresponding Mueller matrix.
607
+
608
+ Examples
609
+ ========
610
+
611
+ Generic optical components.
612
+
613
+ >>> from sympy import pprint, symbols
614
+ >>> from sympy.physics.optics.polarization import (mueller_matrix,
615
+ ... linear_polarizer, half_wave_retarder, quarter_wave_retarder)
616
+ >>> theta = symbols("theta", real=True)
617
+
618
+ A linear_polarizer
619
+
620
+ >>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True)
621
+ ⎡ cos(2⋅θ) sin(2⋅θ) ⎤
622
+ ⎢ 1/2 ──────── ──────── 0⎥
623
+ ⎢ 2 2 ⎥
624
+ ⎢ ⎥
625
+ ⎢cos(2⋅θ) cos(4⋅θ) 1 sin(4⋅θ) ⎥
626
+ ⎢──────── ──────── + ─ ──────── 0⎥
627
+ ⎢ 2 4 4 4 ⎥
628
+ ⎢ ⎥
629
+ ⎢sin(2⋅θ) sin(4⋅θ) 1 cos(4⋅θ) ⎥
630
+ ⎢──────── ──────── ─ - ──────── 0⎥
631
+ ⎢ 2 4 4 4 ⎥
632
+ ⎢ ⎥
633
+ ⎣ 0 0 0 0⎦
634
+
635
+ A half-wave plate
636
+
637
+ >>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True)
638
+ ⎡1 0 0 0 ⎤
639
+ ⎢ ⎥
640
+ ⎢ 4 2 ⎥
641
+ ⎢0 8⋅sin (θ) - 8⋅sin (θ) + 1 sin(4⋅θ) 0 ⎥
642
+ ⎢ ⎥
643
+ ⎢ 4 2 ⎥
644
+ ⎢0 sin(4⋅θ) - 8⋅sin (θ) + 8⋅sin (θ) - 1 0 ⎥
645
+ ⎢ ⎥
646
+ ⎣0 0 0 -1⎦
647
+
648
+ A quarter-wave plate
649
+
650
+ >>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True)
651
+ ⎡1 0 0 0 ⎤
652
+ ⎢ ⎥
653
+ ⎢ cos(4⋅θ) 1 sin(4⋅θ) ⎥
654
+ ⎢0 ──────── + ─ ──────── -sin(2⋅θ)⎥
655
+ ⎢ 2 2 2 ⎥
656
+ ⎢ ⎥
657
+ ⎢ sin(4⋅θ) 1 cos(4⋅θ) ⎥
658
+ ⎢0 ──────── ─ - ──────── cos(2⋅θ) ⎥
659
+ ⎢ 2 2 2 ⎥
660
+ ⎢ ⎥
661
+ ⎣0 sin(2⋅θ) -cos(2⋅θ) 0 ⎦
662
+
663
+ """
664
+ A = Matrix([[1, 0, 0, 1],
665
+ [1, 0, 0, -1],
666
+ [0, 1, 1, 0],
667
+ [0, -I, I, 0]])
668
+
669
+ return simplify(A*TensorProduct(J, J.conjugate())*A.inv())
670
+
671
+
672
+ def polarizing_beam_splitter(Tp=1, Rs=1, Ts=0, Rp=0, phia=0, phib=0):
673
+ r"""A polarizing beam splitter Jones matrix at angle `theta`.
674
+
675
+ Parameters
676
+ ==========
677
+
678
+ J : SymPy Matrix
679
+ A Jones matrix.
680
+ Tp : numeric type or SymPy Symbol
681
+ The transmissivity of the P-polarized component.
682
+ Rs : numeric type or SymPy Symbol
683
+ The reflectivity of the S-polarized component.
684
+ Ts : numeric type or SymPy Symbol
685
+ The transmissivity of the S-polarized component.
686
+ Rp : numeric type or SymPy Symbol
687
+ The reflectivity of the P-polarized component.
688
+ phia : numeric type or SymPy Symbol
689
+ The phase difference between transmitted and reflected component for
690
+ output mode a.
691
+ phib : numeric type or SymPy Symbol
692
+ The phase difference between transmitted and reflected component for
693
+ output mode b.
694
+
695
+
696
+ Returns
697
+ =======
698
+
699
+ SymPy Matrix
700
+ A 4x4 matrix representing the PBS. This matrix acts on a 4x1 vector
701
+ whose first two entries are the Jones vector on one of the PBS ports,
702
+ and the last two entries the Jones vector on the other port.
703
+
704
+ Examples
705
+ ========
706
+
707
+ Generic polarizing beam-splitter.
708
+
709
+ >>> from sympy import pprint, symbols
710
+ >>> from sympy.physics.optics.polarization import polarizing_beam_splitter
711
+ >>> Ts, Rs, Tp, Rp = symbols(r"Ts, Rs, Tp, Rp", positive=True)
712
+ >>> phia, phib = symbols("phi_a, phi_b", real=True)
713
+ >>> PBS = polarizing_beam_splitter(Tp, Rs, Ts, Rp, phia, phib)
714
+ >>> pprint(PBS, use_unicode=False)
715
+ [ ____ ____ ]
716
+ [ \/ Tp 0 I*\/ Rp 0 ]
717
+ [ ]
718
+ [ ____ ____ I*phi_a]
719
+ [ 0 \/ Ts 0 -I*\/ Rs *e ]
720
+ [ ]
721
+ [ ____ ____ ]
722
+ [I*\/ Rp 0 \/ Tp 0 ]
723
+ [ ]
724
+ [ ____ I*phi_b ____ ]
725
+ [ 0 -I*\/ Rs *e 0 \/ Ts ]
726
+
727
+ """
728
+ PBS = Matrix([[sqrt(Tp), 0, I*sqrt(Rp), 0],
729
+ [0, sqrt(Ts), 0, -I*sqrt(Rs)*exp(I*phia)],
730
+ [I*sqrt(Rp), 0, sqrt(Tp), 0],
731
+ [0, -I*sqrt(Rs)*exp(I*phib), 0, sqrt(Ts)]])
732
+ return PBS
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/utils.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **Contains**
3
+
4
+ * refraction_angle
5
+ * fresnel_coefficients
6
+ * deviation
7
+ * brewster_angle
8
+ * critical_angle
9
+ * lens_makers_formula
10
+ * mirror_formula
11
+ * lens_formula
12
+ * hyperfocal_distance
13
+ * transverse_magnification
14
+ """
15
+
16
+ __all__ = ['refraction_angle',
17
+ 'deviation',
18
+ 'fresnel_coefficients',
19
+ 'brewster_angle',
20
+ 'critical_angle',
21
+ 'lens_makers_formula',
22
+ 'mirror_formula',
23
+ 'lens_formula',
24
+ 'hyperfocal_distance',
25
+ 'transverse_magnification'
26
+ ]
27
+
28
+ from sympy.core.numbers import (Float, I, oo, pi, zoo)
29
+ from sympy.core.singleton import S
30
+ from sympy.core.symbol import Symbol
31
+ from sympy.core.sympify import sympify
32
+ from sympy.functions.elementary.miscellaneous import sqrt
33
+ from sympy.functions.elementary.trigonometric import (acos, asin, atan2, cos, sin, tan)
34
+ from sympy.matrices.dense import Matrix
35
+ from sympy.polys.polytools import cancel
36
+ from sympy.series.limits import Limit
37
+ from sympy.geometry.line import Ray3D
38
+ from sympy.geometry.util import intersection
39
+ from sympy.geometry.plane import Plane
40
+ from sympy.utilities.iterables import is_sequence
41
+ from .medium import Medium
42
+
43
+
44
+ def refractive_index_of_medium(medium):
45
+ """
46
+ Helper function that returns refractive index, given a medium
47
+ """
48
+ if isinstance(medium, Medium):
49
+ n = medium.refractive_index
50
+ else:
51
+ n = sympify(medium)
52
+ return n
53
+
54
+
55
+ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
56
+ """
57
+ This function calculates transmitted vector after refraction at planar
58
+ surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object.
59
+ If ``incident`` is a number then treated as angle of incidence (in radians)
60
+ in which case refraction angle is returned.
61
+
62
+ If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance
63
+ of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
64
+ plane of separation is not provided and normal is an instance of `Ray3D`,
65
+ ``normal`` will be assumed to be intersecting incident ray at the plane of
66
+ separation. This will not be the case when `normal` is a `Matrix` or
67
+ any other sequence.
68
+ If ``incident`` is an instance of `Ray3D` and `plane` has not been provided
69
+ and ``normal`` is not `Ray3D`, output will be a `Matrix`.
70
+
71
+ Parameters
72
+ ==========
73
+
74
+ incident : Matrix, Ray3D, sequence or a number
75
+ Incident vector or angle of incidence
76
+ medium1 : sympy.physics.optics.medium.Medium or sympifiable
77
+ Medium 1 or its refractive index
78
+ medium2 : sympy.physics.optics.medium.Medium or sympifiable
79
+ Medium 2 or its refractive index
80
+ normal : Matrix, Ray3D, or sequence
81
+ Normal vector
82
+ plane : Plane
83
+ Plane of separation of the two media.
84
+
85
+ Returns
86
+ =======
87
+
88
+ Returns an angle of refraction or a refracted ray depending on inputs.
89
+
90
+ Examples
91
+ ========
92
+
93
+ >>> from sympy.physics.optics import refraction_angle
94
+ >>> from sympy.geometry import Point3D, Ray3D, Plane
95
+ >>> from sympy.matrices import Matrix
96
+ >>> from sympy import symbols, pi
97
+ >>> n = Matrix([0, 0, 1])
98
+ >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
99
+ >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
100
+ >>> refraction_angle(r1, 1, 1, n)
101
+ Matrix([
102
+ [ 1],
103
+ [ 1],
104
+ [-1]])
105
+ >>> refraction_angle(r1, 1, 1, plane=P)
106
+ Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
107
+
108
+ With different index of refraction of the two media
109
+
110
+ >>> n1, n2 = symbols('n1, n2')
111
+ >>> refraction_angle(r1, n1, n2, n)
112
+ Matrix([
113
+ [ n1/n2],
114
+ [ n1/n2],
115
+ [-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
116
+ >>> refraction_angle(r1, n1, n2, plane=P)
117
+ Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
118
+ >>> round(refraction_angle(pi/6, 1.2, 1.5), 5)
119
+ 0.41152
120
+ """
121
+
122
+ n1 = refractive_index_of_medium(medium1)
123
+ n2 = refractive_index_of_medium(medium2)
124
+
125
+ # check if an incidence angle was supplied instead of a ray
126
+ try:
127
+ angle_of_incidence = float(incident)
128
+ except TypeError:
129
+ angle_of_incidence = None
130
+
131
+ try:
132
+ critical_angle_ = critical_angle(medium1, medium2)
133
+ except (ValueError, TypeError):
134
+ critical_angle_ = None
135
+
136
+ if angle_of_incidence is not None:
137
+ if normal is not None or plane is not None:
138
+ raise ValueError('Normal/plane not allowed if incident is an angle')
139
+
140
+ if not 0.0 <= angle_of_incidence < pi*0.5:
141
+ raise ValueError('Angle of incidence not in range [0:pi/2)')
142
+
143
+ if critical_angle_ and angle_of_incidence > critical_angle_:
144
+ raise ValueError('Ray undergoes total internal reflection')
145
+ return asin(n1*sin(angle_of_incidence)/n2)
146
+
147
+ # Treat the incident as ray below
148
+ # A flag to check whether to return Ray3D or not
149
+ return_ray = False
150
+
151
+ if plane is not None and normal is not None:
152
+ raise ValueError("Either plane or normal is acceptable.")
153
+
154
+ if not isinstance(incident, Matrix):
155
+ if is_sequence(incident):
156
+ _incident = Matrix(incident)
157
+ elif isinstance(incident, Ray3D):
158
+ _incident = Matrix(incident.direction_ratio)
159
+ else:
160
+ raise TypeError(
161
+ "incident should be a Matrix, Ray3D, or sequence")
162
+ else:
163
+ _incident = incident
164
+
165
+ # If plane is provided, get direction ratios of the normal
166
+ # to the plane from the plane else go with `normal` param.
167
+ if plane is not None:
168
+ if not isinstance(plane, Plane):
169
+ raise TypeError("plane should be an instance of geometry.plane.Plane")
170
+ # If we have the plane, we can get the intersection
171
+ # point of incident ray and the plane and thus return
172
+ # an instance of Ray3D.
173
+ if isinstance(incident, Ray3D):
174
+ return_ray = True
175
+ intersection_pt = plane.intersection(incident)[0]
176
+ _normal = Matrix(plane.normal_vector)
177
+ else:
178
+ if not isinstance(normal, Matrix):
179
+ if is_sequence(normal):
180
+ _normal = Matrix(normal)
181
+ elif isinstance(normal, Ray3D):
182
+ _normal = Matrix(normal.direction_ratio)
183
+ if isinstance(incident, Ray3D):
184
+ intersection_pt = intersection(incident, normal)
185
+ if len(intersection_pt) == 0:
186
+ raise ValueError(
187
+ "Normal isn't concurrent with the incident ray.")
188
+ else:
189
+ return_ray = True
190
+ intersection_pt = intersection_pt[0]
191
+ else:
192
+ raise TypeError(
193
+ "Normal should be a Matrix, Ray3D, or sequence")
194
+ else:
195
+ _normal = normal
196
+
197
+ eta = n1/n2 # Relative index of refraction
198
+ # Calculating magnitude of the vectors
199
+ mag_incident = sqrt(sum([i**2 for i in _incident]))
200
+ mag_normal = sqrt(sum([i**2 for i in _normal]))
201
+ # Converting vectors to unit vectors by dividing
202
+ # them with their magnitudes
203
+ _incident /= mag_incident
204
+ _normal /= mag_normal
205
+ c1 = -_incident.dot(_normal) # cos(angle_of_incidence)
206
+ cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
207
+ if cs2.is_negative: # This is the case of total internal reflection(TIR).
208
+ return S.Zero
209
+ drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
210
+ # Multiplying unit vector by its magnitude
211
+ drs = drs*mag_incident
212
+ if not return_ray:
213
+ return drs
214
+ else:
215
+ return Ray3D(intersection_pt, direction_ratio=drs)
216
+
217
+
218
+ def fresnel_coefficients(angle_of_incidence, medium1, medium2):
219
+ """
220
+ This function uses Fresnel equations to calculate reflection and
221
+ transmission coefficients. Those are obtained for both polarisations
222
+ when the electric field vector is in the plane of incidence (labelled 'p')
223
+ and when the electric field vector is perpendicular to the plane of
224
+ incidence (labelled 's'). There are four real coefficients unless the
225
+ incident ray reflects in total internal in which case there are two complex
226
+ ones. Angle of incidence is the angle between the incident ray and the
227
+ surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any
228
+ sympifiable object.
229
+
230
+ Parameters
231
+ ==========
232
+
233
+ angle_of_incidence : sympifiable
234
+
235
+ medium1 : Medium or sympifiable
236
+ Medium 1 or its refractive index
237
+
238
+ medium2 : Medium or sympifiable
239
+ Medium 2 or its refractive index
240
+
241
+ Returns
242
+ =======
243
+
244
+ Returns a list with four real Fresnel coefficients:
245
+ [reflection p (TM), reflection s (TE),
246
+ transmission p (TM), transmission s (TE)]
247
+ If the ray is undergoes total internal reflection then returns a
248
+ list of two complex Fresnel coefficients:
249
+ [reflection p (TM), reflection s (TE)]
250
+
251
+ Examples
252
+ ========
253
+
254
+ >>> from sympy.physics.optics import fresnel_coefficients
255
+ >>> fresnel_coefficients(0.3, 1, 2)
256
+ [0.317843553417859, -0.348645229818821,
257
+ 0.658921776708929, 0.651354770181179]
258
+ >>> fresnel_coefficients(0.6, 2, 1)
259
+ [-0.235625382192159 - 0.971843958291041*I,
260
+ 0.816477005968898 - 0.577377951366403*I]
261
+
262
+ References
263
+ ==========
264
+
265
+ .. [1] https://en.wikipedia.org/wiki/Fresnel_equations
266
+ """
267
+ if not 0 <= 2*angle_of_incidence < pi:
268
+ raise ValueError('Angle of incidence not in range [0:pi/2)')
269
+
270
+ n1 = refractive_index_of_medium(medium1)
271
+ n2 = refractive_index_of_medium(medium2)
272
+
273
+ angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2)
274
+ try:
275
+ angle_of_total_internal_reflection_onset = critical_angle(n1, n2)
276
+ except ValueError:
277
+ angle_of_total_internal_reflection_onset = None
278
+
279
+ if angle_of_total_internal_reflection_onset is None or\
280
+ angle_of_total_internal_reflection_onset > angle_of_incidence:
281
+ R_s = -sin(angle_of_incidence - angle_of_refraction)\
282
+ /sin(angle_of_incidence + angle_of_refraction)
283
+ R_p = tan(angle_of_incidence - angle_of_refraction)\
284
+ /tan(angle_of_incidence + angle_of_refraction)
285
+ T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
286
+ /sin(angle_of_incidence + angle_of_refraction)
287
+ T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
288
+ /(sin(angle_of_incidence + angle_of_refraction)\
289
+ *cos(angle_of_incidence - angle_of_refraction))
290
+ return [R_p, R_s, T_p, T_s]
291
+ else:
292
+ n = n2/n1
293
+ R_s = cancel((cos(angle_of_incidence)-\
294
+ I*sqrt(sin(angle_of_incidence)**2 - n**2))\
295
+ /(cos(angle_of_incidence)+\
296
+ I*sqrt(sin(angle_of_incidence)**2 - n**2)))
297
+ R_p = cancel((n**2*cos(angle_of_incidence)-\
298
+ I*sqrt(sin(angle_of_incidence)**2 - n**2))\
299
+ /(n**2*cos(angle_of_incidence)+\
300
+ I*sqrt(sin(angle_of_incidence)**2 - n**2)))
301
+ return [R_p, R_s]
302
+
303
+
304
+ def deviation(incident, medium1, medium2, normal=None, plane=None):
305
+ """
306
+ This function calculates the angle of deviation of a ray
307
+ due to refraction at planar surface.
308
+
309
+ Parameters
310
+ ==========
311
+
312
+ incident : Matrix, Ray3D, sequence or float
313
+ Incident vector or angle of incidence
314
+ medium1 : sympy.physics.optics.medium.Medium or sympifiable
315
+ Medium 1 or its refractive index
316
+ medium2 : sympy.physics.optics.medium.Medium or sympifiable
317
+ Medium 2 or its refractive index
318
+ normal : Matrix, Ray3D, or sequence
319
+ Normal vector
320
+ plane : Plane
321
+ Plane of separation of the two media.
322
+
323
+ Returns angular deviation between incident and refracted rays
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.physics.optics import deviation
329
+ >>> from sympy.geometry import Point3D, Ray3D, Plane
330
+ >>> from sympy.matrices import Matrix
331
+ >>> from sympy import symbols
332
+ >>> n1, n2 = symbols('n1, n2')
333
+ >>> n = Matrix([0, 0, 1])
334
+ >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
335
+ >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
336
+ >>> deviation(r1, 1, 1, n)
337
+ 0
338
+ >>> deviation(r1, n1, n2, plane=P)
339
+ -acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
340
+ >>> round(deviation(0.1, 1.2, 1.5), 5)
341
+ -0.02005
342
+ """
343
+ refracted = refraction_angle(incident,
344
+ medium1,
345
+ medium2,
346
+ normal=normal,
347
+ plane=plane)
348
+ try:
349
+ angle_of_incidence = Float(incident)
350
+ except TypeError:
351
+ angle_of_incidence = None
352
+
353
+ if angle_of_incidence is not None:
354
+ return float(refracted) - angle_of_incidence
355
+
356
+ if refracted != 0:
357
+ if isinstance(refracted, Ray3D):
358
+ refracted = Matrix(refracted.direction_ratio)
359
+
360
+ if not isinstance(incident, Matrix):
361
+ if is_sequence(incident):
362
+ _incident = Matrix(incident)
363
+ elif isinstance(incident, Ray3D):
364
+ _incident = Matrix(incident.direction_ratio)
365
+ else:
366
+ raise TypeError(
367
+ "incident should be a Matrix, Ray3D, or sequence")
368
+ else:
369
+ _incident = incident
370
+
371
+ if plane is None:
372
+ if not isinstance(normal, Matrix):
373
+ if is_sequence(normal):
374
+ _normal = Matrix(normal)
375
+ elif isinstance(normal, Ray3D):
376
+ _normal = Matrix(normal.direction_ratio)
377
+ else:
378
+ raise TypeError(
379
+ "normal should be a Matrix, Ray3D, or sequence")
380
+ else:
381
+ _normal = normal
382
+ else:
383
+ _normal = Matrix(plane.normal_vector)
384
+
385
+ mag_incident = sqrt(sum([i**2 for i in _incident]))
386
+ mag_normal = sqrt(sum([i**2 for i in _normal]))
387
+ mag_refracted = sqrt(sum([i**2 for i in refracted]))
388
+ _incident /= mag_incident
389
+ _normal /= mag_normal
390
+ refracted /= mag_refracted
391
+ i = acos(_incident.dot(_normal))
392
+ r = acos(refracted.dot(_normal))
393
+ return i - r
394
+
395
+
396
+ def brewster_angle(medium1, medium2):
397
+ """
398
+ This function calculates the Brewster's angle of incidence to Medium 2 from
399
+ Medium 1 in radians.
400
+
401
+ Parameters
402
+ ==========
403
+
404
+ medium 1 : Medium or sympifiable
405
+ Refractive index of Medium 1
406
+ medium 2 : Medium or sympifiable
407
+ Refractive index of Medium 1
408
+
409
+ Examples
410
+ ========
411
+
412
+ >>> from sympy.physics.optics import brewster_angle
413
+ >>> brewster_angle(1, 1.33)
414
+ 0.926093295503462
415
+
416
+ """
417
+
418
+ n1 = refractive_index_of_medium(medium1)
419
+ n2 = refractive_index_of_medium(medium2)
420
+
421
+ return atan2(n2, n1)
422
+
423
+ def critical_angle(medium1, medium2):
424
+ """
425
+ This function calculates the critical angle of incidence (marking the onset
426
+ of total internal) to Medium 2 from Medium 1 in radians.
427
+
428
+ Parameters
429
+ ==========
430
+
431
+ medium 1 : Medium or sympifiable
432
+ Refractive index of Medium 1.
433
+ medium 2 : Medium or sympifiable
434
+ Refractive index of Medium 1.
435
+
436
+ Examples
437
+ ========
438
+
439
+ >>> from sympy.physics.optics import critical_angle
440
+ >>> critical_angle(1.33, 1)
441
+ 0.850908514477849
442
+
443
+ """
444
+
445
+ n1 = refractive_index_of_medium(medium1)
446
+ n2 = refractive_index_of_medium(medium2)
447
+
448
+ if n2 > n1:
449
+ raise ValueError('Total internal reflection impossible for n1 < n2')
450
+ else:
451
+ return asin(n2/n1)
452
+
453
+
454
+
455
+ def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):
456
+ """
457
+ This function calculates focal length of a lens.
458
+ It follows cartesian sign convention.
459
+
460
+ Parameters
461
+ ==========
462
+
463
+ n_lens : Medium or sympifiable
464
+ Index of refraction of lens.
465
+ n_surr : Medium or sympifiable
466
+ Index of reflection of surrounding.
467
+ r1 : sympifiable
468
+ Radius of curvature of first surface.
469
+ r2 : sympifiable
470
+ Radius of curvature of second surface.
471
+ d : sympifiable, optional
472
+ Thickness of lens, default value is 0.
473
+
474
+ Examples
475
+ ========
476
+
477
+ >>> from sympy.physics.optics import lens_makers_formula
478
+ >>> from sympy import S
479
+ >>> lens_makers_formula(1.33, 1, 10, -10)
480
+ 15.1515151515151
481
+ >>> lens_makers_formula(1.2, 1, 10, S.Infinity)
482
+ 50.0000000000000
483
+ >>> lens_makers_formula(1.33, 1, 10, -10, d=1)
484
+ 15.3418463277618
485
+
486
+ """
487
+
488
+ if isinstance(n_lens, Medium):
489
+ n_lens = n_lens.refractive_index
490
+ else:
491
+ n_lens = sympify(n_lens)
492
+ if isinstance(n_surr, Medium):
493
+ n_surr = n_surr.refractive_index
494
+ else:
495
+ n_surr = sympify(n_surr)
496
+ d = sympify(d)
497
+
498
+ focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))
499
+
500
+ if focal_length == zoo:
501
+ return S.Infinity
502
+ return focal_length
503
+
504
+
505
+ def mirror_formula(focal_length=None, u=None, v=None):
506
+ """
507
+ This function provides one of the three parameters
508
+ when two of them are supplied.
509
+ This is valid only for paraxial rays.
510
+
511
+ Parameters
512
+ ==========
513
+
514
+ focal_length : sympifiable
515
+ Focal length of the mirror.
516
+ u : sympifiable
517
+ Distance of object from the pole on
518
+ the principal axis.
519
+ v : sympifiable
520
+ Distance of the image from the pole
521
+ on the principal axis.
522
+
523
+ Examples
524
+ ========
525
+
526
+ >>> from sympy.physics.optics import mirror_formula
527
+ >>> from sympy.abc import f, u, v
528
+ >>> mirror_formula(focal_length=f, u=u)
529
+ f*u/(-f + u)
530
+ >>> mirror_formula(focal_length=f, v=v)
531
+ f*v/(-f + v)
532
+ >>> mirror_formula(u=u, v=v)
533
+ u*v/(u + v)
534
+
535
+ """
536
+ if focal_length and u and v:
537
+ raise ValueError("Please provide only two parameters")
538
+
539
+ focal_length = sympify(focal_length)
540
+ u = sympify(u)
541
+ v = sympify(v)
542
+ if u is oo:
543
+ _u = Symbol('u')
544
+ if v is oo:
545
+ _v = Symbol('v')
546
+ if focal_length is oo:
547
+ _f = Symbol('f')
548
+ if focal_length is None:
549
+ if u is oo and v is oo:
550
+ return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
551
+ if u is oo:
552
+ return Limit(v*_u/(v + _u), _u, oo).doit()
553
+ if v is oo:
554
+ return Limit(_v*u/(_v + u), _v, oo).doit()
555
+ return v*u/(v + u)
556
+ if u is None:
557
+ if v is oo and focal_length is oo:
558
+ return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
559
+ if v is oo:
560
+ return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
561
+ if focal_length is oo:
562
+ return Limit(v*_f/(v - _f), _f, oo).doit()
563
+ return v*focal_length/(v - focal_length)
564
+ if v is None:
565
+ if u is oo and focal_length is oo:
566
+ return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
567
+ if u is oo:
568
+ return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
569
+ if focal_length is oo:
570
+ return Limit(u*_f/(u - _f), _f, oo).doit()
571
+ return u*focal_length/(u - focal_length)
572
+
573
+
574
+ def lens_formula(focal_length=None, u=None, v=None):
575
+ """
576
+ This function provides one of the three parameters
577
+ when two of them are supplied.
578
+ This is valid only for paraxial rays.
579
+
580
+ Parameters
581
+ ==========
582
+
583
+ focal_length : sympifiable
584
+ Focal length of the mirror.
585
+ u : sympifiable
586
+ Distance of object from the optical center on
587
+ the principal axis.
588
+ v : sympifiable
589
+ Distance of the image from the optical center
590
+ on the principal axis.
591
+
592
+ Examples
593
+ ========
594
+
595
+ >>> from sympy.physics.optics import lens_formula
596
+ >>> from sympy.abc import f, u, v
597
+ >>> lens_formula(focal_length=f, u=u)
598
+ f*u/(f + u)
599
+ >>> lens_formula(focal_length=f, v=v)
600
+ f*v/(f - v)
601
+ >>> lens_formula(u=u, v=v)
602
+ u*v/(u - v)
603
+
604
+ """
605
+ if focal_length and u and v:
606
+ raise ValueError("Please provide only two parameters")
607
+
608
+ focal_length = sympify(focal_length)
609
+ u = sympify(u)
610
+ v = sympify(v)
611
+ if u is oo:
612
+ _u = Symbol('u')
613
+ if v is oo:
614
+ _v = Symbol('v')
615
+ if focal_length is oo:
616
+ _f = Symbol('f')
617
+ if focal_length is None:
618
+ if u is oo and v is oo:
619
+ return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
620
+ if u is oo:
621
+ return Limit(v*_u/(_u - v), _u, oo).doit()
622
+ if v is oo:
623
+ return Limit(_v*u/(u - _v), _v, oo).doit()
624
+ return v*u/(u - v)
625
+ if u is None:
626
+ if v is oo and focal_length is oo:
627
+ return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
628
+ if v is oo:
629
+ return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
630
+ if focal_length is oo:
631
+ return Limit(v*_f/(_f - v), _f, oo).doit()
632
+ return v*focal_length/(focal_length - v)
633
+ if v is None:
634
+ if u is oo and focal_length is oo:
635
+ return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
636
+ if u is oo:
637
+ return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
638
+ if focal_length is oo:
639
+ return Limit(u*_f/(u + _f), _f, oo).doit()
640
+ return u*focal_length/(u + focal_length)
641
+
642
+ def hyperfocal_distance(f, N, c):
643
+ """
644
+
645
+ Parameters
646
+ ==========
647
+
648
+ f: sympifiable
649
+ Focal length of a given lens.
650
+
651
+ N: sympifiable
652
+ F-number of a given lens.
653
+
654
+ c: sympifiable
655
+ Circle of Confusion (CoC) of a given image format.
656
+
657
+ Example
658
+ =======
659
+
660
+ >>> from sympy.physics.optics import hyperfocal_distance
661
+ >>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
662
+ 9.47
663
+ """
664
+
665
+ f = sympify(f)
666
+ N = sympify(N)
667
+ c = sympify(c)
668
+
669
+ return (1/(N * c))*(f**2)
670
+
671
+ def transverse_magnification(si, so):
672
+ """
673
+
674
+ Calculates the transverse magnification, which is the ratio of the
675
+ image size to the object size.
676
+
677
+ Parameters
678
+ ==========
679
+
680
+ so: sympifiable
681
+ Lens-object distance.
682
+
683
+ si: sympifiable
684
+ Lens-image distance.
685
+
686
+ Example
687
+ =======
688
+
689
+ >>> from sympy.physics.optics import transverse_magnification
690
+ >>> transverse_magnification(30, 15)
691
+ -2
692
+
693
+ """
694
+
695
+ si = sympify(si)
696
+ so = sympify(so)
697
+
698
+ return (-(si/so))
env-llmeval/lib/python3.10/site-packages/sympy/physics/optics/waves.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module has all the classes and functions related to waves in optics.
3
+
4
+ **Contains**
5
+
6
+ * TWave
7
+ """
8
+
9
+ __all__ = ['TWave']
10
+
11
+ from sympy.core.basic import Basic
12
+ from sympy.core.expr import Expr
13
+ from sympy.core.function import Derivative, Function
14
+ from sympy.core.numbers import (Number, pi, I)
15
+ from sympy.core.singleton import S
16
+ from sympy.core.symbol import (Symbol, symbols)
17
+ from sympy.core.sympify import _sympify, sympify
18
+ from sympy.functions.elementary.exponential import exp
19
+ from sympy.functions.elementary.miscellaneous import sqrt
20
+ from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
21
+ from sympy.physics.units import speed_of_light, meter, second
22
+
23
+
24
+ c = speed_of_light.convert_to(meter/second)
25
+
26
+
27
+ class TWave(Expr):
28
+
29
+ r"""
30
+ This is a simple transverse sine wave travelling in a one-dimensional space.
31
+ Basic properties are required at the time of creation of the object,
32
+ but they can be changed later with respective methods provided.
33
+
34
+ Explanation
35
+ ===========
36
+
37
+ It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`,
38
+ where :math:`A` is the amplitude, :math:`\omega` is the angular frequency,
39
+ :math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable
40
+ to represent the position on the dimension on which the wave propagates,
41
+ and :math:`\phi` is the phase angle of the wave.
42
+
43
+
44
+ Arguments
45
+ =========
46
+
47
+ amplitude : Sympifyable
48
+ Amplitude of the wave.
49
+ frequency : Sympifyable
50
+ Frequency of the wave.
51
+ phase : Sympifyable
52
+ Phase angle of the wave.
53
+ time_period : Sympifyable
54
+ Time period of the wave.
55
+ n : Sympifyable
56
+ Refractive index of the medium.
57
+
58
+ Raises
59
+ =======
60
+
61
+ ValueError : When neither frequency nor time period is provided
62
+ or they are not consistent.
63
+ TypeError : When anything other than TWave objects is added.
64
+
65
+
66
+ Examples
67
+ ========
68
+
69
+ >>> from sympy import symbols
70
+ >>> from sympy.physics.optics import TWave
71
+ >>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
72
+ >>> w1 = TWave(A1, f, phi1)
73
+ >>> w2 = TWave(A2, f, phi2)
74
+ >>> w3 = w1 + w2 # Superposition of two waves
75
+ >>> w3
76
+ TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
77
+ atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)), 1/f, n)
78
+ >>> w3.amplitude
79
+ sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
80
+ >>> w3.phase
81
+ atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
82
+ >>> w3.speed
83
+ 299792458*meter/(second*n)
84
+ >>> w3.angular_velocity
85
+ 2*pi*f
86
+
87
+ """
88
+
89
+ def __new__(
90
+ cls,
91
+ amplitude,
92
+ frequency=None,
93
+ phase=S.Zero,
94
+ time_period=None,
95
+ n=Symbol('n')):
96
+ if time_period is not None:
97
+ time_period = _sympify(time_period)
98
+ _frequency = S.One/time_period
99
+ if frequency is not None:
100
+ frequency = _sympify(frequency)
101
+ _time_period = S.One/frequency
102
+ if time_period is not None:
103
+ if frequency != S.One/time_period:
104
+ raise ValueError("frequency and time_period should be consistent.")
105
+ if frequency is None and time_period is None:
106
+ raise ValueError("Either frequency or time period is needed.")
107
+ if frequency is None:
108
+ frequency = _frequency
109
+ if time_period is None:
110
+ time_period = _time_period
111
+
112
+ amplitude = _sympify(amplitude)
113
+ phase = _sympify(phase)
114
+ n = sympify(n)
115
+ obj = Basic.__new__(cls, amplitude, frequency, phase, time_period, n)
116
+ return obj
117
+
118
+ @property
119
+ def amplitude(self):
120
+ """
121
+ Returns the amplitude of the wave.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy import symbols
127
+ >>> from sympy.physics.optics import TWave
128
+ >>> A, phi, f = symbols('A, phi, f')
129
+ >>> w = TWave(A, f, phi)
130
+ >>> w.amplitude
131
+ A
132
+ """
133
+ return self.args[0]
134
+
135
+ @property
136
+ def frequency(self):
137
+ """
138
+ Returns the frequency of the wave,
139
+ in cycles per second.
140
+
141
+ Examples
142
+ ========
143
+
144
+ >>> from sympy import symbols
145
+ >>> from sympy.physics.optics import TWave
146
+ >>> A, phi, f = symbols('A, phi, f')
147
+ >>> w = TWave(A, f, phi)
148
+ >>> w.frequency
149
+ f
150
+ """
151
+ return self.args[1]
152
+
153
+ @property
154
+ def phase(self):
155
+ """
156
+ Returns the phase angle of the wave,
157
+ in radians.
158
+
159
+ Examples
160
+ ========
161
+
162
+ >>> from sympy import symbols
163
+ >>> from sympy.physics.optics import TWave
164
+ >>> A, phi, f = symbols('A, phi, f')
165
+ >>> w = TWave(A, f, phi)
166
+ >>> w.phase
167
+ phi
168
+ """
169
+ return self.args[2]
170
+
171
+ @property
172
+ def time_period(self):
173
+ """
174
+ Returns the temporal period of the wave,
175
+ in seconds per cycle.
176
+
177
+ Examples
178
+ ========
179
+
180
+ >>> from sympy import symbols
181
+ >>> from sympy.physics.optics import TWave
182
+ >>> A, phi, f = symbols('A, phi, f')
183
+ >>> w = TWave(A, f, phi)
184
+ >>> w.time_period
185
+ 1/f
186
+ """
187
+ return self.args[3]
188
+
189
+ @property
190
+ def n(self):
191
+ """
192
+ Returns the refractive index of the medium
193
+ """
194
+ return self.args[4]
195
+
196
+ @property
197
+ def wavelength(self):
198
+ """
199
+ Returns the wavelength (spatial period) of the wave,
200
+ in meters per cycle.
201
+ It depends on the medium of the wave.
202
+
203
+ Examples
204
+ ========
205
+
206
+ >>> from sympy import symbols
207
+ >>> from sympy.physics.optics import TWave
208
+ >>> A, phi, f = symbols('A, phi, f')
209
+ >>> w = TWave(A, f, phi)
210
+ >>> w.wavelength
211
+ 299792458*meter/(second*f*n)
212
+ """
213
+ return c/(self.frequency*self.n)
214
+
215
+
216
+ @property
217
+ def speed(self):
218
+ """
219
+ Returns the propagation speed of the wave,
220
+ in meters per second.
221
+ It is dependent on the propagation medium.
222
+
223
+ Examples
224
+ ========
225
+
226
+ >>> from sympy import symbols
227
+ >>> from sympy.physics.optics import TWave
228
+ >>> A, phi, f = symbols('A, phi, f')
229
+ >>> w = TWave(A, f, phi)
230
+ >>> w.speed
231
+ 299792458*meter/(second*n)
232
+ """
233
+ return self.wavelength*self.frequency
234
+
235
+ @property
236
+ def angular_velocity(self):
237
+ """
238
+ Returns the angular velocity of the wave,
239
+ in radians per second.
240
+
241
+ Examples
242
+ ========
243
+
244
+ >>> from sympy import symbols
245
+ >>> from sympy.physics.optics import TWave
246
+ >>> A, phi, f = symbols('A, phi, f')
247
+ >>> w = TWave(A, f, phi)
248
+ >>> w.angular_velocity
249
+ 2*pi*f
250
+ """
251
+ return 2*pi*self.frequency
252
+
253
+ @property
254
+ def wavenumber(self):
255
+ """
256
+ Returns the wavenumber of the wave,
257
+ in radians per meter.
258
+
259
+ Examples
260
+ ========
261
+
262
+ >>> from sympy import symbols
263
+ >>> from sympy.physics.optics import TWave
264
+ >>> A, phi, f = symbols('A, phi, f')
265
+ >>> w = TWave(A, f, phi)
266
+ >>> w.wavenumber
267
+ pi*second*f*n/(149896229*meter)
268
+ """
269
+ return 2*pi/self.wavelength
270
+
271
+ def __str__(self):
272
+ """String representation of a TWave."""
273
+ from sympy.printing import sstr
274
+ return type(self).__name__ + sstr(self.args)
275
+
276
+ __repr__ = __str__
277
+
278
+ def __add__(self, other):
279
+ """
280
+ Addition of two waves will result in their superposition.
281
+ The type of interference will depend on their phase angles.
282
+ """
283
+ if isinstance(other, TWave):
284
+ if self.frequency == other.frequency and self.wavelength == other.wavelength:
285
+ return TWave(sqrt(self.amplitude**2 + other.amplitude**2 + 2 *
286
+ self.amplitude*other.amplitude*cos(
287
+ self.phase - other.phase)),
288
+ self.frequency,
289
+ atan2(self.amplitude*sin(self.phase)
290
+ + other.amplitude*sin(other.phase),
291
+ self.amplitude*cos(self.phase)
292
+ + other.amplitude*cos(other.phase))
293
+ )
294
+ else:
295
+ raise NotImplementedError("Interference of waves with different frequencies"
296
+ " has not been implemented.")
297
+ else:
298
+ raise TypeError(type(other).__name__ + " and TWave objects cannot be added.")
299
+
300
+ def __mul__(self, other):
301
+ """
302
+ Multiplying a wave by a scalar rescales the amplitude of the wave.
303
+ """
304
+ other = sympify(other)
305
+ if isinstance(other, Number):
306
+ return TWave(self.amplitude*other, *self.args[1:])
307
+ else:
308
+ raise TypeError(type(other).__name__ + " and TWave objects cannot be multiplied.")
309
+
310
+ def __sub__(self, other):
311
+ return self.__add__(-1*other)
312
+
313
+ def __neg__(self):
314
+ return self.__mul__(-1)
315
+
316
+ def __radd__(self, other):
317
+ return self.__add__(other)
318
+
319
+ def __rmul__(self, other):
320
+ return self.__mul__(other)
321
+
322
+ def __rsub__(self, other):
323
+ return (-self).__radd__(other)
324
+
325
+ def _eval_rewrite_as_sin(self, *args, **kwargs):
326
+ return self.amplitude*sin(self.wavenumber*Symbol('x')
327
+ - self.angular_velocity*Symbol('t') + self.phase + pi/2, evaluate=False)
328
+
329
+ def _eval_rewrite_as_cos(self, *args, **kwargs):
330
+ return self.amplitude*cos(self.wavenumber*Symbol('x')
331
+ - self.angular_velocity*Symbol('t') + self.phase)
332
+
333
+ def _eval_rewrite_as_pde(self, *args, **kwargs):
334
+ mu, epsilon, x, t = symbols('mu, epsilon, x, t')
335
+ E = Function('E')
336
+ return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
337
+
338
+ def _eval_rewrite_as_exp(self, *args, **kwargs):
339
+ return self.amplitude*exp(I*(self.wavenumber*Symbol('x')
340
+ - self.angular_velocity*Symbol('t') + self.phase))
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc ADDED
Binary file (7.86 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc ADDED
Binary file (5.26 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc ADDED
Binary file (2.58 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc ADDED
Binary file (38 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.integrals.integrals import integrate
8
+ from sympy.simplify.simplify import simplify
9
+ from sympy.physics.hydrogen import R_nl, E_nl, E_nl_dirac, Psi_nlm
10
+ from sympy.testing.pytest import raises
11
+
12
+ n, r, Z = symbols('n r Z')
13
+
14
+
15
+ def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
16
+ a = float(a)
17
+ b = float(b)
18
+ # if the numbers are close enough (absolutely), then they are equal
19
+ if abs(a - b) < max_absolute_error:
20
+ return True
21
+ # if not, they can still be equal if their relative error is small
22
+ if abs(b) > abs(a):
23
+ relative_error = abs((a - b)/b)
24
+ else:
25
+ relative_error = abs((a - b)/a)
26
+ return relative_error <= max_relative_error
27
+
28
+
29
+ def test_wavefunction():
30
+ a = 1/Z
31
+ R = {
32
+ (1, 0): 2*sqrt(1/a**3) * exp(-r/a),
33
+ (2, 0): sqrt(1/(2*a**3)) * exp(-r/(2*a)) * (1 - r/(2*a)),
34
+ (2, 1): S.Half * sqrt(1/(6*a**3)) * exp(-r/(2*a)) * r/a,
35
+ (3, 0): Rational(2, 3) * sqrt(1/(3*a**3)) * exp(-r/(3*a)) *
36
+ (1 - 2*r/(3*a) + Rational(2, 27) * (r/a)**2),
37
+ (3, 1): Rational(4, 27) * sqrt(2/(3*a**3)) * exp(-r/(3*a)) *
38
+ (1 - r/(6*a)) * r/a,
39
+ (3, 2): Rational(2, 81) * sqrt(2/(15*a**3)) * exp(-r/(3*a)) * (r/a)**2,
40
+ (4, 0): Rational(1, 4) * sqrt(1/a**3) * exp(-r/(4*a)) *
41
+ (1 - 3*r/(4*a) + Rational(1, 8) * (r/a)**2 - Rational(1, 192) * (r/a)**3),
42
+ (4, 1): Rational(1, 16) * sqrt(5/(3*a**3)) * exp(-r/(4*a)) *
43
+ (1 - r/(4*a) + Rational(1, 80) * (r/a)**2) * (r/a),
44
+ (4, 2): Rational(1, 64) * sqrt(1/(5*a**3)) * exp(-r/(4*a)) *
45
+ (1 - r/(12*a)) * (r/a)**2,
46
+ (4, 3): Rational(1, 768) * sqrt(1/(35*a**3)) * exp(-r/(4*a)) * (r/a)**3,
47
+ }
48
+ for n, l in R:
49
+ assert simplify(R_nl(n, l, r, Z) - R[(n, l)]) == 0
50
+
51
+
52
+ def test_norm():
53
+ # Maximum "n" which is tested:
54
+ n_max = 2 # it works, but is slow, for n_max > 2
55
+ for n in range(n_max + 1):
56
+ for l in range(n):
57
+ assert integrate(R_nl(n, l, r)**2 * r**2, (r, 0, oo)) == 1
58
+
59
+ def test_psi_nlm():
60
+ r=S('r')
61
+ phi=S('phi')
62
+ theta=S('theta')
63
+ assert (Psi_nlm(1, 0, 0, r, phi, theta) == exp(-r) / sqrt(pi))
64
+ assert (Psi_nlm(2, 1, -1, r, phi, theta)) == S.Half * exp(-r / (2)) * r \
65
+ * (sin(theta) * exp(-I * phi) / (4 * sqrt(pi)))
66
+ assert (Psi_nlm(3, 2, 1, r, phi, theta, 2) == -sqrt(2) * sin(theta) \
67
+ * exp(I * phi) * cos(theta) / (4 * sqrt(pi)) * S(2) / 81 \
68
+ * sqrt(2 * 2 ** 3) * exp(-2 * r / (3)) * (r * 2) ** 2)
69
+
70
+ def test_hydrogen_energies():
71
+ assert E_nl(n, Z) == -Z**2/(2*n**2)
72
+ assert E_nl(n) == -1/(2*n**2)
73
+
74
+ assert E_nl(1, 47) == -S(47)**2/(2*1**2)
75
+ assert E_nl(2, 47) == -S(47)**2/(2*2**2)
76
+
77
+ assert E_nl(1) == -S.One/(2*1**2)
78
+ assert E_nl(2) == -S.One/(2*2**2)
79
+ assert E_nl(3) == -S.One/(2*3**2)
80
+ assert E_nl(4) == -S.One/(2*4**2)
81
+ assert E_nl(100) == -S.One/(2*100**2)
82
+
83
+ raises(ValueError, lambda: E_nl(0))
84
+
85
+
86
+ def test_hydrogen_energies_relat():
87
+ # First test exact formulas for small "c" so that we get nice expressions:
88
+ assert E_nl_dirac(2, 0, Z=1, c=1) == 1/sqrt(2) - 1
89
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=2) - ( (8*sqrt(3) + 16)
90
+ / sqrt(16*sqrt(3) + 32) - 4)) == 0
91
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=3) - ( (54*sqrt(2) + 81)
92
+ / sqrt(108*sqrt(2) + 162) - 9)) == 0
93
+
94
+ # Now test for almost the correct speed of light, without floating point
95
+ # numbers:
96
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=137) - ( (352275361 + 10285412 *
97
+ sqrt(1173)) / sqrt(704550722 + 20570824 * sqrt(1173)) - 18769)) == 0
98
+ assert simplify(E_nl_dirac(2, 0, Z=82, c=137) - ( (352275361 + 2571353 *
99
+ sqrt(12045)) / sqrt(704550722 + 5142706*sqrt(12045)) - 18769)) == 0
100
+
101
+ # Test using exact speed of light, and compare against the nonrelativistic
102
+ # energies:
103
+ for n in range(1, 5):
104
+ for l in range(n):
105
+ assert feq(E_nl_dirac(n, l), E_nl(n), 1e-5, 1e-5)
106
+ if l > 0:
107
+ assert feq(E_nl_dirac(n, l, False), E_nl(n), 1e-5, 1e-5)
108
+
109
+ Z = 2
110
+ for n in range(1, 5):
111
+ for l in range(n):
112
+ assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-4, 1e-4)
113
+ if l > 0:
114
+ assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-4, 1e-4)
115
+
116
+ Z = 3
117
+ for n in range(1, 5):
118
+ for l in range(n):
119
+ assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-3, 1e-3)
120
+ if l > 0:
121
+ assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-3, 1e-3)
122
+
123
+ # Test the exceptions:
124
+ raises(ValueError, lambda: E_nl_dirac(0, 0))
125
+ raises(ValueError, lambda: E_nl_dirac(1, -1))
126
+ raises(ValueError, lambda: E_nl_dirac(1, 0, False))
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I
2
+ from sympy.core.symbol import symbols
3
+ from sympy.physics.paulialgebra import Pauli
4
+ from sympy.testing.pytest import XFAIL
5
+ from sympy.physics.quantum import TensorProduct
6
+
7
+ sigma1 = Pauli(1)
8
+ sigma2 = Pauli(2)
9
+ sigma3 = Pauli(3)
10
+
11
+ tau1 = symbols("tau1", commutative = False)
12
+
13
+
14
+ def test_Pauli():
15
+
16
+ assert sigma1 == sigma1
17
+ assert sigma1 != sigma2
18
+
19
+ assert sigma1*sigma2 == I*sigma3
20
+ assert sigma3*sigma1 == I*sigma2
21
+ assert sigma2*sigma3 == I*sigma1
22
+
23
+ assert sigma1*sigma1 == 1
24
+ assert sigma2*sigma2 == 1
25
+ assert sigma3*sigma3 == 1
26
+
27
+ assert sigma1**0 == 1
28
+ assert sigma1**1 == sigma1
29
+ assert sigma1**2 == 1
30
+ assert sigma1**3 == sigma1
31
+ assert sigma1**4 == 1
32
+
33
+ assert sigma3**2 == 1
34
+
35
+ assert sigma1*2*sigma1 == 2
36
+
37
+
38
+ def test_evaluate_pauli_product():
39
+ from sympy.physics.paulialgebra import evaluate_pauli_product
40
+
41
+ assert evaluate_pauli_product(I*sigma2*sigma3) == -sigma1
42
+
43
+ # Check issue 6471
44
+ assert evaluate_pauli_product(-I*4*sigma1*sigma2) == 4*sigma3
45
+
46
+ assert evaluate_pauli_product(
47
+ 1 + I*sigma1*sigma2*sigma1*sigma2 + \
48
+ I*sigma1*sigma2*tau1*sigma1*sigma3 + \
49
+ ((tau1**2).subs(tau1, I*sigma1)) + \
50
+ sigma3*((tau1**2).subs(tau1, I*sigma1)) + \
51
+ TensorProduct(I*sigma1*sigma2*sigma1*sigma2, 1)
52
+ ) == 1 -I + I*sigma3*tau1*sigma2 - 1 - sigma3 - I*TensorProduct(1,1)
53
+
54
+
55
+ @XFAIL
56
+ def test_Pauli_should_work():
57
+ assert sigma1*sigma3*sigma1 == -sigma3
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.matrices import msigma, mgamma, minkowski_tensor, pat_matrix, mdft
2
+ from sympy.core.numbers import (I, Rational)
3
+ from sympy.core.singleton import S
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.matrices.dense import (Matrix, eye, zeros)
6
+ from sympy.testing.pytest import warns_deprecated_sympy
7
+
8
+
9
+ def test_parallel_axis_theorem():
10
+ # This tests the parallel axis theorem matrix by comparing to test
11
+ # matrices.
12
+
13
+ # First case, 1 in all directions.
14
+ mat1 = Matrix(((2, -1, -1), (-1, 2, -1), (-1, -1, 2)))
15
+ assert pat_matrix(1, 1, 1, 1) == mat1
16
+ assert pat_matrix(2, 1, 1, 1) == 2*mat1
17
+
18
+ # Second case, 1 in x, 0 in all others
19
+ mat2 = Matrix(((0, 0, 0), (0, 1, 0), (0, 0, 1)))
20
+ assert pat_matrix(1, 1, 0, 0) == mat2
21
+ assert pat_matrix(2, 1, 0, 0) == 2*mat2
22
+
23
+ # Third case, 1 in y, 0 in all others
24
+ mat3 = Matrix(((1, 0, 0), (0, 0, 0), (0, 0, 1)))
25
+ assert pat_matrix(1, 0, 1, 0) == mat3
26
+ assert pat_matrix(2, 0, 1, 0) == 2*mat3
27
+
28
+ # Fourth case, 1 in z, 0 in all others
29
+ mat4 = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 0)))
30
+ assert pat_matrix(1, 0, 0, 1) == mat4
31
+ assert pat_matrix(2, 0, 0, 1) == 2*mat4
32
+
33
+
34
+ def test_Pauli():
35
+ #this and the following test are testing both Pauli and Dirac matrices
36
+ #and also that the general Matrix class works correctly in a real world
37
+ #situation
38
+ sigma1 = msigma(1)
39
+ sigma2 = msigma(2)
40
+ sigma3 = msigma(3)
41
+
42
+ assert sigma1 == sigma1
43
+ assert sigma1 != sigma2
44
+
45
+ # sigma*I -> I*sigma (see #354)
46
+ assert sigma1*sigma2 == sigma3*I
47
+ assert sigma3*sigma1 == sigma2*I
48
+ assert sigma2*sigma3 == sigma1*I
49
+
50
+ assert sigma1*sigma1 == eye(2)
51
+ assert sigma2*sigma2 == eye(2)
52
+ assert sigma3*sigma3 == eye(2)
53
+
54
+ assert sigma1*2*sigma1 == 2*eye(2)
55
+ assert sigma1*sigma3*sigma1 == -sigma3
56
+
57
+
58
+ def test_Dirac():
59
+ gamma0 = mgamma(0)
60
+ gamma1 = mgamma(1)
61
+ gamma2 = mgamma(2)
62
+ gamma3 = mgamma(3)
63
+ gamma5 = mgamma(5)
64
+
65
+ # gamma*I -> I*gamma (see #354)
66
+ assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I
67
+ assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4)
68
+ assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0]
69
+ assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0]
70
+ assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2]
71
+
72
+ assert mgamma(5, True) == \
73
+ mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I
74
+
75
+ def test_mdft():
76
+ with warns_deprecated_sympy():
77
+ assert mdft(1) == Matrix([[1]])
78
+ with warns_deprecated_sympy():
79
+ assert mdft(2) == 1/sqrt(2)*Matrix([[1,1],[1,-1]])
80
+ with warns_deprecated_sympy():
81
+ assert mdft(4) == Matrix([[S.Half, S.Half, S.Half, S.Half],
82
+ [S.Half, -I/2, Rational(-1,2), I/2],
83
+ [S.Half, Rational(-1,2), S.Half, Rational(-1,2)],
84
+ [S.Half, I/2, Rational(-1,2), -I/2]])
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.integrals.integrals import integrate
7
+ from sympy.simplify.simplify import simplify
8
+ from sympy.abc import omega, m, x
9
+ from sympy.physics.qho_1d import psi_n, E_n, coherent_state
10
+ from sympy.physics.quantum.constants import hbar
11
+
12
+ nu = m * omega / hbar
13
+
14
+
15
+ def test_wavefunction():
16
+ Psi = {
17
+ 0: (nu/pi)**Rational(1, 4) * exp(-nu * x**2 /2),
18
+ 1: (nu/pi)**Rational(1, 4) * sqrt(2*nu) * x * exp(-nu * x**2 /2),
19
+ 2: (nu/pi)**Rational(1, 4) * (2 * nu * x**2 - 1)/sqrt(2) * exp(-nu * x**2 /2),
20
+ 3: (nu/pi)**Rational(1, 4) * sqrt(nu/3) * (2 * nu * x**3 - 3 * x) * exp(-nu * x**2 /2)
21
+ }
22
+ for n in Psi:
23
+ assert simplify(psi_n(n, x, m, omega) - Psi[n]) == 0
24
+
25
+
26
+ def test_norm(n=1):
27
+ # Maximum "n" which is tested:
28
+ for i in range(n + 1):
29
+ assert integrate(psi_n(i, x, 1, 1)**2, (x, -oo, oo)) == 1
30
+
31
+
32
+ def test_orthogonality(n=1):
33
+ # Maximum "n" which is tested:
34
+ for i in range(n + 1):
35
+ for j in range(i + 1, n + 1):
36
+ assert integrate(
37
+ psi_n(i, x, 1, 1)*psi_n(j, x, 1, 1), (x, -oo, oo)) == 0
38
+
39
+
40
+ def test_energies(n=1):
41
+ # Maximum "n" which is tested:
42
+ for i in range(n + 1):
43
+ assert E_n(i, omega) == hbar * omega * (i + S.Half)
44
+
45
+ def test_coherent_state(n=10):
46
+ # Maximum "n" which is tested:
47
+ # test whether coherent state is the eigenstate of annihilation operator
48
+ alpha = Symbol("alpha")
49
+ for i in range(n + 1):
50
+ assert simplify(sqrt(n + 1) * coherent_state(n + 1, alpha)) == simplify(alpha * coherent_state(n, alpha))
env-llmeval/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py ADDED
@@ -0,0 +1,1280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.secondquant import (
2
+ Dagger, Bd, VarBosonicBasis, BBra, B, BKet, FixedBosonicBasis,
3
+ matrix_rep, apply_operators, InnerProduct, Commutator, KroneckerDelta,
4
+ AnnihilateBoson, CreateBoson, BosonicOperator,
5
+ F, Fd, FKet, BosonState, CreateFermion, AnnihilateFermion,
6
+ evaluate_deltas, AntiSymmetricTensor, contraction, NO, wicks,
7
+ PermutationOperator, simplify_index_permutations,
8
+ _sort_anticommuting_fermions, _get_ordered_dummies,
9
+ substitute_dummies, FockStateBosonKet,
10
+ ContractionAppliesOnlyToFermions
11
+ )
12
+
13
+ from sympy.concrete.summations import Sum
14
+ from sympy.core.function import (Function, expand)
15
+ from sympy.core.numbers import (I, Rational)
16
+ from sympy.core.singleton import S
17
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
18
+ from sympy.functions.elementary.miscellaneous import sqrt
19
+ from sympy.printing.repr import srepr
20
+ from sympy.simplify.simplify import simplify
21
+
22
+ from sympy.testing.pytest import slow, raises
23
+ from sympy.printing.latex import latex
24
+
25
+
26
+ def test_PermutationOperator():
27
+ p, q, r, s = symbols('p,q,r,s')
28
+ f, g, h, i = map(Function, 'fghi')
29
+ P = PermutationOperator
30
+ assert P(p, q).get_permuted(f(p)*g(q)) == -f(q)*g(p)
31
+ assert P(p, q).get_permuted(f(p, q)) == -f(q, p)
32
+ assert P(p, q).get_permuted(f(p)) == f(p)
33
+ expr = (f(p)*g(q)*h(r)*i(s)
34
+ - f(q)*g(p)*h(r)*i(s)
35
+ - f(p)*g(q)*h(s)*i(r)
36
+ + f(q)*g(p)*h(s)*i(r))
37
+ perms = [P(p, q), P(r, s)]
38
+ assert (simplify_index_permutations(expr, perms) ==
39
+ P(p, q)*P(r, s)*f(p)*g(q)*h(r)*i(s))
40
+ assert latex(P(p, q)) == 'P(pq)'
41
+
42
+
43
+ def test_index_permutations_with_dummies():
44
+ a, b, c, d = symbols('a b c d')
45
+ p, q, r, s = symbols('p q r s', cls=Dummy)
46
+ f, g = map(Function, 'fg')
47
+ P = PermutationOperator
48
+
49
+ # No dummy substitution necessary
50
+ expr = f(a, b, p, q) - f(b, a, p, q)
51
+ assert simplify_index_permutations(
52
+ expr, [P(a, b)]) == P(a, b)*f(a, b, p, q)
53
+
54
+ # Cases where dummy substitution is needed
55
+ expected = P(a, b)*substitute_dummies(f(a, b, p, q))
56
+
57
+ expr = f(a, b, p, q) - f(b, a, q, p)
58
+ result = simplify_index_permutations(expr, [P(a, b)])
59
+ assert expected == substitute_dummies(result)
60
+
61
+ expr = f(a, b, q, p) - f(b, a, p, q)
62
+ result = simplify_index_permutations(expr, [P(a, b)])
63
+ assert expected == substitute_dummies(result)
64
+
65
+ # A case where nothing can be done
66
+ expr = f(a, b, q, p) - g(b, a, p, q)
67
+ result = simplify_index_permutations(expr, [P(a, b)])
68
+ assert expr == result
69
+
70
+
71
+ def test_dagger():
72
+ i, j, n, m = symbols('i,j,n,m')
73
+ assert Dagger(1) == 1
74
+ assert Dagger(1.0) == 1.0
75
+ assert Dagger(2*I) == -2*I
76
+ assert Dagger(S.Half*I/3.0) == I*Rational(-1, 2)/3.0
77
+ assert Dagger(BKet([n])) == BBra([n])
78
+ assert Dagger(B(0)) == Bd(0)
79
+ assert Dagger(Bd(0)) == B(0)
80
+ assert Dagger(B(n)) == Bd(n)
81
+ assert Dagger(Bd(n)) == B(n)
82
+ assert Dagger(B(0) + B(1)) == Bd(0) + Bd(1)
83
+ assert Dagger(n*m) == Dagger(n)*Dagger(m) # n, m commute
84
+ assert Dagger(B(n)*B(m)) == Bd(m)*Bd(n)
85
+ assert Dagger(B(n)**10) == Dagger(B(n))**10
86
+ assert Dagger('a') == Dagger(Symbol('a'))
87
+ assert Dagger(Dagger('a')) == Symbol('a')
88
+
89
+
90
+ def test_operator():
91
+ i, j = symbols('i,j')
92
+ o = BosonicOperator(i)
93
+ assert o.state == i
94
+ assert o.is_symbolic
95
+ o = BosonicOperator(1)
96
+ assert o.state == 1
97
+ assert not o.is_symbolic
98
+
99
+
100
+ def test_create():
101
+ i, j, n, m = symbols('i,j,n,m')
102
+ o = Bd(i)
103
+ assert latex(o) == "{b^\\dagger_{i}}"
104
+ assert isinstance(o, CreateBoson)
105
+ o = o.subs(i, j)
106
+ assert o.atoms(Symbol) == {j}
107
+ o = Bd(0)
108
+ assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1])
109
+ o = Bd(n)
110
+ assert o.apply_operator(BKet([n])) == o*BKet([n])
111
+
112
+
113
+ def test_annihilate():
114
+ i, j, n, m = symbols('i,j,n,m')
115
+ o = B(i)
116
+ assert latex(o) == "b_{i}"
117
+ assert isinstance(o, AnnihilateBoson)
118
+ o = o.subs(i, j)
119
+ assert o.atoms(Symbol) == {j}
120
+ o = B(0)
121
+ assert o.apply_operator(BKet([n])) == sqrt(n)*BKet([n - 1])
122
+ o = B(n)
123
+ assert o.apply_operator(BKet([n])) == o*BKet([n])
124
+
125
+
126
+ def test_basic_state():
127
+ i, j, n, m = symbols('i,j,n,m')
128
+ s = BosonState([0, 1, 2, 3, 4])
129
+ assert len(s) == 5
130
+ assert s.args[0] == tuple(range(5))
131
+ assert s.up(0) == BosonState([1, 1, 2, 3, 4])
132
+ assert s.down(4) == BosonState([0, 1, 2, 3, 3])
133
+ for i in range(5):
134
+ assert s.up(i).down(i) == s
135
+ assert s.down(0) == 0
136
+ for i in range(5):
137
+ assert s[i] == i
138
+ s = BosonState([n, m])
139
+ assert s.down(0) == BosonState([n - 1, m])
140
+ assert s.up(0) == BosonState([n + 1, m])
141
+
142
+
143
+ def test_basic_apply():
144
+ n = symbols("n")
145
+ e = B(0)*BKet([n])
146
+ assert apply_operators(e) == sqrt(n)*BKet([n - 1])
147
+ e = Bd(0)*BKet([n])
148
+ assert apply_operators(e) == sqrt(n + 1)*BKet([n + 1])
149
+
150
+
151
+ def test_complex_apply():
152
+ n, m = symbols("n,m")
153
+ o = Bd(0)*B(0)*Bd(1)*B(0)
154
+ e = apply_operators(o*BKet([n, m]))
155
+ answer = sqrt(n)*sqrt(m + 1)*(-1 + n)*BKet([-1 + n, 1 + m])
156
+ assert expand(e) == expand(answer)
157
+
158
+
159
+ def test_number_operator():
160
+ n = symbols("n")
161
+ o = Bd(0)*B(0)
162
+ e = apply_operators(o*BKet([n]))
163
+ assert e == n*BKet([n])
164
+
165
+
166
+ def test_inner_product():
167
+ i, j, k, l = symbols('i,j,k,l')
168
+ s1 = BBra([0])
169
+ s2 = BKet([1])
170
+ assert InnerProduct(s1, Dagger(s1)) == 1
171
+ assert InnerProduct(s1, s2) == 0
172
+ s1 = BBra([i, j])
173
+ s2 = BKet([k, l])
174
+ r = InnerProduct(s1, s2)
175
+ assert r == KroneckerDelta(i, k)*KroneckerDelta(j, l)
176
+
177
+
178
+ def test_symbolic_matrix_elements():
179
+ n, m = symbols('n,m')
180
+ s1 = BBra([n])
181
+ s2 = BKet([m])
182
+ o = B(0)
183
+ e = apply_operators(s1*o*s2)
184
+ assert e == sqrt(m)*KroneckerDelta(n, m - 1)
185
+
186
+
187
+ def test_matrix_elements():
188
+ b = VarBosonicBasis(5)
189
+ o = B(0)
190
+ m = matrix_rep(o, b)
191
+ for i in range(4):
192
+ assert m[i, i + 1] == sqrt(i + 1)
193
+ o = Bd(0)
194
+ m = matrix_rep(o, b)
195
+ for i in range(4):
196
+ assert m[i + 1, i] == sqrt(i + 1)
197
+
198
+
199
+ def test_fixed_bosonic_basis():
200
+ b = FixedBosonicBasis(2, 2)
201
+ # assert b == [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]
202
+ state = b.state(1)
203
+ assert state == FockStateBosonKet((1, 1))
204
+ assert b.index(state) == 1
205
+ assert b.state(1) == b[1]
206
+ assert len(b) == 3
207
+ assert str(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
208
+ assert repr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
209
+ assert srepr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
210
+
211
+
212
+ @slow
213
+ def test_sho():
214
+ n, m = symbols('n,m')
215
+ h_n = Bd(n)*B(n)*(n + S.Half)
216
+ H = Sum(h_n, (n, 0, 5))
217
+ o = H.doit(deep=False)
218
+ b = FixedBosonicBasis(2, 6)
219
+ m = matrix_rep(o, b)
220
+ # We need to double check these energy values to make sure that they
221
+ # are correct and have the proper degeneracies!
222
+ diag = [1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11]
223
+ for i in range(len(diag)):
224
+ assert diag[i] == m[i, i]
225
+
226
+
227
+ def test_commutation():
228
+ n, m = symbols("n,m", above_fermi=True)
229
+ c = Commutator(B(0), Bd(0))
230
+ assert c == 1
231
+ c = Commutator(Bd(0), B(0))
232
+ assert c == -1
233
+ c = Commutator(B(n), Bd(0))
234
+ assert c == KroneckerDelta(n, 0)
235
+ c = Commutator(B(0), B(0))
236
+ assert c == 0
237
+ c = Commutator(B(0), Bd(0))
238
+ e = simplify(apply_operators(c*BKet([n])))
239
+ assert e == BKet([n])
240
+ c = Commutator(B(0), B(1))
241
+ e = simplify(apply_operators(c*BKet([n, m])))
242
+ assert e == 0
243
+
244
+ c = Commutator(F(m), Fd(m))
245
+ assert c == +1 - 2*NO(Fd(m)*F(m))
246
+ c = Commutator(Fd(m), F(m))
247
+ assert c.expand() == -1 + 2*NO(Fd(m)*F(m))
248
+
249
+ C = Commutator
250
+ X, Y, Z = symbols('X,Y,Z', commutative=False)
251
+ assert C(C(X, Y), Z) != 0
252
+ assert C(C(X, Z), Y) != 0
253
+ assert C(Y, C(X, Z)) != 0
254
+
255
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
256
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
257
+ p, q, r, s = symbols('p,q,r,s')
258
+ D = KroneckerDelta
259
+
260
+ assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a))
261
+ assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a)
262
+ assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0
263
+
264
+ c1 = Commutator(F(a), Fd(a))
265
+ assert Commutator.eval(c1, c1) == 0
266
+ c = Commutator(Fd(a)*F(i),Fd(b)*F(j))
267
+ assert latex(c) == r'\left[{a^\dagger_{a}} a_{i},{a^\dagger_{b}} a_{j}\right]'
268
+ assert repr(c) == 'Commutator(CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j))'
269
+ assert str(c) == '[CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j)]'
270
+
271
+
272
+ def test_create_f():
273
+ i, j, n, m = symbols('i,j,n,m')
274
+ o = Fd(i)
275
+ assert isinstance(o, CreateFermion)
276
+ o = o.subs(i, j)
277
+ assert o.atoms(Symbol) == {j}
278
+ o = Fd(1)
279
+ assert o.apply_operator(FKet([n])) == FKet([1, n])
280
+ assert o.apply_operator(FKet([n])) == -FKet([n, 1])
281
+ o = Fd(n)
282
+ assert o.apply_operator(FKet([])) == FKet([n])
283
+
284
+ vacuum = FKet([], fermi_level=4)
285
+ assert vacuum == FKet([], fermi_level=4)
286
+
287
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
288
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
289
+ p, q, r, s = symbols('p,q,r,s')
290
+
291
+ assert Fd(i).apply_operator(FKet([i, j, k], 4)) == FKet([j, k], 4)
292
+ assert Fd(a).apply_operator(FKet([i, b, k], 4)) == FKet([a, i, b, k], 4)
293
+
294
+ assert Dagger(B(p)).apply_operator(q) == q*CreateBoson(p)
295
+ assert repr(Fd(p)) == 'CreateFermion(p)'
296
+ assert srepr(Fd(p)) == "CreateFermion(Symbol('p'))"
297
+ assert latex(Fd(p)) == r'{a^\dagger_{p}}'
298
+
299
+
300
+ def test_annihilate_f():
301
+ i, j, n, m = symbols('i,j,n,m')
302
+ o = F(i)
303
+ assert isinstance(o, AnnihilateFermion)
304
+ o = o.subs(i, j)
305
+ assert o.atoms(Symbol) == {j}
306
+ o = F(1)
307
+ assert o.apply_operator(FKet([1, n])) == FKet([n])
308
+ assert o.apply_operator(FKet([n, 1])) == -FKet([n])
309
+ o = F(n)
310
+ assert o.apply_operator(FKet([n])) == FKet([])
311
+
312
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
313
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
314
+ p, q, r, s = symbols('p,q,r,s')
315
+ assert F(i).apply_operator(FKet([i, j, k], 4)) == 0
316
+ assert F(a).apply_operator(FKet([i, b, k], 4)) == 0
317
+ assert F(l).apply_operator(FKet([i, j, k], 3)) == 0
318
+ assert F(l).apply_operator(FKet([i, j, k], 4)) == FKet([l, i, j, k], 4)
319
+ assert str(F(p)) == 'f(p)'
320
+ assert repr(F(p)) == 'AnnihilateFermion(p)'
321
+ assert srepr(F(p)) == "AnnihilateFermion(Symbol('p'))"
322
+ assert latex(F(p)) == 'a_{p}'
323
+
324
+
325
+ def test_create_b():
326
+ i, j, n, m = symbols('i,j,n,m')
327
+ o = Bd(i)
328
+ assert isinstance(o, CreateBoson)
329
+ o = o.subs(i, j)
330
+ assert o.atoms(Symbol) == {j}
331
+ o = Bd(0)
332
+ assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1])
333
+ o = Bd(n)
334
+ assert o.apply_operator(BKet([n])) == o*BKet([n])
335
+
336
+
337
+ def test_annihilate_b():
338
+ i, j, n, m = symbols('i,j,n,m')
339
+ o = B(i)
340
+ assert isinstance(o, AnnihilateBoson)
341
+ o = o.subs(i, j)
342
+ assert o.atoms(Symbol) == {j}
343
+ o = B(0)
344
+
345
+
346
+ def test_wicks():
347
+ p, q, r, s = symbols('p,q,r,s', above_fermi=True)
348
+
349
+ # Testing for particles only
350
+
351
+ str = F(p)*Fd(q)
352
+ assert wicks(str) == NO(F(p)*Fd(q)) + KroneckerDelta(p, q)
353
+ str = Fd(p)*F(q)
354
+ assert wicks(str) == NO(Fd(p)*F(q))
355
+
356
+ str = F(p)*Fd(q)*F(r)*Fd(s)
357
+ nstr = wicks(str)
358
+ fasit = NO(
359
+ KroneckerDelta(p, q)*KroneckerDelta(r, s)
360
+ + KroneckerDelta(p, q)*AnnihilateFermion(r)*CreateFermion(s)
361
+ + KroneckerDelta(r, s)*AnnihilateFermion(p)*CreateFermion(q)
362
+ - KroneckerDelta(p, s)*AnnihilateFermion(r)*CreateFermion(q)
363
+ - AnnihilateFermion(p)*AnnihilateFermion(r)*CreateFermion(q)*CreateFermion(s))
364
+ assert nstr == fasit
365
+
366
+ assert (p*q*nstr).expand() == wicks(p*q*str)
367
+ assert (nstr*p*q*2).expand() == wicks(str*p*q*2)
368
+
369
+ # Testing CC equations particles and holes
370
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
371
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
372
+ p, q, r, s = symbols('p q r s', cls=Dummy)
373
+
374
+ assert (wicks(F(a)*NO(F(i)*F(j))*Fd(b)) ==
375
+ NO(F(a)*F(i)*F(j)*Fd(b)) +
376
+ KroneckerDelta(a, b)*NO(F(i)*F(j)))
377
+ assert (wicks(F(a)*NO(F(i)*F(j)*F(k))*Fd(b)) ==
378
+ NO(F(a)*F(i)*F(j)*F(k)*Fd(b)) -
379
+ KroneckerDelta(a, b)*NO(F(i)*F(j)*F(k)))
380
+
381
+ expr = wicks(Fd(i)*NO(Fd(j)*F(k))*F(l))
382
+ assert (expr ==
383
+ -KroneckerDelta(i, k)*NO(Fd(j)*F(l)) -
384
+ KroneckerDelta(j, l)*NO(Fd(i)*F(k)) -
385
+ KroneckerDelta(i, k)*KroneckerDelta(j, l) +
386
+ KroneckerDelta(i, l)*NO(Fd(j)*F(k)) +
387
+ NO(Fd(i)*Fd(j)*F(k)*F(l)))
388
+ expr = wicks(F(a)*NO(F(b)*Fd(c))*Fd(d))
389
+ assert (expr ==
390
+ -KroneckerDelta(a, c)*NO(F(b)*Fd(d)) -
391
+ KroneckerDelta(b, d)*NO(F(a)*Fd(c)) -
392
+ KroneckerDelta(a, c)*KroneckerDelta(b, d) +
393
+ KroneckerDelta(a, d)*NO(F(b)*Fd(c)) +
394
+ NO(F(a)*F(b)*Fd(c)*Fd(d)))
395
+
396
+
397
+ def test_NO():
398
+ i, j, k, l = symbols('i j k l', below_fermi=True)
399
+ a, b, c, d = symbols('a b c d', above_fermi=True)
400
+ p, q, r, s = symbols('p q r s', cls=Dummy)
401
+
402
+ assert (NO(Fd(p)*F(q) + Fd(a)*F(b)) ==
403
+ NO(Fd(p)*F(q)) + NO(Fd(a)*F(b)))
404
+ assert (NO(Fd(i)*NO(F(j)*Fd(a))) ==
405
+ NO(Fd(i)*F(j)*Fd(a)))
406
+ assert NO(1) == 1
407
+ assert NO(i) == i
408
+ assert (NO(Fd(a)*Fd(b)*(F(c) + F(d))) ==
409
+ NO(Fd(a)*Fd(b)*F(c)) +
410
+ NO(Fd(a)*Fd(b)*F(d)))
411
+
412
+ assert NO(Fd(a)*F(b))._remove_brackets() == Fd(a)*F(b)
413
+ assert NO(F(j)*Fd(i))._remove_brackets() == F(j)*Fd(i)
414
+
415
+ assert (NO(Fd(p)*F(q)).subs(Fd(p), Fd(a) + Fd(i)) ==
416
+ NO(Fd(a)*F(q)) + NO(Fd(i)*F(q)))
417
+ assert (NO(Fd(p)*F(q)).subs(F(q), F(a) + F(i)) ==
418
+ NO(Fd(p)*F(a)) + NO(Fd(p)*F(i)))
419
+
420
+ expr = NO(Fd(p)*F(q))._remove_brackets()
421
+ assert wicks(expr) == NO(expr)
422
+
423
+ assert NO(Fd(a)*F(b)) == - NO(F(b)*Fd(a))
424
+
425
+ no = NO(Fd(a)*F(i)*F(b)*Fd(j))
426
+ l1 = list(no.iter_q_creators())
427
+ assert l1 == [0, 1]
428
+ l2 = list(no.iter_q_annihilators())
429
+ assert l2 == [3, 2]
430
+ no = NO(Fd(a)*Fd(i))
431
+ assert no.has_q_creators == 1
432
+ assert no.has_q_annihilators == -1
433
+ assert str(no) == ':CreateFermion(a)*CreateFermion(i):'
434
+ assert repr(no) == 'NO(CreateFermion(a)*CreateFermion(i))'
435
+ assert latex(no) == r'\left\{{a^\dagger_{a}} {a^\dagger_{i}}\right\}'
436
+ raises(NotImplementedError, lambda: NO(Bd(p)*F(q)))
437
+
438
+
439
+ def test_sorting():
440
+ i, j = symbols('i,j', below_fermi=True)
441
+ a, b = symbols('a,b', above_fermi=True)
442
+ p, q = symbols('p,q')
443
+
444
+ # p, q
445
+ assert _sort_anticommuting_fermions([Fd(p), F(q)]) == ([Fd(p), F(q)], 0)
446
+ assert _sort_anticommuting_fermions([F(p), Fd(q)]) == ([Fd(q), F(p)], 1)
447
+
448
+ # i, p
449
+ assert _sort_anticommuting_fermions([F(p), Fd(i)]) == ([F(p), Fd(i)], 0)
450
+ assert _sort_anticommuting_fermions([Fd(i), F(p)]) == ([F(p), Fd(i)], 1)
451
+ assert _sort_anticommuting_fermions([Fd(p), Fd(i)]) == ([Fd(p), Fd(i)], 0)
452
+ assert _sort_anticommuting_fermions([Fd(i), Fd(p)]) == ([Fd(p), Fd(i)], 1)
453
+ assert _sort_anticommuting_fermions([F(p), F(i)]) == ([F(i), F(p)], 1)
454
+ assert _sort_anticommuting_fermions([F(i), F(p)]) == ([F(i), F(p)], 0)
455
+ assert _sort_anticommuting_fermions([Fd(p), F(i)]) == ([F(i), Fd(p)], 1)
456
+ assert _sort_anticommuting_fermions([F(i), Fd(p)]) == ([F(i), Fd(p)], 0)
457
+
458
+ # a, p
459
+ assert _sort_anticommuting_fermions([F(p), Fd(a)]) == ([Fd(a), F(p)], 1)
460
+ assert _sort_anticommuting_fermions([Fd(a), F(p)]) == ([Fd(a), F(p)], 0)
461
+ assert _sort_anticommuting_fermions([Fd(p), Fd(a)]) == ([Fd(a), Fd(p)], 1)
462
+ assert _sort_anticommuting_fermions([Fd(a), Fd(p)]) == ([Fd(a), Fd(p)], 0)
463
+ assert _sort_anticommuting_fermions([F(p), F(a)]) == ([F(p), F(a)], 0)
464
+ assert _sort_anticommuting_fermions([F(a), F(p)]) == ([F(p), F(a)], 1)
465
+ assert _sort_anticommuting_fermions([Fd(p), F(a)]) == ([Fd(p), F(a)], 0)
466
+ assert _sort_anticommuting_fermions([F(a), Fd(p)]) == ([Fd(p), F(a)], 1)
467
+
468
+ # i, a
469
+ assert _sort_anticommuting_fermions([F(i), Fd(j)]) == ([F(i), Fd(j)], 0)
470
+ assert _sort_anticommuting_fermions([Fd(j), F(i)]) == ([F(i), Fd(j)], 1)
471
+ assert _sort_anticommuting_fermions([Fd(a), Fd(i)]) == ([Fd(a), Fd(i)], 0)
472
+ assert _sort_anticommuting_fermions([Fd(i), Fd(a)]) == ([Fd(a), Fd(i)], 1)
473
+ assert _sort_anticommuting_fermions([F(a), F(i)]) == ([F(i), F(a)], 1)
474
+ assert _sort_anticommuting_fermions([F(i), F(a)]) == ([F(i), F(a)], 0)
475
+
476
+
477
+ def test_contraction():
478
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
479
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
480
+ p, q, r, s = symbols('p,q,r,s')
481
+ assert contraction(Fd(i), F(j)) == KroneckerDelta(i, j)
482
+ assert contraction(F(a), Fd(b)) == KroneckerDelta(a, b)
483
+ assert contraction(F(a), Fd(i)) == 0
484
+ assert contraction(Fd(a), F(i)) == 0
485
+ assert contraction(F(i), Fd(a)) == 0
486
+ assert contraction(Fd(i), F(a)) == 0
487
+ assert contraction(Fd(i), F(p)) == KroneckerDelta(i, p)
488
+ restr = evaluate_deltas(contraction(Fd(p), F(q)))
489
+ assert restr.is_only_below_fermi
490
+ restr = evaluate_deltas(contraction(F(p), Fd(q)))
491
+ assert restr.is_only_above_fermi
492
+ raises(ContractionAppliesOnlyToFermions, lambda: contraction(B(a), Fd(b)))
493
+
494
+
495
+ def test_evaluate_deltas():
496
+ i, j, k = symbols('i,j,k')
497
+
498
+ r = KroneckerDelta(i, j) * KroneckerDelta(j, k)
499
+ assert evaluate_deltas(r) == KroneckerDelta(i, k)
500
+
501
+ r = KroneckerDelta(i, 0) * KroneckerDelta(j, k)
502
+ assert evaluate_deltas(r) == KroneckerDelta(i, 0) * KroneckerDelta(j, k)
503
+
504
+ r = KroneckerDelta(1, j) * KroneckerDelta(j, k)
505
+ assert evaluate_deltas(r) == KroneckerDelta(1, k)
506
+
507
+ r = KroneckerDelta(j, 2) * KroneckerDelta(k, j)
508
+ assert evaluate_deltas(r) == KroneckerDelta(2, k)
509
+
510
+ r = KroneckerDelta(i, 0) * KroneckerDelta(i, j) * KroneckerDelta(j, 1)
511
+ assert evaluate_deltas(r) == 0
512
+
513
+ r = (KroneckerDelta(0, i) * KroneckerDelta(0, j)
514
+ * KroneckerDelta(1, j) * KroneckerDelta(1, j))
515
+ assert evaluate_deltas(r) == 0
516
+
517
+
518
+ def test_Tensors():
519
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
520
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
521
+ p, q, r, s = symbols('p q r s')
522
+
523
+ AT = AntiSymmetricTensor
524
+ assert AT('t', (a, b), (i, j)) == -AT('t', (b, a), (i, j))
525
+ assert AT('t', (a, b), (i, j)) == AT('t', (b, a), (j, i))
526
+ assert AT('t', (a, b), (i, j)) == -AT('t', (a, b), (j, i))
527
+ assert AT('t', (a, a), (i, j)) == 0
528
+ assert AT('t', (a, b), (i, i)) == 0
529
+ assert AT('t', (a, b, c), (i, j)) == -AT('t', (b, a, c), (i, j))
530
+ assert AT('t', (a, b, c), (i, j, k)) == AT('t', (b, a, c), (i, k, j))
531
+
532
+ tabij = AT('t', (a, b), (i, j))
533
+ assert tabij.has(a)
534
+ assert tabij.has(b)
535
+ assert tabij.has(i)
536
+ assert tabij.has(j)
537
+ assert tabij.subs(b, c) == AT('t', (a, c), (i, j))
538
+ assert (2*tabij).subs(i, c) == 2*AT('t', (a, b), (c, j))
539
+ assert tabij.symbol == Symbol('t')
540
+ assert latex(tabij) == '{t^{ab}_{ij}}'
541
+ assert str(tabij) == 't((_a, _b),(_i, _j))'
542
+
543
+ assert AT('t', (a, a), (i, j)).subs(a, b) == AT('t', (b, b), (i, j))
544
+ assert AT('t', (a, i), (a, j)).subs(a, b) == AT('t', (b, i), (b, j))
545
+
546
+
547
+ def test_fully_contracted():
548
+ i, j, k, l = symbols('i j k l', below_fermi=True)
549
+ a, b, c, d = symbols('a b c d', above_fermi=True)
550
+ p, q, r, s = symbols('p q r s', cls=Dummy)
551
+
552
+ Fock = (AntiSymmetricTensor('f', (p,), (q,))*
553
+ NO(Fd(p)*F(q)))
554
+ V = (AntiSymmetricTensor('v', (p, q), (r, s))*
555
+ NO(Fd(p)*Fd(q)*F(s)*F(r)))/4
556
+
557
+ Fai = wicks(NO(Fd(i)*F(a))*Fock,
558
+ keep_only_fully_contracted=True,
559
+ simplify_kronecker_deltas=True)
560
+ assert Fai == AntiSymmetricTensor('f', (a,), (i,))
561
+ Vabij = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*V,
562
+ keep_only_fully_contracted=True,
563
+ simplify_kronecker_deltas=True)
564
+ assert Vabij == AntiSymmetricTensor('v', (a, b), (i, j))
565
+
566
+
567
+ def test_substitute_dummies_without_dummies():
568
+ i, j = symbols('i,j')
569
+ assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2
570
+ assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1
571
+
572
+
573
+ def test_substitute_dummies_NO_operator():
574
+ i, j = symbols('i j', cls=Dummy)
575
+ assert substitute_dummies(att(i, j)*NO(Fd(i)*F(j))
576
+ - att(j, i)*NO(Fd(j)*F(i))) == 0
577
+
578
+
579
+ def test_substitute_dummies_SQ_operator():
580
+ i, j = symbols('i j', cls=Dummy)
581
+ assert substitute_dummies(att(i, j)*Fd(i)*F(j)
582
+ - att(j, i)*Fd(j)*F(i)) == 0
583
+
584
+
585
+ def test_substitute_dummies_new_indices():
586
+ i, j = symbols('i j', below_fermi=True, cls=Dummy)
587
+ a, b = symbols('a b', above_fermi=True, cls=Dummy)
588
+ p, q = symbols('p q', cls=Dummy)
589
+ f = Function('f')
590
+ assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0
591
+
592
+
593
+ def test_substitute_dummies_substitution_order():
594
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
595
+ f = Function('f')
596
+ from sympy.utilities.iterables import variations
597
+ for permut in variations([i, j, k, l], 4):
598
+ assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0
599
+
600
+
601
+ def test_dummy_order_inner_outer_lines_VT1T1T1():
602
+ ii = symbols('i', below_fermi=True)
603
+ aa = symbols('a', above_fermi=True)
604
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
605
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
606
+
607
+ v = Function('v')
608
+ t = Function('t')
609
+ dums = _get_ordered_dummies
610
+
611
+ # Coupled-Cluster T1 terms with V*T1*T1*T1
612
+ # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc}
613
+ exprs = [
614
+ # permut v and t <=> swapping internal lines, equivalent
615
+ # irrespective of symmetries in v
616
+ v(k, l, c, d)*t(c, ii)*t(d, l)*t(aa, k),
617
+ v(l, k, c, d)*t(c, ii)*t(d, k)*t(aa, l),
618
+ v(k, l, d, c)*t(d, ii)*t(c, l)*t(aa, k),
619
+ v(l, k, d, c)*t(d, ii)*t(c, k)*t(aa, l),
620
+ ]
621
+ for permut in exprs[1:]:
622
+ assert dums(exprs[0]) != dums(permut)
623
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
624
+
625
+
626
+ def test_dummy_order_inner_outer_lines_VT1T1T1T1():
627
+ ii, jj = symbols('i j', below_fermi=True)
628
+ aa, bb = symbols('a b', above_fermi=True)
629
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
630
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
631
+
632
+ v = Function('v')
633
+ t = Function('t')
634
+ dums = _get_ordered_dummies
635
+
636
+ # Coupled-Cluster T2 terms with V*T1*T1*T1*T1
637
+ exprs = [
638
+ # permut t <=> swapping external lines, not equivalent
639
+ # except if v has certain symmetries.
640
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
641
+ v(k, l, c, d)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l),
642
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l),
643
+ v(k, l, c, d)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l),
644
+ ]
645
+ for permut in exprs[1:]:
646
+ assert dums(exprs[0]) != dums(permut)
647
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
648
+ exprs = [
649
+ # permut v <=> swapping external lines, not equivalent
650
+ # except if v has certain symmetries.
651
+ #
652
+ # Note that in contrast to above, these permutations have identical
653
+ # dummy order. That is because the proximity to external indices
654
+ # has higher influence on the canonical dummy ordering than the
655
+ # position of a dummy on the factors. In fact, the terms here are
656
+ # similar in structure as the result of the dummy substitutions above.
657
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
658
+ v(l, k, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
659
+ v(k, l, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
660
+ v(l, k, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
661
+ ]
662
+ for permut in exprs[1:]:
663
+ assert dums(exprs[0]) == dums(permut)
664
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
665
+ exprs = [
666
+ # permut t and v <=> swapping internal lines, equivalent.
667
+ # Canonical dummy order is different, and a consistent
668
+ # substitution reveals the equivalence.
669
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
670
+ v(k, l, d, c)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l),
671
+ v(l, k, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l),
672
+ v(l, k, d, c)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l),
673
+ ]
674
+ for permut in exprs[1:]:
675
+ assert dums(exprs[0]) != dums(permut)
676
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
677
+
678
+
679
+ def test_get_subNO():
680
+ p, q, r = symbols('p,q,r')
681
+ assert NO(F(p)*F(q)*F(r)).get_subNO(1) == NO(F(p)*F(r))
682
+ assert NO(F(p)*F(q)*F(r)).get_subNO(0) == NO(F(q)*F(r))
683
+ assert NO(F(p)*F(q)*F(r)).get_subNO(2) == NO(F(p)*F(q))
684
+
685
+
686
+ def test_equivalent_internal_lines_VT1T1():
687
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
688
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
689
+
690
+ v = Function('v')
691
+ t = Function('t')
692
+ dums = _get_ordered_dummies
693
+
694
+ exprs = [ # permute v. Different dummy order. Not equivalent.
695
+ v(i, j, a, b)*t(a, i)*t(b, j),
696
+ v(j, i, a, b)*t(a, i)*t(b, j),
697
+ v(i, j, b, a)*t(a, i)*t(b, j),
698
+ ]
699
+ for permut in exprs[1:]:
700
+ assert dums(exprs[0]) != dums(permut)
701
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
702
+
703
+ exprs = [ # permute v. Different dummy order. Equivalent
704
+ v(i, j, a, b)*t(a, i)*t(b, j),
705
+ v(j, i, b, a)*t(a, i)*t(b, j),
706
+ ]
707
+ for permut in exprs[1:]:
708
+ assert dums(exprs[0]) != dums(permut)
709
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
710
+
711
+ exprs = [ # permute t. Same dummy order, not equivalent.
712
+ v(i, j, a, b)*t(a, i)*t(b, j),
713
+ v(i, j, a, b)*t(b, i)*t(a, j),
714
+ ]
715
+ for permut in exprs[1:]:
716
+ assert dums(exprs[0]) == dums(permut)
717
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
718
+
719
+ exprs = [ # permute v and t. Different dummy order, equivalent
720
+ v(i, j, a, b)*t(a, i)*t(b, j),
721
+ v(j, i, a, b)*t(a, j)*t(b, i),
722
+ v(i, j, b, a)*t(b, i)*t(a, j),
723
+ v(j, i, b, a)*t(b, j)*t(a, i),
724
+ ]
725
+ for permut in exprs[1:]:
726
+ assert dums(exprs[0]) != dums(permut)
727
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
728
+
729
+
730
+ def test_equivalent_internal_lines_VT2conjT2():
731
+ # this diagram requires special handling in TCE
732
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
733
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
734
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
735
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
736
+
737
+ from sympy.utilities.iterables import variations
738
+
739
+ v = Function('v')
740
+ t = Function('t')
741
+ dums = _get_ordered_dummies
742
+
743
+ # v(abcd)t(abij)t(ijcd)
744
+ template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(i, j, p3, p4)
745
+ permutator = variations([a, b, c, d], 4)
746
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
747
+ for permut in permutator:
748
+ subslist = zip([p1, p2, p3, p4], permut)
749
+ expr = template.subs(subslist)
750
+ assert dums(base) != dums(expr)
751
+ assert substitute_dummies(expr) == substitute_dummies(base)
752
+ template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(j, i, p3, p4)
753
+ permutator = variations([a, b, c, d], 4)
754
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
755
+ for permut in permutator:
756
+ subslist = zip([p1, p2, p3, p4], permut)
757
+ expr = template.subs(subslist)
758
+ assert dums(base) != dums(expr)
759
+ assert substitute_dummies(expr) == substitute_dummies(base)
760
+
761
+ # v(abcd)t(abij)t(jicd)
762
+ template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(j, i, p3, p4)
763
+ permutator = variations([a, b, c, d], 4)
764
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
765
+ for permut in permutator:
766
+ subslist = zip([p1, p2, p3, p4], permut)
767
+ expr = template.subs(subslist)
768
+ assert dums(base) != dums(expr)
769
+ assert substitute_dummies(expr) == substitute_dummies(base)
770
+ template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(i, j, p3, p4)
771
+ permutator = variations([a, b, c, d], 4)
772
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
773
+ for permut in permutator:
774
+ subslist = zip([p1, p2, p3, p4], permut)
775
+ expr = template.subs(subslist)
776
+ assert dums(base) != dums(expr)
777
+ assert substitute_dummies(expr) == substitute_dummies(base)
778
+
779
+
780
+ def test_equivalent_internal_lines_VT2conjT2_ambiguous_order():
781
+ # These diagrams invokes _determine_ambiguous() because the
782
+ # dummies can not be ordered unambiguously by the key alone
783
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
784
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
785
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
786
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
787
+
788
+ from sympy.utilities.iterables import variations
789
+
790
+ v = Function('v')
791
+ t = Function('t')
792
+ dums = _get_ordered_dummies
793
+
794
+ # v(abcd)t(abij)t(cdij)
795
+ template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(p3, p4, i, j)
796
+ permutator = variations([a, b, c, d], 4)
797
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
798
+ for permut in permutator:
799
+ subslist = zip([p1, p2, p3, p4], permut)
800
+ expr = template.subs(subslist)
801
+ assert dums(base) != dums(expr)
802
+ assert substitute_dummies(expr) == substitute_dummies(base)
803
+ template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(p3, p4, i, j)
804
+ permutator = variations([a, b, c, d], 4)
805
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
806
+ for permut in permutator:
807
+ subslist = zip([p1, p2, p3, p4], permut)
808
+ expr = template.subs(subslist)
809
+ assert dums(base) != dums(expr)
810
+ assert substitute_dummies(expr) == substitute_dummies(base)
811
+
812
+
813
+ def test_equivalent_internal_lines_VT2():
814
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
815
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
816
+
817
+ v = Function('v')
818
+ t = Function('t')
819
+ dums = _get_ordered_dummies
820
+ exprs = [
821
+ # permute v. Same dummy order, not equivalent.
822
+ #
823
+ # This test show that the dummy order may not be sensitive to all
824
+ # index permutations. The following expressions have identical
825
+ # structure as the resulting terms from of the dummy substitutions
826
+ # in the test above. Here, all expressions have the same dummy
827
+ # order, so they cannot be simplified by means of dummy
828
+ # substitution. In order to simplify further, it is necessary to
829
+ # exploit symmetries in the objects, for instance if t or v is
830
+ # antisymmetric.
831
+ v(i, j, a, b)*t(a, b, i, j),
832
+ v(j, i, a, b)*t(a, b, i, j),
833
+ v(i, j, b, a)*t(a, b, i, j),
834
+ v(j, i, b, a)*t(a, b, i, j),
835
+ ]
836
+ for permut in exprs[1:]:
837
+ assert dums(exprs[0]) == dums(permut)
838
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
839
+
840
+ exprs = [
841
+ # permute t.
842
+ v(i, j, a, b)*t(a, b, i, j),
843
+ v(i, j, a, b)*t(b, a, i, j),
844
+ v(i, j, a, b)*t(a, b, j, i),
845
+ v(i, j, a, b)*t(b, a, j, i),
846
+ ]
847
+ for permut in exprs[1:]:
848
+ assert dums(exprs[0]) != dums(permut)
849
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
850
+
851
+ exprs = [ # permute v and t. Relabelling of dummies should be equivalent.
852
+ v(i, j, a, b)*t(a, b, i, j),
853
+ v(j, i, a, b)*t(a, b, j, i),
854
+ v(i, j, b, a)*t(b, a, i, j),
855
+ v(j, i, b, a)*t(b, a, j, i),
856
+ ]
857
+ for permut in exprs[1:]:
858
+ assert dums(exprs[0]) != dums(permut)
859
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
860
+
861
+
862
+ def test_internal_external_VT2T2():
863
+ ii, jj = symbols('i j', below_fermi=True)
864
+ aa, bb = symbols('a b', above_fermi=True)
865
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
866
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
867
+
868
+ v = Function('v')
869
+ t = Function('t')
870
+ dums = _get_ordered_dummies
871
+
872
+ exprs = [
873
+ v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l),
874
+ v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k),
875
+ v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l),
876
+ v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k),
877
+ ]
878
+ for permut in exprs[1:]:
879
+ assert dums(exprs[0]) != dums(permut)
880
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
881
+ exprs = [
882
+ v(k, l, c, d)*t(aa, c, ii, k)*t(d, bb, jj, l),
883
+ v(l, k, c, d)*t(aa, c, ii, l)*t(d, bb, jj, k),
884
+ v(k, l, d, c)*t(aa, d, ii, k)*t(c, bb, jj, l),
885
+ v(l, k, d, c)*t(aa, d, ii, l)*t(c, bb, jj, k),
886
+ ]
887
+ for permut in exprs[1:]:
888
+ assert dums(exprs[0]) != dums(permut)
889
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
890
+ exprs = [
891
+ v(k, l, c, d)*t(c, aa, ii, k)*t(bb, d, jj, l),
892
+ v(l, k, c, d)*t(c, aa, ii, l)*t(bb, d, jj, k),
893
+ v(k, l, d, c)*t(d, aa, ii, k)*t(bb, c, jj, l),
894
+ v(l, k, d, c)*t(d, aa, ii, l)*t(bb, c, jj, k),
895
+ ]
896
+ for permut in exprs[1:]:
897
+ assert dums(exprs[0]) != dums(permut)
898
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
899
+
900
+
901
+ def test_internal_external_pqrs():
902
+ ii, jj = symbols('i j')
903
+ aa, bb = symbols('a b')
904
+ k, l = symbols('k l', cls=Dummy)
905
+ c, d = symbols('c d', cls=Dummy)
906
+
907
+ v = Function('v')
908
+ t = Function('t')
909
+ dums = _get_ordered_dummies
910
+
911
+ exprs = [
912
+ v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l),
913
+ v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k),
914
+ v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l),
915
+ v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k),
916
+ ]
917
+ for permut in exprs[1:]:
918
+ assert dums(exprs[0]) != dums(permut)
919
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
920
+
921
+
922
+ def test_dummy_order_well_defined():
923
+ aa, bb = symbols('a b', above_fermi=True)
924
+ k, l, m = symbols('k l m', below_fermi=True, cls=Dummy)
925
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
926
+ p, q = symbols('p q', cls=Dummy)
927
+
928
+ A = Function('A')
929
+ B = Function('B')
930
+ C = Function('C')
931
+ dums = _get_ordered_dummies
932
+
933
+ # We go through all key components in the order of increasing priority,
934
+ # and consider only fully orderable expressions. Non-orderable expressions
935
+ # are tested elsewhere.
936
+
937
+ # pos in first factor determines sort order
938
+ assert dums(A(k, l)*B(l, k)) == [k, l]
939
+ assert dums(A(l, k)*B(l, k)) == [l, k]
940
+ assert dums(A(k, l)*B(k, l)) == [k, l]
941
+ assert dums(A(l, k)*B(k, l)) == [l, k]
942
+
943
+ # factors involving the index
944
+ assert dums(A(k, l)*B(l, m)*C(k, m)) == [l, k, m]
945
+ assert dums(A(k, l)*B(l, m)*C(m, k)) == [l, k, m]
946
+ assert dums(A(l, k)*B(l, m)*C(k, m)) == [l, k, m]
947
+ assert dums(A(l, k)*B(l, m)*C(m, k)) == [l, k, m]
948
+ assert dums(A(k, l)*B(m, l)*C(k, m)) == [l, k, m]
949
+ assert dums(A(k, l)*B(m, l)*C(m, k)) == [l, k, m]
950
+ assert dums(A(l, k)*B(m, l)*C(k, m)) == [l, k, m]
951
+ assert dums(A(l, k)*B(m, l)*C(m, k)) == [l, k, m]
952
+
953
+ # same, but with factor order determined by non-dummies
954
+ assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, k, m)) == [l, k, m]
955
+ assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, m, k)) == [l, k, m]
956
+ assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, k, m)) == [l, k, m]
957
+ assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, m, k)) == [l, k, m]
958
+ assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, k, m)) == [l, k, m]
959
+ assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, m, k)) == [l, k, m]
960
+ assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, k, m)) == [l, k, m]
961
+ assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, m, k)) == [l, k, m]
962
+
963
+ # index range
964
+ assert dums(A(p, c, k)*B(p, c, k)) == [k, c, p]
965
+ assert dums(A(p, k, c)*B(p, c, k)) == [k, c, p]
966
+ assert dums(A(c, k, p)*B(p, c, k)) == [k, c, p]
967
+ assert dums(A(c, p, k)*B(p, c, k)) == [k, c, p]
968
+ assert dums(A(k, c, p)*B(p, c, k)) == [k, c, p]
969
+ assert dums(A(k, p, c)*B(p, c, k)) == [k, c, p]
970
+ assert dums(B(p, c, k)*A(p, c, k)) == [k, c, p]
971
+ assert dums(B(p, k, c)*A(p, c, k)) == [k, c, p]
972
+ assert dums(B(c, k, p)*A(p, c, k)) == [k, c, p]
973
+ assert dums(B(c, p, k)*A(p, c, k)) == [k, c, p]
974
+ assert dums(B(k, c, p)*A(p, c, k)) == [k, c, p]
975
+ assert dums(B(k, p, c)*A(p, c, k)) == [k, c, p]
976
+
977
+
978
+ def test_dummy_order_ambiguous():
979
+ aa, bb = symbols('a b', above_fermi=True)
980
+ i, j, k, l, m = symbols('i j k l m', below_fermi=True, cls=Dummy)
981
+ a, b, c, d, e = symbols('a b c d e', above_fermi=True, cls=Dummy)
982
+ p, q = symbols('p q', cls=Dummy)
983
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
984
+ p5, p6, p7, p8 = symbols('p5 p6 p7 p8', above_fermi=True, cls=Dummy)
985
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
986
+ h5, h6, h7, h8 = symbols('h5 h6 h7 h8', below_fermi=True, cls=Dummy)
987
+
988
+ A = Function('A')
989
+ B = Function('B')
990
+
991
+ from sympy.utilities.iterables import variations
992
+
993
+ # A*A*A*A*B -- ordering of p5 and p4 is used to figure out the rest
994
+ template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*B(p5, p4)
995
+ permutator = variations([a, b, c, d, e], 5)
996
+ base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
997
+ for permut in permutator:
998
+ subslist = zip([p1, p2, p3, p4, p5], permut)
999
+ expr = template.subs(subslist)
1000
+ assert substitute_dummies(expr) == substitute_dummies(base)
1001
+
1002
+ # A*A*A*A*A -- an arbitrary index is assigned and the rest are figured out
1003
+ template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*A(p5, p4)
1004
+ permutator = variations([a, b, c, d, e], 5)
1005
+ base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
1006
+ for permut in permutator:
1007
+ subslist = zip([p1, p2, p3, p4, p5], permut)
1008
+ expr = template.subs(subslist)
1009
+ assert substitute_dummies(expr) == substitute_dummies(base)
1010
+
1011
+ # A*A*A -- ordering of p5 and p4 is used to figure out the rest
1012
+ template = A(p1, p2, p4, p1)*A(p2, p3, p3, p5)*A(p5, p4)
1013
+ permutator = variations([a, b, c, d, e], 5)
1014
+ base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
1015
+ for permut in permutator:
1016
+ subslist = zip([p1, p2, p3, p4, p5], permut)
1017
+ expr = template.subs(subslist)
1018
+ assert substitute_dummies(expr) == substitute_dummies(base)
1019
+
1020
+
1021
+ def atv(*args):
1022
+ return AntiSymmetricTensor('v', args[:2], args[2:] )
1023
+
1024
+
1025
+ def att(*args):
1026
+ if len(args) == 4:
1027
+ return AntiSymmetricTensor('t', args[:2], args[2:] )
1028
+ elif len(args) == 2:
1029
+ return AntiSymmetricTensor('t', (args[0],), (args[1],))
1030
+
1031
+
1032
+ def test_dummy_order_inner_outer_lines_VT1T1T1_AT():
1033
+ ii = symbols('i', below_fermi=True)
1034
+ aa = symbols('a', above_fermi=True)
1035
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
1036
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
1037
+
1038
+ # Coupled-Cluster T1 terms with V*T1*T1*T1
1039
+ # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc}
1040
+ exprs = [
1041
+ # permut v and t <=> swapping internal lines, equivalent
1042
+ # irrespective of symmetries in v
1043
+ atv(k, l, c, d)*att(c, ii)*att(d, l)*att(aa, k),
1044
+ atv(l, k, c, d)*att(c, ii)*att(d, k)*att(aa, l),
1045
+ atv(k, l, d, c)*att(d, ii)*att(c, l)*att(aa, k),
1046
+ atv(l, k, d, c)*att(d, ii)*att(c, k)*att(aa, l),
1047
+ ]
1048
+ for permut in exprs[1:]:
1049
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1050
+
1051
+
1052
+ def test_dummy_order_inner_outer_lines_VT1T1T1T1_AT():
1053
+ ii, jj = symbols('i j', below_fermi=True)
1054
+ aa, bb = symbols('a b', above_fermi=True)
1055
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
1056
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
1057
+
1058
+ # Coupled-Cluster T2 terms with V*T1*T1*T1*T1
1059
+ # non-equivalent substitutions (change of sign)
1060
+ exprs = [
1061
+ # permut t <=> swapping external lines
1062
+ atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l),
1063
+ atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(aa, k)*att(bb, l),
1064
+ atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(bb, k)*att(aa, l),
1065
+ ]
1066
+ for permut in exprs[1:]:
1067
+ assert substitute_dummies(exprs[0]) == -substitute_dummies(permut)
1068
+
1069
+ # equivalent substitutions
1070
+ exprs = [
1071
+ atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l),
1072
+ # permut t <=> swapping external lines
1073
+ atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(bb, k)*att(aa, l),
1074
+ ]
1075
+ for permut in exprs[1:]:
1076
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1077
+
1078
+
1079
+ def test_equivalent_internal_lines_VT1T1_AT():
1080
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
1081
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
1082
+
1083
+ exprs = [ # permute v. Different dummy order. Not equivalent.
1084
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1085
+ atv(j, i, a, b)*att(a, i)*att(b, j),
1086
+ atv(i, j, b, a)*att(a, i)*att(b, j),
1087
+ ]
1088
+ for permut in exprs[1:]:
1089
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1090
+
1091
+ exprs = [ # permute v. Different dummy order. Equivalent
1092
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1093
+ atv(j, i, b, a)*att(a, i)*att(b, j),
1094
+ ]
1095
+ for permut in exprs[1:]:
1096
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1097
+
1098
+ exprs = [ # permute t. Same dummy order, not equivalent.
1099
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1100
+ atv(i, j, a, b)*att(b, i)*att(a, j),
1101
+ ]
1102
+ for permut in exprs[1:]:
1103
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1104
+
1105
+ exprs = [ # permute v and t. Different dummy order, equivalent
1106
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1107
+ atv(j, i, a, b)*att(a, j)*att(b, i),
1108
+ atv(i, j, b, a)*att(b, i)*att(a, j),
1109
+ atv(j, i, b, a)*att(b, j)*att(a, i),
1110
+ ]
1111
+ for permut in exprs[1:]:
1112
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1113
+
1114
+
1115
+ def test_equivalent_internal_lines_VT2conjT2_AT():
1116
+ # this diagram requires special handling in TCE
1117
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
1118
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
1119
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
1120
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
1121
+
1122
+ from sympy.utilities.iterables import variations
1123
+
1124
+ # atv(abcd)att(abij)att(ijcd)
1125
+ template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(i, j, p3, p4)
1126
+ permutator = variations([a, b, c, d], 4)
1127
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1128
+ for permut in permutator:
1129
+ subslist = zip([p1, p2, p3, p4], permut)
1130
+ expr = template.subs(subslist)
1131
+ assert substitute_dummies(expr) == substitute_dummies(base)
1132
+ template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(j, i, p3, p4)
1133
+ permutator = variations([a, b, c, d], 4)
1134
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1135
+ for permut in permutator:
1136
+ subslist = zip([p1, p2, p3, p4], permut)
1137
+ expr = template.subs(subslist)
1138
+ assert substitute_dummies(expr) == substitute_dummies(base)
1139
+
1140
+ # atv(abcd)att(abij)att(jicd)
1141
+ template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(j, i, p3, p4)
1142
+ permutator = variations([a, b, c, d], 4)
1143
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1144
+ for permut in permutator:
1145
+ subslist = zip([p1, p2, p3, p4], permut)
1146
+ expr = template.subs(subslist)
1147
+ assert substitute_dummies(expr) == substitute_dummies(base)
1148
+ template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(i, j, p3, p4)
1149
+ permutator = variations([a, b, c, d], 4)
1150
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1151
+ for permut in permutator:
1152
+ subslist = zip([p1, p2, p3, p4], permut)
1153
+ expr = template.subs(subslist)
1154
+ assert substitute_dummies(expr) == substitute_dummies(base)
1155
+
1156
+
1157
+ def test_equivalent_internal_lines_VT2conjT2_ambiguous_order_AT():
1158
+ # These diagrams invokes _determine_ambiguous() because the
1159
+ # dummies can not be ordered unambiguously by the key alone
1160
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
1161
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
1162
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
1163
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
1164
+
1165
+ from sympy.utilities.iterables import variations
1166
+
1167
+ # atv(abcd)att(abij)att(cdij)
1168
+ template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(p3, p4, i, j)
1169
+ permutator = variations([a, b, c, d], 4)
1170
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1171
+ for permut in permutator:
1172
+ subslist = zip([p1, p2, p3, p4], permut)
1173
+ expr = template.subs(subslist)
1174
+ assert substitute_dummies(expr) == substitute_dummies(base)
1175
+ template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(p3, p4, i, j)
1176
+ permutator = variations([a, b, c, d], 4)
1177
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1178
+ for permut in permutator:
1179
+ subslist = zip([p1, p2, p3, p4], permut)
1180
+ expr = template.subs(subslist)
1181
+ assert substitute_dummies(expr) == substitute_dummies(base)
1182
+
1183
+
1184
+ def test_equivalent_internal_lines_VT2_AT():
1185
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
1186
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
1187
+
1188
+ exprs = [
1189
+ # permute v. Same dummy order, not equivalent.
1190
+ atv(i, j, a, b)*att(a, b, i, j),
1191
+ atv(j, i, a, b)*att(a, b, i, j),
1192
+ atv(i, j, b, a)*att(a, b, i, j),
1193
+ ]
1194
+ for permut in exprs[1:]:
1195
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1196
+
1197
+ exprs = [
1198
+ # permute t.
1199
+ atv(i, j, a, b)*att(a, b, i, j),
1200
+ atv(i, j, a, b)*att(b, a, i, j),
1201
+ atv(i, j, a, b)*att(a, b, j, i),
1202
+ ]
1203
+ for permut in exprs[1:]:
1204
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1205
+
1206
+ exprs = [ # permute v and t. Relabelling of dummies should be equivalent.
1207
+ atv(i, j, a, b)*att(a, b, i, j),
1208
+ atv(j, i, a, b)*att(a, b, j, i),
1209
+ atv(i, j, b, a)*att(b, a, i, j),
1210
+ atv(j, i, b, a)*att(b, a, j, i),
1211
+ ]
1212
+ for permut in exprs[1:]:
1213
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1214
+
1215
+
1216
+ def test_internal_external_VT2T2_AT():
1217
+ ii, jj = symbols('i j', below_fermi=True)
1218
+ aa, bb = symbols('a b', above_fermi=True)
1219
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
1220
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
1221
+
1222
+ exprs = [
1223
+ atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l),
1224
+ atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k),
1225
+ atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l),
1226
+ atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k),
1227
+ ]
1228
+ for permut in exprs[1:]:
1229
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1230
+ exprs = [
1231
+ atv(k, l, c, d)*att(aa, c, ii, k)*att(d, bb, jj, l),
1232
+ atv(l, k, c, d)*att(aa, c, ii, l)*att(d, bb, jj, k),
1233
+ atv(k, l, d, c)*att(aa, d, ii, k)*att(c, bb, jj, l),
1234
+ atv(l, k, d, c)*att(aa, d, ii, l)*att(c, bb, jj, k),
1235
+ ]
1236
+ for permut in exprs[1:]:
1237
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1238
+ exprs = [
1239
+ atv(k, l, c, d)*att(c, aa, ii, k)*att(bb, d, jj, l),
1240
+ atv(l, k, c, d)*att(c, aa, ii, l)*att(bb, d, jj, k),
1241
+ atv(k, l, d, c)*att(d, aa, ii, k)*att(bb, c, jj, l),
1242
+ atv(l, k, d, c)*att(d, aa, ii, l)*att(bb, c, jj, k),
1243
+ ]
1244
+ for permut in exprs[1:]:
1245
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1246
+
1247
+
1248
+ def test_internal_external_pqrs_AT():
1249
+ ii, jj = symbols('i j')
1250
+ aa, bb = symbols('a b')
1251
+ k, l = symbols('k l', cls=Dummy)
1252
+ c, d = symbols('c d', cls=Dummy)
1253
+
1254
+ exprs = [
1255
+ atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l),
1256
+ atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k),
1257
+ atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l),
1258
+ atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k),
1259
+ ]
1260
+ for permut in exprs[1:]:
1261
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1262
+
1263
+
1264
+ def test_issue_19661():
1265
+ a = Symbol('0')
1266
+ assert latex(Commutator(Bd(a)**2, B(a))
1267
+ ) == '- \\left[b_{0},{b^\\dagger_{0}}^{2}\\right]'
1268
+
1269
+
1270
+ def test_canonical_ordering_AntiSymmetricTensor():
1271
+ v = symbols("v")
1272
+
1273
+ c, d = symbols(('c','d'), above_fermi=True,
1274
+ cls=Dummy)
1275
+ k, l = symbols(('k','l'), below_fermi=True,
1276
+ cls=Dummy)
1277
+
1278
+ # formerly, the left gave either the left or the right
1279
+ assert AntiSymmetricTensor(v, (k, l), (d, c)
1280
+ ) == -AntiSymmetricTensor(v, (l, k), (d, c))
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__init__.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort:skip_file
2
+ """
3
+ Dimensional analysis and unit systems.
4
+
5
+ This module defines dimension/unit systems and physical quantities. It is
6
+ based on a group-theoretical construction where dimensions are represented as
7
+ vectors (coefficients being the exponents), and units are defined as a dimension
8
+ to which we added a scale.
9
+
10
+ Quantities are built from a factor and a unit, and are the basic objects that
11
+ one will use when doing computations.
12
+
13
+ All objects except systems and prefixes can be used in SymPy expressions.
14
+ Note that as part of a CAS, various objects do not combine automatically
15
+ under operations.
16
+
17
+ Details about the implementation can be found in the documentation, and we
18
+ will not repeat all the explanations we gave there concerning our approach.
19
+ Ideas about future developments can be found on the `Github wiki
20
+ <https://github.com/sympy/sympy/wiki/Unit-systems>`_, and you should consult
21
+ this page if you are willing to help.
22
+
23
+ Useful functions:
24
+
25
+ - ``find_unit``: easily lookup pre-defined units.
26
+ - ``convert_to(expr, newunit)``: converts an expression into the same
27
+ expression expressed in another unit.
28
+
29
+ """
30
+
31
+ from .dimensions import Dimension, DimensionSystem
32
+ from .unitsystem import UnitSystem
33
+ from .util import convert_to
34
+ from .quantities import Quantity
35
+
36
+ from .definitions.dimension_definitions import (
37
+ amount_of_substance, acceleration, action, area,
38
+ capacitance, charge, conductance, current, energy,
39
+ force, frequency, impedance, inductance, length,
40
+ luminous_intensity, magnetic_density,
41
+ magnetic_flux, mass, momentum, power, pressure, temperature, time,
42
+ velocity, voltage, volume
43
+ )
44
+
45
+ Unit = Quantity
46
+
47
+ speed = velocity
48
+ luminosity = luminous_intensity
49
+ magnetic_flux_density = magnetic_density
50
+ amount = amount_of_substance
51
+
52
+ from .prefixes import (
53
+ # 10-power based:
54
+ yotta,
55
+ zetta,
56
+ exa,
57
+ peta,
58
+ tera,
59
+ giga,
60
+ mega,
61
+ kilo,
62
+ hecto,
63
+ deca,
64
+ deci,
65
+ centi,
66
+ milli,
67
+ micro,
68
+ nano,
69
+ pico,
70
+ femto,
71
+ atto,
72
+ zepto,
73
+ yocto,
74
+ # 2-power based:
75
+ kibi,
76
+ mebi,
77
+ gibi,
78
+ tebi,
79
+ pebi,
80
+ exbi,
81
+ )
82
+
83
+ from .definitions import (
84
+ percent, percents,
85
+ permille,
86
+ rad, radian, radians,
87
+ deg, degree, degrees,
88
+ sr, steradian, steradians,
89
+ mil, angular_mil, angular_mils,
90
+ m, meter, meters,
91
+ kg, kilogram, kilograms,
92
+ s, second, seconds,
93
+ A, ampere, amperes,
94
+ K, kelvin, kelvins,
95
+ mol, mole, moles,
96
+ cd, candela, candelas,
97
+ g, gram, grams,
98
+ mg, milligram, milligrams,
99
+ ug, microgram, micrograms,
100
+ t, tonne, metric_ton,
101
+ newton, newtons, N,
102
+ joule, joules, J,
103
+ watt, watts, W,
104
+ pascal, pascals, Pa, pa,
105
+ hertz, hz, Hz,
106
+ coulomb, coulombs, C,
107
+ volt, volts, v, V,
108
+ ohm, ohms,
109
+ siemens, S, mho, mhos,
110
+ farad, farads, F,
111
+ henry, henrys, H,
112
+ tesla, teslas, T,
113
+ weber, webers, Wb, wb,
114
+ optical_power, dioptre, D,
115
+ lux, lx,
116
+ katal, kat,
117
+ gray, Gy,
118
+ becquerel, Bq,
119
+ km, kilometer, kilometers,
120
+ dm, decimeter, decimeters,
121
+ cm, centimeter, centimeters,
122
+ mm, millimeter, millimeters,
123
+ um, micrometer, micrometers, micron, microns,
124
+ nm, nanometer, nanometers,
125
+ pm, picometer, picometers,
126
+ ft, foot, feet,
127
+ inch, inches,
128
+ yd, yard, yards,
129
+ mi, mile, miles,
130
+ nmi, nautical_mile, nautical_miles,
131
+ angstrom, angstroms,
132
+ ha, hectare,
133
+ l, L, liter, liters,
134
+ dl, dL, deciliter, deciliters,
135
+ cl, cL, centiliter, centiliters,
136
+ ml, mL, milliliter, milliliters,
137
+ ms, millisecond, milliseconds,
138
+ us, microsecond, microseconds,
139
+ ns, nanosecond, nanoseconds,
140
+ ps, picosecond, picoseconds,
141
+ minute, minutes,
142
+ h, hour, hours,
143
+ day, days,
144
+ anomalistic_year, anomalistic_years,
145
+ sidereal_year, sidereal_years,
146
+ tropical_year, tropical_years,
147
+ common_year, common_years,
148
+ julian_year, julian_years,
149
+ draconic_year, draconic_years,
150
+ gaussian_year, gaussian_years,
151
+ full_moon_cycle, full_moon_cycles,
152
+ year, years,
153
+ G, gravitational_constant,
154
+ c, speed_of_light,
155
+ elementary_charge,
156
+ hbar,
157
+ planck,
158
+ eV, electronvolt, electronvolts,
159
+ avogadro_number,
160
+ avogadro, avogadro_constant,
161
+ boltzmann, boltzmann_constant,
162
+ stefan, stefan_boltzmann_constant,
163
+ R, molar_gas_constant,
164
+ faraday_constant,
165
+ josephson_constant,
166
+ von_klitzing_constant,
167
+ Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant,
168
+ me, electron_rest_mass,
169
+ gee, gees, acceleration_due_to_gravity,
170
+ u0, magnetic_constant, vacuum_permeability,
171
+ e0, electric_constant, vacuum_permittivity,
172
+ Z0, vacuum_impedance,
173
+ coulomb_constant, electric_force_constant,
174
+ atmosphere, atmospheres, atm,
175
+ kPa,
176
+ bar, bars,
177
+ pound, pounds,
178
+ psi,
179
+ dHg0,
180
+ mmHg, torr,
181
+ mmu, mmus, milli_mass_unit,
182
+ quart, quarts,
183
+ ly, lightyear, lightyears,
184
+ au, astronomical_unit, astronomical_units,
185
+ planck_mass,
186
+ planck_time,
187
+ planck_temperature,
188
+ planck_length,
189
+ planck_charge,
190
+ planck_area,
191
+ planck_volume,
192
+ planck_momentum,
193
+ planck_energy,
194
+ planck_force,
195
+ planck_power,
196
+ planck_density,
197
+ planck_energy_density,
198
+ planck_intensity,
199
+ planck_angular_frequency,
200
+ planck_pressure,
201
+ planck_current,
202
+ planck_voltage,
203
+ planck_impedance,
204
+ planck_acceleration,
205
+ bit, bits,
206
+ byte,
207
+ kibibyte, kibibytes,
208
+ mebibyte, mebibytes,
209
+ gibibyte, gibibytes,
210
+ tebibyte, tebibytes,
211
+ pebibyte, pebibytes,
212
+ exbibyte, exbibytes,
213
+ )
214
+
215
+ from .systems import (
216
+ mks, mksa, si
217
+ )
218
+
219
+
220
+ def find_unit(quantity, unit_system="SI"):
221
+ """
222
+ Return a list of matching units or dimension names.
223
+
224
+ - If ``quantity`` is a string -- units/dimensions containing the string
225
+ `quantity`.
226
+ - If ``quantity`` is a unit or dimension -- units having matching base
227
+ units or dimensions.
228
+
229
+ Examples
230
+ ========
231
+
232
+ >>> from sympy.physics import units as u
233
+ >>> u.find_unit('charge')
234
+ ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
235
+ >>> u.find_unit(u.charge)
236
+ ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
237
+ >>> u.find_unit("ampere")
238
+ ['ampere', 'amperes']
239
+ >>> u.find_unit('angstrom')
240
+ ['angstrom', 'angstroms']
241
+ >>> u.find_unit('volt')
242
+ ['volt', 'volts', 'electronvolt', 'electronvolts', 'planck_voltage']
243
+ >>> u.find_unit(u.inch**3)[:9]
244
+ ['L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter']
245
+ """
246
+ unit_system = UnitSystem.get_unit_system(unit_system)
247
+
248
+ import sympy.physics.units as u
249
+ rv = []
250
+ if isinstance(quantity, str):
251
+ rv = [i for i in dir(u) if quantity in i and isinstance(getattr(u, i), Quantity)]
252
+ dim = getattr(u, quantity)
253
+ if isinstance(dim, Dimension):
254
+ rv.extend(find_unit(dim))
255
+ else:
256
+ for i in sorted(dir(u)):
257
+ other = getattr(u, i)
258
+ if not isinstance(other, Quantity):
259
+ continue
260
+ if isinstance(quantity, Quantity):
261
+ if quantity.dimension == other.dimension:
262
+ rv.append(str(i))
263
+ elif isinstance(quantity, Dimension):
264
+ if other.dimension == quantity:
265
+ rv.append(str(i))
266
+ elif other.dimension == Dimension(unit_system.get_dimensional_expr(quantity)):
267
+ rv.append(str(i))
268
+ return sorted(set(rv), key=lambda x: (len(x), x))
269
+
270
+ # NOTE: the old units module had additional variables:
271
+ # 'density', 'illuminance', 'resistance'.
272
+ # They were not dimensions, but units (old Unit class).
273
+
274
+ __all__ = [
275
+ 'Dimension', 'DimensionSystem',
276
+ 'UnitSystem',
277
+ 'convert_to',
278
+ 'Quantity',
279
+
280
+ 'amount_of_substance', 'acceleration', 'action', 'area',
281
+ 'capacitance', 'charge', 'conductance', 'current', 'energy',
282
+ 'force', 'frequency', 'impedance', 'inductance', 'length',
283
+ 'luminous_intensity', 'magnetic_density',
284
+ 'magnetic_flux', 'mass', 'momentum', 'power', 'pressure', 'temperature', 'time',
285
+ 'velocity', 'voltage', 'volume',
286
+
287
+ 'Unit',
288
+
289
+ 'speed',
290
+ 'luminosity',
291
+ 'magnetic_flux_density',
292
+ 'amount',
293
+
294
+ 'yotta',
295
+ 'zetta',
296
+ 'exa',
297
+ 'peta',
298
+ 'tera',
299
+ 'giga',
300
+ 'mega',
301
+ 'kilo',
302
+ 'hecto',
303
+ 'deca',
304
+ 'deci',
305
+ 'centi',
306
+ 'milli',
307
+ 'micro',
308
+ 'nano',
309
+ 'pico',
310
+ 'femto',
311
+ 'atto',
312
+ 'zepto',
313
+ 'yocto',
314
+
315
+ 'kibi',
316
+ 'mebi',
317
+ 'gibi',
318
+ 'tebi',
319
+ 'pebi',
320
+ 'exbi',
321
+
322
+ 'percent', 'percents',
323
+ 'permille',
324
+ 'rad', 'radian', 'radians',
325
+ 'deg', 'degree', 'degrees',
326
+ 'sr', 'steradian', 'steradians',
327
+ 'mil', 'angular_mil', 'angular_mils',
328
+ 'm', 'meter', 'meters',
329
+ 'kg', 'kilogram', 'kilograms',
330
+ 's', 'second', 'seconds',
331
+ 'A', 'ampere', 'amperes',
332
+ 'K', 'kelvin', 'kelvins',
333
+ 'mol', 'mole', 'moles',
334
+ 'cd', 'candela', 'candelas',
335
+ 'g', 'gram', 'grams',
336
+ 'mg', 'milligram', 'milligrams',
337
+ 'ug', 'microgram', 'micrograms',
338
+ 't', 'tonne', 'metric_ton',
339
+ 'newton', 'newtons', 'N',
340
+ 'joule', 'joules', 'J',
341
+ 'watt', 'watts', 'W',
342
+ 'pascal', 'pascals', 'Pa', 'pa',
343
+ 'hertz', 'hz', 'Hz',
344
+ 'coulomb', 'coulombs', 'C',
345
+ 'volt', 'volts', 'v', 'V',
346
+ 'ohm', 'ohms',
347
+ 'siemens', 'S', 'mho', 'mhos',
348
+ 'farad', 'farads', 'F',
349
+ 'henry', 'henrys', 'H',
350
+ 'tesla', 'teslas', 'T',
351
+ 'weber', 'webers', 'Wb', 'wb',
352
+ 'optical_power', 'dioptre', 'D',
353
+ 'lux', 'lx',
354
+ 'katal', 'kat',
355
+ 'gray', 'Gy',
356
+ 'becquerel', 'Bq',
357
+ 'km', 'kilometer', 'kilometers',
358
+ 'dm', 'decimeter', 'decimeters',
359
+ 'cm', 'centimeter', 'centimeters',
360
+ 'mm', 'millimeter', 'millimeters',
361
+ 'um', 'micrometer', 'micrometers', 'micron', 'microns',
362
+ 'nm', 'nanometer', 'nanometers',
363
+ 'pm', 'picometer', 'picometers',
364
+ 'ft', 'foot', 'feet',
365
+ 'inch', 'inches',
366
+ 'yd', 'yard', 'yards',
367
+ 'mi', 'mile', 'miles',
368
+ 'nmi', 'nautical_mile', 'nautical_miles',
369
+ 'angstrom', 'angstroms',
370
+ 'ha', 'hectare',
371
+ 'l', 'L', 'liter', 'liters',
372
+ 'dl', 'dL', 'deciliter', 'deciliters',
373
+ 'cl', 'cL', 'centiliter', 'centiliters',
374
+ 'ml', 'mL', 'milliliter', 'milliliters',
375
+ 'ms', 'millisecond', 'milliseconds',
376
+ 'us', 'microsecond', 'microseconds',
377
+ 'ns', 'nanosecond', 'nanoseconds',
378
+ 'ps', 'picosecond', 'picoseconds',
379
+ 'minute', 'minutes',
380
+ 'h', 'hour', 'hours',
381
+ 'day', 'days',
382
+ 'anomalistic_year', 'anomalistic_years',
383
+ 'sidereal_year', 'sidereal_years',
384
+ 'tropical_year', 'tropical_years',
385
+ 'common_year', 'common_years',
386
+ 'julian_year', 'julian_years',
387
+ 'draconic_year', 'draconic_years',
388
+ 'gaussian_year', 'gaussian_years',
389
+ 'full_moon_cycle', 'full_moon_cycles',
390
+ 'year', 'years',
391
+ 'G', 'gravitational_constant',
392
+ 'c', 'speed_of_light',
393
+ 'elementary_charge',
394
+ 'hbar',
395
+ 'planck',
396
+ 'eV', 'electronvolt', 'electronvolts',
397
+ 'avogadro_number',
398
+ 'avogadro', 'avogadro_constant',
399
+ 'boltzmann', 'boltzmann_constant',
400
+ 'stefan', 'stefan_boltzmann_constant',
401
+ 'R', 'molar_gas_constant',
402
+ 'faraday_constant',
403
+ 'josephson_constant',
404
+ 'von_klitzing_constant',
405
+ 'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
406
+ 'me', 'electron_rest_mass',
407
+ 'gee', 'gees', 'acceleration_due_to_gravity',
408
+ 'u0', 'magnetic_constant', 'vacuum_permeability',
409
+ 'e0', 'electric_constant', 'vacuum_permittivity',
410
+ 'Z0', 'vacuum_impedance',
411
+ 'coulomb_constant', 'electric_force_constant',
412
+ 'atmosphere', 'atmospheres', 'atm',
413
+ 'kPa',
414
+ 'bar', 'bars',
415
+ 'pound', 'pounds',
416
+ 'psi',
417
+ 'dHg0',
418
+ 'mmHg', 'torr',
419
+ 'mmu', 'mmus', 'milli_mass_unit',
420
+ 'quart', 'quarts',
421
+ 'ly', 'lightyear', 'lightyears',
422
+ 'au', 'astronomical_unit', 'astronomical_units',
423
+ 'planck_mass',
424
+ 'planck_time',
425
+ 'planck_temperature',
426
+ 'planck_length',
427
+ 'planck_charge',
428
+ 'planck_area',
429
+ 'planck_volume',
430
+ 'planck_momentum',
431
+ 'planck_energy',
432
+ 'planck_force',
433
+ 'planck_power',
434
+ 'planck_density',
435
+ 'planck_energy_density',
436
+ 'planck_intensity',
437
+ 'planck_angular_frequency',
438
+ 'planck_pressure',
439
+ 'planck_current',
440
+ 'planck_voltage',
441
+ 'planck_impedance',
442
+ 'planck_acceleration',
443
+ 'bit', 'bits',
444
+ 'byte',
445
+ 'kibibyte', 'kibibytes',
446
+ 'mebibyte', 'mebibytes',
447
+ 'gibibyte', 'gibibytes',
448
+ 'tebibyte', 'tebibytes',
449
+ 'pebibyte', 'pebibytes',
450
+ 'exbibyte', 'exbibytes',
451
+
452
+ 'mks', 'mksa', 'si',
453
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/dimensions.cpython-310.pyc ADDED
Binary file (21.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/prefixes.cpython-310.pyc ADDED
Binary file (6.06 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/unitsystem.cpython-310.pyc ADDED
Binary file (7.72 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/__pycache__/util.cpython-310.pyc ADDED
Binary file (9.63 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .unit_definitions import (
2
+ percent, percents,
3
+ permille,
4
+ rad, radian, radians,
5
+ deg, degree, degrees,
6
+ sr, steradian, steradians,
7
+ mil, angular_mil, angular_mils,
8
+ m, meter, meters,
9
+ kg, kilogram, kilograms,
10
+ s, second, seconds,
11
+ A, ampere, amperes,
12
+ K, kelvin, kelvins,
13
+ mol, mole, moles,
14
+ cd, candela, candelas,
15
+ g, gram, grams,
16
+ mg, milligram, milligrams,
17
+ ug, microgram, micrograms,
18
+ t, tonne, metric_ton,
19
+ newton, newtons, N,
20
+ joule, joules, J,
21
+ watt, watts, W,
22
+ pascal, pascals, Pa, pa,
23
+ hertz, hz, Hz,
24
+ coulomb, coulombs, C,
25
+ volt, volts, v, V,
26
+ ohm, ohms,
27
+ siemens, S, mho, mhos,
28
+ farad, farads, F,
29
+ henry, henrys, H,
30
+ tesla, teslas, T,
31
+ weber, webers, Wb, wb,
32
+ optical_power, dioptre, D,
33
+ lux, lx,
34
+ katal, kat,
35
+ gray, Gy,
36
+ becquerel, Bq,
37
+ km, kilometer, kilometers,
38
+ dm, decimeter, decimeters,
39
+ cm, centimeter, centimeters,
40
+ mm, millimeter, millimeters,
41
+ um, micrometer, micrometers, micron, microns,
42
+ nm, nanometer, nanometers,
43
+ pm, picometer, picometers,
44
+ ft, foot, feet,
45
+ inch, inches,
46
+ yd, yard, yards,
47
+ mi, mile, miles,
48
+ nmi, nautical_mile, nautical_miles,
49
+ ha, hectare,
50
+ l, L, liter, liters,
51
+ dl, dL, deciliter, deciliters,
52
+ cl, cL, centiliter, centiliters,
53
+ ml, mL, milliliter, milliliters,
54
+ ms, millisecond, milliseconds,
55
+ us, microsecond, microseconds,
56
+ ns, nanosecond, nanoseconds,
57
+ ps, picosecond, picoseconds,
58
+ minute, minutes,
59
+ h, hour, hours,
60
+ day, days,
61
+ anomalistic_year, anomalistic_years,
62
+ sidereal_year, sidereal_years,
63
+ tropical_year, tropical_years,
64
+ common_year, common_years,
65
+ julian_year, julian_years,
66
+ draconic_year, draconic_years,
67
+ gaussian_year, gaussian_years,
68
+ full_moon_cycle, full_moon_cycles,
69
+ year, years,
70
+ G, gravitational_constant,
71
+ c, speed_of_light,
72
+ elementary_charge,
73
+ hbar,
74
+ planck,
75
+ eV, electronvolt, electronvolts,
76
+ avogadro_number,
77
+ avogadro, avogadro_constant,
78
+ boltzmann, boltzmann_constant,
79
+ stefan, stefan_boltzmann_constant,
80
+ R, molar_gas_constant,
81
+ faraday_constant,
82
+ josephson_constant,
83
+ von_klitzing_constant,
84
+ Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant,
85
+ me, electron_rest_mass,
86
+ gee, gees, acceleration_due_to_gravity,
87
+ u0, magnetic_constant, vacuum_permeability,
88
+ e0, electric_constant, vacuum_permittivity,
89
+ Z0, vacuum_impedance,
90
+ coulomb_constant, coulombs_constant, electric_force_constant,
91
+ atmosphere, atmospheres, atm,
92
+ kPa, kilopascal,
93
+ bar, bars,
94
+ pound, pounds,
95
+ psi,
96
+ dHg0,
97
+ mmHg, torr,
98
+ mmu, mmus, milli_mass_unit,
99
+ quart, quarts,
100
+ angstrom, angstroms,
101
+ ly, lightyear, lightyears,
102
+ au, astronomical_unit, astronomical_units,
103
+ planck_mass,
104
+ planck_time,
105
+ planck_temperature,
106
+ planck_length,
107
+ planck_charge,
108
+ planck_area,
109
+ planck_volume,
110
+ planck_momentum,
111
+ planck_energy,
112
+ planck_force,
113
+ planck_power,
114
+ planck_density,
115
+ planck_energy_density,
116
+ planck_intensity,
117
+ planck_angular_frequency,
118
+ planck_pressure,
119
+ planck_current,
120
+ planck_voltage,
121
+ planck_impedance,
122
+ planck_acceleration,
123
+ bit, bits,
124
+ byte,
125
+ kibibyte, kibibytes,
126
+ mebibyte, mebibytes,
127
+ gibibyte, gibibytes,
128
+ tebibyte, tebibytes,
129
+ pebibyte, pebibytes,
130
+ exbibyte, exbibytes,
131
+ curie, rutherford
132
+ )
133
+
134
+ __all__ = [
135
+ 'percent', 'percents',
136
+ 'permille',
137
+ 'rad', 'radian', 'radians',
138
+ 'deg', 'degree', 'degrees',
139
+ 'sr', 'steradian', 'steradians',
140
+ 'mil', 'angular_mil', 'angular_mils',
141
+ 'm', 'meter', 'meters',
142
+ 'kg', 'kilogram', 'kilograms',
143
+ 's', 'second', 'seconds',
144
+ 'A', 'ampere', 'amperes',
145
+ 'K', 'kelvin', 'kelvins',
146
+ 'mol', 'mole', 'moles',
147
+ 'cd', 'candela', 'candelas',
148
+ 'g', 'gram', 'grams',
149
+ 'mg', 'milligram', 'milligrams',
150
+ 'ug', 'microgram', 'micrograms',
151
+ 't', 'tonne', 'metric_ton',
152
+ 'newton', 'newtons', 'N',
153
+ 'joule', 'joules', 'J',
154
+ 'watt', 'watts', 'W',
155
+ 'pascal', 'pascals', 'Pa', 'pa',
156
+ 'hertz', 'hz', 'Hz',
157
+ 'coulomb', 'coulombs', 'C',
158
+ 'volt', 'volts', 'v', 'V',
159
+ 'ohm', 'ohms',
160
+ 'siemens', 'S', 'mho', 'mhos',
161
+ 'farad', 'farads', 'F',
162
+ 'henry', 'henrys', 'H',
163
+ 'tesla', 'teslas', 'T',
164
+ 'weber', 'webers', 'Wb', 'wb',
165
+ 'optical_power', 'dioptre', 'D',
166
+ 'lux', 'lx',
167
+ 'katal', 'kat',
168
+ 'gray', 'Gy',
169
+ 'becquerel', 'Bq',
170
+ 'km', 'kilometer', 'kilometers',
171
+ 'dm', 'decimeter', 'decimeters',
172
+ 'cm', 'centimeter', 'centimeters',
173
+ 'mm', 'millimeter', 'millimeters',
174
+ 'um', 'micrometer', 'micrometers', 'micron', 'microns',
175
+ 'nm', 'nanometer', 'nanometers',
176
+ 'pm', 'picometer', 'picometers',
177
+ 'ft', 'foot', 'feet',
178
+ 'inch', 'inches',
179
+ 'yd', 'yard', 'yards',
180
+ 'mi', 'mile', 'miles',
181
+ 'nmi', 'nautical_mile', 'nautical_miles',
182
+ 'ha', 'hectare',
183
+ 'l', 'L', 'liter', 'liters',
184
+ 'dl', 'dL', 'deciliter', 'deciliters',
185
+ 'cl', 'cL', 'centiliter', 'centiliters',
186
+ 'ml', 'mL', 'milliliter', 'milliliters',
187
+ 'ms', 'millisecond', 'milliseconds',
188
+ 'us', 'microsecond', 'microseconds',
189
+ 'ns', 'nanosecond', 'nanoseconds',
190
+ 'ps', 'picosecond', 'picoseconds',
191
+ 'minute', 'minutes',
192
+ 'h', 'hour', 'hours',
193
+ 'day', 'days',
194
+ 'anomalistic_year', 'anomalistic_years',
195
+ 'sidereal_year', 'sidereal_years',
196
+ 'tropical_year', 'tropical_years',
197
+ 'common_year', 'common_years',
198
+ 'julian_year', 'julian_years',
199
+ 'draconic_year', 'draconic_years',
200
+ 'gaussian_year', 'gaussian_years',
201
+ 'full_moon_cycle', 'full_moon_cycles',
202
+ 'year', 'years',
203
+ 'G', 'gravitational_constant',
204
+ 'c', 'speed_of_light',
205
+ 'elementary_charge',
206
+ 'hbar',
207
+ 'planck',
208
+ 'eV', 'electronvolt', 'electronvolts',
209
+ 'avogadro_number',
210
+ 'avogadro', 'avogadro_constant',
211
+ 'boltzmann', 'boltzmann_constant',
212
+ 'stefan', 'stefan_boltzmann_constant',
213
+ 'R', 'molar_gas_constant',
214
+ 'faraday_constant',
215
+ 'josephson_constant',
216
+ 'von_klitzing_constant',
217
+ 'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
218
+ 'me', 'electron_rest_mass',
219
+ 'gee', 'gees', 'acceleration_due_to_gravity',
220
+ 'u0', 'magnetic_constant', 'vacuum_permeability',
221
+ 'e0', 'electric_constant', 'vacuum_permittivity',
222
+ 'Z0', 'vacuum_impedance',
223
+ 'coulomb_constant', 'coulombs_constant', 'electric_force_constant',
224
+ 'atmosphere', 'atmospheres', 'atm',
225
+ 'kPa', 'kilopascal',
226
+ 'bar', 'bars',
227
+ 'pound', 'pounds',
228
+ 'psi',
229
+ 'dHg0',
230
+ 'mmHg', 'torr',
231
+ 'mmu', 'mmus', 'milli_mass_unit',
232
+ 'quart', 'quarts',
233
+ 'angstrom', 'angstroms',
234
+ 'ly', 'lightyear', 'lightyears',
235
+ 'au', 'astronomical_unit', 'astronomical_units',
236
+ 'planck_mass',
237
+ 'planck_time',
238
+ 'planck_temperature',
239
+ 'planck_length',
240
+ 'planck_charge',
241
+ 'planck_area',
242
+ 'planck_volume',
243
+ 'planck_momentum',
244
+ 'planck_energy',
245
+ 'planck_force',
246
+ 'planck_power',
247
+ 'planck_density',
248
+ 'planck_energy_density',
249
+ 'planck_intensity',
250
+ 'planck_angular_frequency',
251
+ 'planck_pressure',
252
+ 'planck_current',
253
+ 'planck_voltage',
254
+ 'planck_impedance',
255
+ 'planck_acceleration',
256
+ 'bit', 'bits',
257
+ 'byte',
258
+ 'kibibyte', 'kibibytes',
259
+ 'mebibyte', 'mebibytes',
260
+ 'gibibyte', 'gibibytes',
261
+ 'tebibyte', 'tebibytes',
262
+ 'pebibyte', 'pebibytes',
263
+ 'exbibyte', 'exbibytes',
264
+ 'curie', 'rutherford',
265
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.04 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc ADDED
Binary file (9.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.units import Dimension
2
+
3
+
4
+ angle = Dimension(name="angle") # type: Dimension
5
+
6
+ # base dimensions (MKS)
7
+ length = Dimension(name="length", symbol="L")
8
+ mass = Dimension(name="mass", symbol="M")
9
+ time = Dimension(name="time", symbol="T")
10
+
11
+ # base dimensions (MKSA not in MKS)
12
+ current = Dimension(name='current', symbol='I') # type: Dimension
13
+
14
+ # other base dimensions:
15
+ temperature = Dimension("temperature", "T") # type: Dimension
16
+ amount_of_substance = Dimension("amount_of_substance") # type: Dimension
17
+ luminous_intensity = Dimension("luminous_intensity") # type: Dimension
18
+
19
+ # derived dimensions (MKS)
20
+ velocity = Dimension(name="velocity")
21
+ acceleration = Dimension(name="acceleration")
22
+ momentum = Dimension(name="momentum")
23
+ force = Dimension(name="force", symbol="F")
24
+ energy = Dimension(name="energy", symbol="E")
25
+ power = Dimension(name="power")
26
+ pressure = Dimension(name="pressure")
27
+ frequency = Dimension(name="frequency", symbol="f")
28
+ action = Dimension(name="action", symbol="A")
29
+ area = Dimension("area")
30
+ volume = Dimension("volume")
31
+
32
+ # derived dimensions (MKSA not in MKS)
33
+ voltage = Dimension(name='voltage', symbol='U') # type: Dimension
34
+ impedance = Dimension(name='impedance', symbol='Z') # type: Dimension
35
+ conductance = Dimension(name='conductance', symbol='G') # type: Dimension
36
+ capacitance = Dimension(name='capacitance') # type: Dimension
37
+ inductance = Dimension(name='inductance') # type: Dimension
38
+ charge = Dimension(name='charge', symbol='Q') # type: Dimension
39
+ magnetic_density = Dimension(name='magnetic_density', symbol='B') # type: Dimension
40
+ magnetic_flux = Dimension(name='magnetic_flux') # type: Dimension
41
+
42
+ # Dimensions in information theory:
43
+ information = Dimension(name='information') # type: Dimension
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.units.definitions.dimension_definitions import current, temperature, amount_of_substance, \
2
+ luminous_intensity, angle, charge, voltage, impedance, conductance, capacitance, inductance, magnetic_density, \
3
+ magnetic_flux, information
4
+
5
+ from sympy.core.numbers import (Rational, pi)
6
+ from sympy.core.singleton import S as S_singleton
7
+ from sympy.physics.units.prefixes import kilo, mega, milli, micro, deci, centi, nano, pico, kibi, mebi, gibi, tebi, pebi, exbi
8
+ from sympy.physics.units.quantities import PhysicalConstant, Quantity
9
+
10
+ One = S_singleton.One
11
+
12
+ #### UNITS ####
13
+
14
+ # Dimensionless:
15
+ percent = percents = Quantity("percent", latex_repr=r"\%")
16
+ percent.set_global_relative_scale_factor(Rational(1, 100), One)
17
+
18
+ permille = Quantity("permille")
19
+ permille.set_global_relative_scale_factor(Rational(1, 1000), One)
20
+
21
+
22
+ # Angular units (dimensionless)
23
+ rad = radian = radians = Quantity("radian", abbrev="rad")
24
+ radian.set_global_dimension(angle)
25
+ deg = degree = degrees = Quantity("degree", abbrev="deg", latex_repr=r"^\circ")
26
+ degree.set_global_relative_scale_factor(pi/180, radian)
27
+ sr = steradian = steradians = Quantity("steradian", abbrev="sr")
28
+ mil = angular_mil = angular_mils = Quantity("angular_mil", abbrev="mil")
29
+
30
+ # Base units:
31
+ m = meter = meters = Quantity("meter", abbrev="m")
32
+
33
+ # gram; used to define its prefixed units
34
+ g = gram = grams = Quantity("gram", abbrev="g")
35
+
36
+ # NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but
37
+ # nonetheless we are trying to be compatible with the `kilo` prefix. In a
38
+ # similar manner, people using CGS or gaussian units could argue that the
39
+ # `centimeter` rather than `meter` is the fundamental unit for length, but the
40
+ # scale factor of `centimeter` will be kept as 1/100 to be compatible with the
41
+ # `centi` prefix. The current state of the code assumes SI unit dimensions, in
42
+ # the future this module will be modified in order to be unit system-neutral
43
+ # (that is, support all kinds of unit systems).
44
+ kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg")
45
+ kg.set_global_relative_scale_factor(kilo, gram)
46
+
47
+ s = second = seconds = Quantity("second", abbrev="s")
48
+ A = ampere = amperes = Quantity("ampere", abbrev='A')
49
+ ampere.set_global_dimension(current)
50
+ K = kelvin = kelvins = Quantity("kelvin", abbrev='K')
51
+ kelvin.set_global_dimension(temperature)
52
+ mol = mole = moles = Quantity("mole", abbrev="mol")
53
+ mole.set_global_dimension(amount_of_substance)
54
+ cd = candela = candelas = Quantity("candela", abbrev="cd")
55
+ candela.set_global_dimension(luminous_intensity)
56
+
57
+ # derived units
58
+ newton = newtons = N = Quantity("newton", abbrev="N")
59
+ joule = joules = J = Quantity("joule", abbrev="J")
60
+ watt = watts = W = Quantity("watt", abbrev="W")
61
+ pascal = pascals = Pa = pa = Quantity("pascal", abbrev="Pa")
62
+ hertz = hz = Hz = Quantity("hertz", abbrev="Hz")
63
+
64
+ # CGS derived units:
65
+ dyne = Quantity("dyne")
66
+ dyne.set_global_relative_scale_factor(One/10**5, newton)
67
+ erg = Quantity("erg")
68
+ erg.set_global_relative_scale_factor(One/10**7, joule)
69
+
70
+ # MKSA extension to MKS: derived units
71
+ coulomb = coulombs = C = Quantity("coulomb", abbrev='C')
72
+ coulomb.set_global_dimension(charge)
73
+ volt = volts = v = V = Quantity("volt", abbrev='V')
74
+ volt.set_global_dimension(voltage)
75
+ ohm = ohms = Quantity("ohm", abbrev='ohm', latex_repr=r"\Omega")
76
+ ohm.set_global_dimension(impedance)
77
+ siemens = S = mho = mhos = Quantity("siemens", abbrev='S')
78
+ siemens.set_global_dimension(conductance)
79
+ farad = farads = F = Quantity("farad", abbrev='F')
80
+ farad.set_global_dimension(capacitance)
81
+ henry = henrys = H = Quantity("henry", abbrev='H')
82
+ henry.set_global_dimension(inductance)
83
+ tesla = teslas = T = Quantity("tesla", abbrev='T')
84
+ tesla.set_global_dimension(magnetic_density)
85
+ weber = webers = Wb = wb = Quantity("weber", abbrev='Wb')
86
+ weber.set_global_dimension(magnetic_flux)
87
+
88
+ # CGS units for electromagnetic quantities:
89
+ statampere = Quantity("statampere")
90
+ statcoulomb = statC = franklin = Quantity("statcoulomb", abbrev="statC")
91
+ statvolt = Quantity("statvolt")
92
+ gauss = Quantity("gauss")
93
+ maxwell = Quantity("maxwell")
94
+ debye = Quantity("debye")
95
+ oersted = Quantity("oersted")
96
+
97
+ # Other derived units:
98
+ optical_power = dioptre = diopter = D = Quantity("dioptre")
99
+ lux = lx = Quantity("lux", abbrev="lx")
100
+
101
+ # katal is the SI unit of catalytic activity
102
+ katal = kat = Quantity("katal", abbrev="kat")
103
+
104
+ # gray is the SI unit of absorbed dose
105
+ gray = Gy = Quantity("gray")
106
+
107
+ # becquerel is the SI unit of radioactivity
108
+ becquerel = Bq = Quantity("becquerel", abbrev="Bq")
109
+
110
+
111
+ # Common mass units
112
+
113
+ mg = milligram = milligrams = Quantity("milligram", abbrev="mg")
114
+ mg.set_global_relative_scale_factor(milli, gram)
115
+
116
+ ug = microgram = micrograms = Quantity("microgram", abbrev="ug", latex_repr=r"\mu\text{g}")
117
+ ug.set_global_relative_scale_factor(micro, gram)
118
+
119
+ # Atomic mass constant
120
+ Da = dalton = amu = amus = atomic_mass_unit = atomic_mass_constant = PhysicalConstant("atomic_mass_constant")
121
+
122
+ t = metric_ton = tonne = Quantity("tonne", abbrev="t")
123
+ tonne.set_global_relative_scale_factor(mega, gram)
124
+
125
+ # Electron rest mass
126
+ me = electron_rest_mass = Quantity("electron_rest_mass", abbrev="me")
127
+
128
+
129
+ # Common length units
130
+
131
+ km = kilometer = kilometers = Quantity("kilometer", abbrev="km")
132
+ km.set_global_relative_scale_factor(kilo, meter)
133
+
134
+ dm = decimeter = decimeters = Quantity("decimeter", abbrev="dm")
135
+ dm.set_global_relative_scale_factor(deci, meter)
136
+
137
+ cm = centimeter = centimeters = Quantity("centimeter", abbrev="cm")
138
+ cm.set_global_relative_scale_factor(centi, meter)
139
+
140
+ mm = millimeter = millimeters = Quantity("millimeter", abbrev="mm")
141
+ mm.set_global_relative_scale_factor(milli, meter)
142
+
143
+ um = micrometer = micrometers = micron = microns = \
144
+ Quantity("micrometer", abbrev="um", latex_repr=r'\mu\text{m}')
145
+ um.set_global_relative_scale_factor(micro, meter)
146
+
147
+ nm = nanometer = nanometers = Quantity("nanometer", abbrev="nm")
148
+ nm.set_global_relative_scale_factor(nano, meter)
149
+
150
+ pm = picometer = picometers = Quantity("picometer", abbrev="pm")
151
+ pm.set_global_relative_scale_factor(pico, meter)
152
+
153
+ ft = foot = feet = Quantity("foot", abbrev="ft")
154
+ ft.set_global_relative_scale_factor(Rational(3048, 10000), meter)
155
+
156
+ inch = inches = Quantity("inch")
157
+ inch.set_global_relative_scale_factor(Rational(1, 12), foot)
158
+
159
+ yd = yard = yards = Quantity("yard", abbrev="yd")
160
+ yd.set_global_relative_scale_factor(3, feet)
161
+
162
+ mi = mile = miles = Quantity("mile")
163
+ mi.set_global_relative_scale_factor(5280, feet)
164
+
165
+ nmi = nautical_mile = nautical_miles = Quantity("nautical_mile")
166
+ nmi.set_global_relative_scale_factor(6076, feet)
167
+
168
+ angstrom = angstroms = Quantity("angstrom", latex_repr=r'\r{A}')
169
+ angstrom.set_global_relative_scale_factor(Rational(1, 10**10), meter)
170
+
171
+
172
+ # Common volume and area units
173
+
174
+ ha = hectare = Quantity("hectare", abbrev="ha")
175
+
176
+ l = L = liter = liters = Quantity("liter")
177
+
178
+ dl = dL = deciliter = deciliters = Quantity("deciliter")
179
+ dl.set_global_relative_scale_factor(Rational(1, 10), liter)
180
+
181
+ cl = cL = centiliter = centiliters = Quantity("centiliter")
182
+ cl.set_global_relative_scale_factor(Rational(1, 100), liter)
183
+
184
+ ml = mL = milliliter = milliliters = Quantity("milliliter")
185
+ ml.set_global_relative_scale_factor(Rational(1, 1000), liter)
186
+
187
+
188
+ # Common time units
189
+
190
+ ms = millisecond = milliseconds = Quantity("millisecond", abbrev="ms")
191
+ millisecond.set_global_relative_scale_factor(milli, second)
192
+
193
+ us = microsecond = microseconds = Quantity("microsecond", abbrev="us", latex_repr=r'\mu\text{s}')
194
+ microsecond.set_global_relative_scale_factor(micro, second)
195
+
196
+ ns = nanosecond = nanoseconds = Quantity("nanosecond", abbrev="ns")
197
+ nanosecond.set_global_relative_scale_factor(nano, second)
198
+
199
+ ps = picosecond = picoseconds = Quantity("picosecond", abbrev="ps")
200
+ picosecond.set_global_relative_scale_factor(pico, second)
201
+
202
+ minute = minutes = Quantity("minute")
203
+ minute.set_global_relative_scale_factor(60, second)
204
+
205
+ h = hour = hours = Quantity("hour")
206
+ hour.set_global_relative_scale_factor(60, minute)
207
+
208
+ day = days = Quantity("day")
209
+ day.set_global_relative_scale_factor(24, hour)
210
+
211
+ anomalistic_year = anomalistic_years = Quantity("anomalistic_year")
212
+ anomalistic_year.set_global_relative_scale_factor(365.259636, day)
213
+
214
+ sidereal_year = sidereal_years = Quantity("sidereal_year")
215
+ sidereal_year.set_global_relative_scale_factor(31558149.540, seconds)
216
+
217
+ tropical_year = tropical_years = Quantity("tropical_year")
218
+ tropical_year.set_global_relative_scale_factor(365.24219, day)
219
+
220
+ common_year = common_years = Quantity("common_year")
221
+ common_year.set_global_relative_scale_factor(365, day)
222
+
223
+ julian_year = julian_years = Quantity("julian_year")
224
+ julian_year.set_global_relative_scale_factor((365 + One/4), day)
225
+
226
+ draconic_year = draconic_years = Quantity("draconic_year")
227
+ draconic_year.set_global_relative_scale_factor(346.62, day)
228
+
229
+ gaussian_year = gaussian_years = Quantity("gaussian_year")
230
+ gaussian_year.set_global_relative_scale_factor(365.2568983, day)
231
+
232
+ full_moon_cycle = full_moon_cycles = Quantity("full_moon_cycle")
233
+ full_moon_cycle.set_global_relative_scale_factor(411.78443029, day)
234
+
235
+ year = years = tropical_year
236
+
237
+
238
+ #### CONSTANTS ####
239
+
240
+ # Newton constant
241
+ G = gravitational_constant = PhysicalConstant("gravitational_constant", abbrev="G")
242
+
243
+ # speed of light
244
+ c = speed_of_light = PhysicalConstant("speed_of_light", abbrev="c")
245
+
246
+ # elementary charge
247
+ elementary_charge = PhysicalConstant("elementary_charge", abbrev="e")
248
+
249
+ # Planck constant
250
+ planck = PhysicalConstant("planck", abbrev="h")
251
+
252
+ # Reduced Planck constant
253
+ hbar = PhysicalConstant("hbar", abbrev="hbar")
254
+
255
+ # Electronvolt
256
+ eV = electronvolt = electronvolts = PhysicalConstant("electronvolt", abbrev="eV")
257
+
258
+ # Avogadro number
259
+ avogadro_number = PhysicalConstant("avogadro_number")
260
+
261
+ # Avogadro constant
262
+ avogadro = avogadro_constant = PhysicalConstant("avogadro_constant")
263
+
264
+ # Boltzmann constant
265
+ boltzmann = boltzmann_constant = PhysicalConstant("boltzmann_constant")
266
+
267
+ # Stefan-Boltzmann constant
268
+ stefan = stefan_boltzmann_constant = PhysicalConstant("stefan_boltzmann_constant")
269
+
270
+ # Molar gas constant
271
+ R = molar_gas_constant = PhysicalConstant("molar_gas_constant", abbrev="R")
272
+
273
+ # Faraday constant
274
+ faraday_constant = PhysicalConstant("faraday_constant")
275
+
276
+ # Josephson constant
277
+ josephson_constant = PhysicalConstant("josephson_constant", abbrev="K_j")
278
+
279
+ # Von Klitzing constant
280
+ von_klitzing_constant = PhysicalConstant("von_klitzing_constant", abbrev="R_k")
281
+
282
+ # Acceleration due to gravity (on the Earth surface)
283
+ gee = gees = acceleration_due_to_gravity = PhysicalConstant("acceleration_due_to_gravity", abbrev="g")
284
+
285
+ # magnetic constant:
286
+ u0 = magnetic_constant = vacuum_permeability = PhysicalConstant("magnetic_constant")
287
+
288
+ # electric constat:
289
+ e0 = electric_constant = vacuum_permittivity = PhysicalConstant("vacuum_permittivity")
290
+
291
+ # vacuum impedance:
292
+ Z0 = vacuum_impedance = PhysicalConstant("vacuum_impedance", abbrev='Z_0', latex_repr=r'Z_{0}')
293
+
294
+ # Coulomb's constant:
295
+ coulomb_constant = coulombs_constant = electric_force_constant = \
296
+ PhysicalConstant("coulomb_constant", abbrev="k_e")
297
+
298
+
299
+ atmosphere = atmospheres = atm = Quantity("atmosphere", abbrev="atm")
300
+
301
+ kPa = kilopascal = Quantity("kilopascal", abbrev="kPa")
302
+ kilopascal.set_global_relative_scale_factor(kilo, Pa)
303
+
304
+ bar = bars = Quantity("bar", abbrev="bar")
305
+
306
+ pound = pounds = Quantity("pound") # exact
307
+
308
+ psi = Quantity("psi")
309
+
310
+ dHg0 = 13.5951 # approx value at 0 C
311
+ mmHg = torr = Quantity("mmHg")
312
+
313
+ atmosphere.set_global_relative_scale_factor(101325, pascal)
314
+ bar.set_global_relative_scale_factor(100, kPa)
315
+ pound.set_global_relative_scale_factor(Rational(45359237, 100000000), kg)
316
+
317
+ mmu = mmus = milli_mass_unit = Quantity("milli_mass_unit")
318
+
319
+ quart = quarts = Quantity("quart")
320
+
321
+
322
+ # Other convenient units and magnitudes
323
+
324
+ ly = lightyear = lightyears = Quantity("lightyear", abbrev="ly")
325
+
326
+ au = astronomical_unit = astronomical_units = Quantity("astronomical_unit", abbrev="AU")
327
+
328
+
329
+ # Fundamental Planck units:
330
+ planck_mass = Quantity("planck_mass", abbrev="m_P", latex_repr=r'm_\text{P}')
331
+
332
+ planck_time = Quantity("planck_time", abbrev="t_P", latex_repr=r't_\text{P}')
333
+
334
+ planck_temperature = Quantity("planck_temperature", abbrev="T_P",
335
+ latex_repr=r'T_\text{P}')
336
+
337
+ planck_length = Quantity("planck_length", abbrev="l_P", latex_repr=r'l_\text{P}')
338
+
339
+ planck_charge = Quantity("planck_charge", abbrev="q_P", latex_repr=r'q_\text{P}')
340
+
341
+
342
+ # Derived Planck units:
343
+ planck_area = Quantity("planck_area")
344
+
345
+ planck_volume = Quantity("planck_volume")
346
+
347
+ planck_momentum = Quantity("planck_momentum")
348
+
349
+ planck_energy = Quantity("planck_energy", abbrev="E_P", latex_repr=r'E_\text{P}')
350
+
351
+ planck_force = Quantity("planck_force", abbrev="F_P", latex_repr=r'F_\text{P}')
352
+
353
+ planck_power = Quantity("planck_power", abbrev="P_P", latex_repr=r'P_\text{P}')
354
+
355
+ planck_density = Quantity("planck_density", abbrev="rho_P", latex_repr=r'\rho_\text{P}')
356
+
357
+ planck_energy_density = Quantity("planck_energy_density", abbrev="rho^E_P")
358
+
359
+ planck_intensity = Quantity("planck_intensity", abbrev="I_P", latex_repr=r'I_\text{P}')
360
+
361
+ planck_angular_frequency = Quantity("planck_angular_frequency", abbrev="omega_P",
362
+ latex_repr=r'\omega_\text{P}')
363
+
364
+ planck_pressure = Quantity("planck_pressure", abbrev="p_P", latex_repr=r'p_\text{P}')
365
+
366
+ planck_current = Quantity("planck_current", abbrev="I_P", latex_repr=r'I_\text{P}')
367
+
368
+ planck_voltage = Quantity("planck_voltage", abbrev="V_P", latex_repr=r'V_\text{P}')
369
+
370
+ planck_impedance = Quantity("planck_impedance", abbrev="Z_P", latex_repr=r'Z_\text{P}')
371
+
372
+ planck_acceleration = Quantity("planck_acceleration", abbrev="a_P",
373
+ latex_repr=r'a_\text{P}')
374
+
375
+
376
+ # Information theory units:
377
+ bit = bits = Quantity("bit")
378
+ bit.set_global_dimension(information)
379
+
380
+ byte = bytes = Quantity("byte")
381
+
382
+ kibibyte = kibibytes = Quantity("kibibyte")
383
+ mebibyte = mebibytes = Quantity("mebibyte")
384
+ gibibyte = gibibytes = Quantity("gibibyte")
385
+ tebibyte = tebibytes = Quantity("tebibyte")
386
+ pebibyte = pebibytes = Quantity("pebibyte")
387
+ exbibyte = exbibytes = Quantity("exbibyte")
388
+
389
+ byte.set_global_relative_scale_factor(8, bit)
390
+ kibibyte.set_global_relative_scale_factor(kibi, byte)
391
+ mebibyte.set_global_relative_scale_factor(mebi, byte)
392
+ gibibyte.set_global_relative_scale_factor(gibi, byte)
393
+ tebibyte.set_global_relative_scale_factor(tebi, byte)
394
+ pebibyte.set_global_relative_scale_factor(pebi, byte)
395
+ exbibyte.set_global_relative_scale_factor(exbi, byte)
396
+
397
+ # Older units for radioactivity
398
+ curie = Ci = Quantity("curie", abbrev="Ci")
399
+
400
+ rutherford = Rd = Quantity("rutherford", abbrev="Rd")
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/dimensions.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Definition of physical dimensions.
3
+
4
+ Unit systems will be constructed on top of these dimensions.
5
+
6
+ Most of the examples in the doc use MKS system and are presented from the
7
+ computer point of view: from a human point, adding length to time is not legal
8
+ in MKS but it is in natural system; for a computer in natural system there is
9
+ no time dimension (but a velocity dimension instead) - in the basis - so the
10
+ question of adding time to length has no meaning.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ from functools import reduce
17
+
18
+ from sympy.core.basic import Basic
19
+ from sympy.core.containers import (Dict, Tuple)
20
+ from sympy.core.singleton import S
21
+ from sympy.core.sorting import default_sort_key
22
+ from sympy.core.symbol import Symbol
23
+ from sympy.core.sympify import sympify
24
+ from sympy.matrices.dense import Matrix
25
+ from sympy.functions.elementary.trigonometric import TrigonometricFunction
26
+ from sympy.core.expr import Expr
27
+ from sympy.core.power import Pow
28
+
29
+
30
+ class _QuantityMapper:
31
+
32
+ _quantity_scale_factors_global: dict[Expr, Expr] = {}
33
+ _quantity_dimensional_equivalence_map_global: dict[Expr, Expr] = {}
34
+ _quantity_dimension_global: dict[Expr, Expr] = {}
35
+
36
+ def __init__(self, *args, **kwargs):
37
+ self._quantity_dimension_map = {}
38
+ self._quantity_scale_factors = {}
39
+
40
+ def set_quantity_dimension(self, quantity, dimension):
41
+ """
42
+ Set the dimension for the quantity in a unit system.
43
+
44
+ If this relation is valid in every unit system, use
45
+ ``quantity.set_global_dimension(dimension)`` instead.
46
+ """
47
+ from sympy.physics.units import Quantity
48
+ dimension = sympify(dimension)
49
+ if not isinstance(dimension, Dimension):
50
+ if dimension == 1:
51
+ dimension = Dimension(1)
52
+ else:
53
+ raise ValueError("expected dimension or 1")
54
+ elif isinstance(dimension, Quantity):
55
+ dimension = self.get_quantity_dimension(dimension)
56
+ self._quantity_dimension_map[quantity] = dimension
57
+
58
+ def set_quantity_scale_factor(self, quantity, scale_factor):
59
+ """
60
+ Set the scale factor of a quantity relative to another quantity.
61
+
62
+ It should be used only once per quantity to just one other quantity,
63
+ the algorithm will then be able to compute the scale factors to all
64
+ other quantities.
65
+
66
+ In case the scale factor is valid in every unit system, please use
67
+ ``quantity.set_global_relative_scale_factor(scale_factor)`` instead.
68
+ """
69
+ from sympy.physics.units import Quantity
70
+ from sympy.physics.units.prefixes import Prefix
71
+ scale_factor = sympify(scale_factor)
72
+ # replace all prefixes by their ratio to canonical units:
73
+ scale_factor = scale_factor.replace(
74
+ lambda x: isinstance(x, Prefix),
75
+ lambda x: x.scale_factor
76
+ )
77
+ # replace all quantities by their ratio to canonical units:
78
+ scale_factor = scale_factor.replace(
79
+ lambda x: isinstance(x, Quantity),
80
+ lambda x: self.get_quantity_scale_factor(x)
81
+ )
82
+ self._quantity_scale_factors[quantity] = scale_factor
83
+
84
+ def get_quantity_dimension(self, unit):
85
+ from sympy.physics.units import Quantity
86
+ # First look-up the local dimension map, then the global one:
87
+ if unit in self._quantity_dimension_map:
88
+ return self._quantity_dimension_map[unit]
89
+ if unit in self._quantity_dimension_global:
90
+ return self._quantity_dimension_global[unit]
91
+ if unit in self._quantity_dimensional_equivalence_map_global:
92
+ dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
93
+ if isinstance(dep_unit, Quantity):
94
+ return self.get_quantity_dimension(dep_unit)
95
+ else:
96
+ return Dimension(self.get_dimensional_expr(dep_unit))
97
+ if isinstance(unit, Quantity):
98
+ return Dimension(unit.name)
99
+ else:
100
+ return Dimension(1)
101
+
102
+ def get_quantity_scale_factor(self, unit):
103
+ if unit in self._quantity_scale_factors:
104
+ return self._quantity_scale_factors[unit]
105
+ if unit in self._quantity_scale_factors_global:
106
+ mul_factor, other_unit = self._quantity_scale_factors_global[unit]
107
+ return mul_factor*self.get_quantity_scale_factor(other_unit)
108
+ return S.One
109
+
110
+
111
+ class Dimension(Expr):
112
+ """
113
+ This class represent the dimension of a physical quantities.
114
+
115
+ The ``Dimension`` constructor takes as parameters a name and an optional
116
+ symbol.
117
+
118
+ For example, in classical mechanics we know that time is different from
119
+ temperature and dimensions make this difference (but they do not provide
120
+ any measure of these quantites.
121
+
122
+ >>> from sympy.physics.units import Dimension
123
+ >>> length = Dimension('length')
124
+ >>> length
125
+ Dimension(length)
126
+ >>> time = Dimension('time')
127
+ >>> time
128
+ Dimension(time)
129
+
130
+ Dimensions can be composed using multiplication, division and
131
+ exponentiation (by a number) to give new dimensions. Addition and
132
+ subtraction is defined only when the two objects are the same dimension.
133
+
134
+ >>> velocity = length / time
135
+ >>> velocity
136
+ Dimension(length/time)
137
+
138
+ It is possible to use a dimension system object to get the dimensionsal
139
+ dependencies of a dimension, for example the dimension system used by the
140
+ SI units convention can be used:
141
+
142
+ >>> from sympy.physics.units.systems.si import dimsys_SI
143
+ >>> dimsys_SI.get_dimensional_dependencies(velocity)
144
+ {Dimension(length, L): 1, Dimension(time, T): -1}
145
+ >>> length + length
146
+ Dimension(length)
147
+ >>> l2 = length**2
148
+ >>> l2
149
+ Dimension(length**2)
150
+ >>> dimsys_SI.get_dimensional_dependencies(l2)
151
+ {Dimension(length, L): 2}
152
+
153
+ """
154
+
155
+ _op_priority = 13.0
156
+
157
+ # XXX: This doesn't seem to be used anywhere...
158
+ _dimensional_dependencies = {} # type: ignore
159
+
160
+ is_commutative = True
161
+ is_number = False
162
+ # make sqrt(M**2) --> M
163
+ is_positive = True
164
+ is_real = True
165
+
166
+ def __new__(cls, name, symbol=None):
167
+
168
+ if isinstance(name, str):
169
+ name = Symbol(name)
170
+ else:
171
+ name = sympify(name)
172
+
173
+ if not isinstance(name, Expr):
174
+ raise TypeError("Dimension name needs to be a valid math expression")
175
+
176
+ if isinstance(symbol, str):
177
+ symbol = Symbol(symbol)
178
+ elif symbol is not None:
179
+ assert isinstance(symbol, Symbol)
180
+
181
+ obj = Expr.__new__(cls, name)
182
+
183
+ obj._name = name
184
+ obj._symbol = symbol
185
+ return obj
186
+
187
+ @property
188
+ def name(self):
189
+ return self._name
190
+
191
+ @property
192
+ def symbol(self):
193
+ return self._symbol
194
+
195
+ def __str__(self):
196
+ """
197
+ Display the string representation of the dimension.
198
+ """
199
+ if self.symbol is None:
200
+ return "Dimension(%s)" % (self.name)
201
+ else:
202
+ return "Dimension(%s, %s)" % (self.name, self.symbol)
203
+
204
+ def __repr__(self):
205
+ return self.__str__()
206
+
207
+ def __neg__(self):
208
+ return self
209
+
210
+ def __add__(self, other):
211
+ from sympy.physics.units.quantities import Quantity
212
+ other = sympify(other)
213
+ if isinstance(other, Basic):
214
+ if other.has(Quantity):
215
+ raise TypeError("cannot sum dimension and quantity")
216
+ if isinstance(other, Dimension) and self == other:
217
+ return self
218
+ return super().__add__(other)
219
+ return self
220
+
221
+ def __radd__(self, other):
222
+ return self.__add__(other)
223
+
224
+ def __sub__(self, other):
225
+ # there is no notion of ordering (or magnitude) among dimension,
226
+ # subtraction is equivalent to addition when the operation is legal
227
+ return self + other
228
+
229
+ def __rsub__(self, other):
230
+ # there is no notion of ordering (or magnitude) among dimension,
231
+ # subtraction is equivalent to addition when the operation is legal
232
+ return self + other
233
+
234
+ def __pow__(self, other):
235
+ return self._eval_power(other)
236
+
237
+ def _eval_power(self, other):
238
+ other = sympify(other)
239
+ return Dimension(self.name**other)
240
+
241
+ def __mul__(self, other):
242
+ from sympy.physics.units.quantities import Quantity
243
+ if isinstance(other, Basic):
244
+ if other.has(Quantity):
245
+ raise TypeError("cannot sum dimension and quantity")
246
+ if isinstance(other, Dimension):
247
+ return Dimension(self.name*other.name)
248
+ if not other.free_symbols: # other.is_number cannot be used
249
+ return self
250
+ return super().__mul__(other)
251
+ return self
252
+
253
+ def __rmul__(self, other):
254
+ return self.__mul__(other)
255
+
256
+ def __truediv__(self, other):
257
+ return self*Pow(other, -1)
258
+
259
+ def __rtruediv__(self, other):
260
+ return other * pow(self, -1)
261
+
262
+ @classmethod
263
+ def _from_dimensional_dependencies(cls, dependencies):
264
+ return reduce(lambda x, y: x * y, (
265
+ d**e for d, e in dependencies.items()
266
+ ), 1)
267
+
268
+ def has_integer_powers(self, dim_sys):
269
+ """
270
+ Check if the dimension object has only integer powers.
271
+
272
+ All the dimension powers should be integers, but rational powers may
273
+ appear in intermediate steps. This method may be used to check that the
274
+ final result is well-defined.
275
+ """
276
+
277
+ return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
278
+
279
+
280
+ # Create dimensions according to the base units in MKSA.
281
+ # For other unit systems, they can be derived by transforming the base
282
+ # dimensional dependency dictionary.
283
+
284
+
285
+ class DimensionSystem(Basic, _QuantityMapper):
286
+ r"""
287
+ DimensionSystem represents a coherent set of dimensions.
288
+
289
+ The constructor takes three parameters:
290
+
291
+ - base dimensions;
292
+ - derived dimensions: these are defined in terms of the base dimensions
293
+ (for example velocity is defined from the division of length by time);
294
+ - dependency of dimensions: how the derived dimensions depend
295
+ on the base dimensions.
296
+
297
+ Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
298
+ may be omitted.
299
+ """
300
+
301
+ def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}):
302
+ dimensional_dependencies = dict(dimensional_dependencies)
303
+
304
+ def parse_dim(dim):
305
+ if isinstance(dim, str):
306
+ dim = Dimension(Symbol(dim))
307
+ elif isinstance(dim, Dimension):
308
+ pass
309
+ elif isinstance(dim, Symbol):
310
+ dim = Dimension(dim)
311
+ else:
312
+ raise TypeError("%s wrong type" % dim)
313
+ return dim
314
+
315
+ base_dims = [parse_dim(i) for i in base_dims]
316
+ derived_dims = [parse_dim(i) for i in derived_dims]
317
+
318
+ for dim in base_dims:
319
+ if (dim in dimensional_dependencies
320
+ and (len(dimensional_dependencies[dim]) != 1 or
321
+ dimensional_dependencies[dim].get(dim, None) != 1)):
322
+ raise IndexError("Repeated value in base dimensions")
323
+ dimensional_dependencies[dim] = Dict({dim: 1})
324
+
325
+ def parse_dim_name(dim):
326
+ if isinstance(dim, Dimension):
327
+ return dim
328
+ elif isinstance(dim, str):
329
+ return Dimension(Symbol(dim))
330
+ elif isinstance(dim, Symbol):
331
+ return Dimension(dim)
332
+ else:
333
+ raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
334
+
335
+ for dim in dimensional_dependencies.keys():
336
+ dim = parse_dim(dim)
337
+ if (dim not in derived_dims) and (dim not in base_dims):
338
+ derived_dims.append(dim)
339
+
340
+ def parse_dict(d):
341
+ return Dict({parse_dim_name(i): j for i, j in d.items()})
342
+
343
+ # Make sure everything is a SymPy type:
344
+ dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
345
+ dimensional_dependencies.items()}
346
+
347
+ for dim in derived_dims:
348
+ if dim in base_dims:
349
+ raise ValueError("Dimension %s both in base and derived" % dim)
350
+ if dim not in dimensional_dependencies:
351
+ # TODO: should this raise a warning?
352
+ dimensional_dependencies[dim] = Dict({dim: 1})
353
+
354
+ base_dims.sort(key=default_sort_key)
355
+ derived_dims.sort(key=default_sort_key)
356
+
357
+ base_dims = Tuple(*base_dims)
358
+ derived_dims = Tuple(*derived_dims)
359
+ dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
360
+ obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
361
+ return obj
362
+
363
+ @property
364
+ def base_dims(self):
365
+ return self.args[0]
366
+
367
+ @property
368
+ def derived_dims(self):
369
+ return self.args[1]
370
+
371
+ @property
372
+ def dimensional_dependencies(self):
373
+ return self.args[2]
374
+
375
+ def _get_dimensional_dependencies_for_name(self, dimension):
376
+ if isinstance(dimension, str):
377
+ dimension = Dimension(Symbol(dimension))
378
+ elif not isinstance(dimension, Dimension):
379
+ dimension = Dimension(dimension)
380
+
381
+ if dimension.name.is_Symbol:
382
+ # Dimensions not included in the dependencies are considered
383
+ # as base dimensions:
384
+ return dict(self.dimensional_dependencies.get(dimension, {dimension: 1}))
385
+
386
+ if dimension.name.is_number or dimension.name.is_NumberSymbol:
387
+ return {}
388
+
389
+ get_for_name = self._get_dimensional_dependencies_for_name
390
+
391
+ if dimension.name.is_Mul:
392
+ ret = collections.defaultdict(int)
393
+ dicts = [get_for_name(i) for i in dimension.name.args]
394
+ for d in dicts:
395
+ for k, v in d.items():
396
+ ret[k] += v
397
+ return {k: v for (k, v) in ret.items() if v != 0}
398
+
399
+ if dimension.name.is_Add:
400
+ dicts = [get_for_name(i) for i in dimension.name.args]
401
+ if all(d == dicts[0] for d in dicts[1:]):
402
+ return dicts[0]
403
+ raise TypeError("Only equivalent dimensions can be added or subtracted.")
404
+
405
+ if dimension.name.is_Pow:
406
+ dim_base = get_for_name(dimension.name.base)
407
+ dim_exp = get_for_name(dimension.name.exp)
408
+ if dim_exp == {} or dimension.name.exp.is_Symbol:
409
+ return {k: v * dimension.name.exp for (k, v) in dim_base.items()}
410
+ else:
411
+ raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
412
+
413
+ if dimension.name.is_Function:
414
+ args = (Dimension._from_dimensional_dependencies(
415
+ get_for_name(arg)) for arg in dimension.name.args)
416
+ result = dimension.name.func(*args)
417
+
418
+ dicts = [get_for_name(i) for i in dimension.name.args]
419
+
420
+ if isinstance(result, Dimension):
421
+ return self.get_dimensional_dependencies(result)
422
+ elif result.func == dimension.name.func:
423
+ if isinstance(dimension.name, TrigonometricFunction):
424
+ if dicts[0] in ({}, {Dimension('angle'): 1}):
425
+ return {}
426
+ else:
427
+ raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(dimension.func))
428
+ else:
429
+ if all(item == {} for item in dicts):
430
+ return {}
431
+ else:
432
+ raise TypeError("The input arguments for the function {} must be dimensionless.".format(dimension.func))
433
+ else:
434
+ return get_for_name(result)
435
+
436
+ raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(dimension.name)))
437
+
438
+ def get_dimensional_dependencies(self, name, mark_dimensionless=False):
439
+ dimdep = self._get_dimensional_dependencies_for_name(name)
440
+ if mark_dimensionless and dimdep == {}:
441
+ return {Dimension(1): 1}
442
+ return {k: v for k, v in dimdep.items()}
443
+
444
+ def equivalent_dims(self, dim1, dim2):
445
+ deps1 = self.get_dimensional_dependencies(dim1)
446
+ deps2 = self.get_dimensional_dependencies(dim2)
447
+ return deps1 == deps2
448
+
449
+ def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None):
450
+ deps = dict(self.dimensional_dependencies)
451
+ if new_dim_deps:
452
+ deps.update(new_dim_deps)
453
+
454
+ new_dim_sys = DimensionSystem(
455
+ tuple(self.base_dims) + tuple(new_base_dims),
456
+ tuple(self.derived_dims) + tuple(new_derived_dims),
457
+ deps
458
+ )
459
+ new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
460
+ new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
461
+ return new_dim_sys
462
+
463
+ def is_dimensionless(self, dimension):
464
+ """
465
+ Check if the dimension object really has a dimension.
466
+
467
+ A dimension should have at least one component with non-zero power.
468
+ """
469
+ if dimension.name == 1:
470
+ return True
471
+ return self.get_dimensional_dependencies(dimension) == {}
472
+
473
+ @property
474
+ def list_can_dims(self):
475
+ """
476
+ Useless method, kept for compatibility with previous versions.
477
+
478
+ DO NOT USE.
479
+
480
+ List all canonical dimension names.
481
+ """
482
+ dimset = set()
483
+ for i in self.base_dims:
484
+ dimset.update(set(self.get_dimensional_dependencies(i).keys()))
485
+ return tuple(sorted(dimset, key=str))
486
+
487
+ @property
488
+ def inv_can_transf_matrix(self):
489
+ """
490
+ Useless method, kept for compatibility with previous versions.
491
+
492
+ DO NOT USE.
493
+
494
+ Compute the inverse transformation matrix from the base to the
495
+ canonical dimension basis.
496
+
497
+ It corresponds to the matrix where columns are the vector of base
498
+ dimensions in canonical basis.
499
+
500
+ This matrix will almost never be used because dimensions are always
501
+ defined with respect to the canonical basis, so no work has to be done
502
+ to get them in this basis. Nonetheless if this matrix is not square
503
+ (or not invertible) it means that we have chosen a bad basis.
504
+ """
505
+ matrix = reduce(lambda x, y: x.row_join(y),
506
+ [self.dim_can_vector(d) for d in self.base_dims])
507
+ return matrix
508
+
509
+ @property
510
+ def can_transf_matrix(self):
511
+ """
512
+ Useless method, kept for compatibility with previous versions.
513
+
514
+ DO NOT USE.
515
+
516
+ Return the canonical transformation matrix from the canonical to the
517
+ base dimension basis.
518
+
519
+ It is the inverse of the matrix computed with inv_can_transf_matrix().
520
+ """
521
+
522
+ #TODO: the inversion will fail if the system is inconsistent, for
523
+ # example if the matrix is not a square
524
+ return reduce(lambda x, y: x.row_join(y),
525
+ [self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
526
+ ).inv()
527
+
528
+ def dim_can_vector(self, dim):
529
+ """
530
+ Useless method, kept for compatibility with previous versions.
531
+
532
+ DO NOT USE.
533
+
534
+ Dimensional representation in terms of the canonical base dimensions.
535
+ """
536
+
537
+ vec = []
538
+ for d in self.list_can_dims:
539
+ vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
540
+ return Matrix(vec)
541
+
542
+ def dim_vector(self, dim):
543
+ """
544
+ Useless method, kept for compatibility with previous versions.
545
+
546
+ DO NOT USE.
547
+
548
+
549
+ Vector representation in terms of the base dimensions.
550
+ """
551
+ return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
552
+
553
+ def print_dim_base(self, dim):
554
+ """
555
+ Give the string expression of a dimension in term of the basis symbols.
556
+ """
557
+ dims = self.dim_vector(dim)
558
+ symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
559
+ res = S.One
560
+ for (s, p) in zip(symbols, dims):
561
+ res *= s**p
562
+ return res
563
+
564
+ @property
565
+ def dim(self):
566
+ """
567
+ Useless method, kept for compatibility with previous versions.
568
+
569
+ DO NOT USE.
570
+
571
+ Give the dimension of the system.
572
+
573
+ That is return the number of dimensions forming the basis.
574
+ """
575
+ return len(self.base_dims)
576
+
577
+ @property
578
+ def is_consistent(self):
579
+ """
580
+ Useless method, kept for compatibility with previous versions.
581
+
582
+ DO NOT USE.
583
+
584
+ Check if the system is well defined.
585
+ """
586
+
587
+ # not enough or too many base dimensions compared to independent
588
+ # dimensions
589
+ # in vector language: the set of vectors do not form a basis
590
+ return self.inv_can_transf_matrix.is_square
env-llmeval/lib/python3.10/site-packages/sympy/physics/units/prefixes.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module defining unit prefixe class and some constants.
3
+
4
+ Constant dict for SI and binary prefixes are defined as PREFIXES and
5
+ BIN_PREFIXES.
6
+ """
7
+ from sympy.core.expr import Expr
8
+ from sympy.core.sympify import sympify
9
+
10
+
11
+ class Prefix(Expr):
12
+ """
13
+ This class represent prefixes, with their name, symbol and factor.
14
+
15
+ Prefixes are used to create derived units from a given unit. They should
16
+ always be encapsulated into units.
17
+
18
+ The factor is constructed from a base (default is 10) to some power, and
19
+ it gives the total multiple or fraction. For example the kilometer km
20
+ is constructed from the meter (factor 1) and the kilo (10 to the power 3,
21
+ i.e. 1000). The base can be changed to allow e.g. binary prefixes.
22
+
23
+ A prefix multiplied by something will always return the product of this
24
+ other object times the factor, except if the other object:
25
+
26
+ - is a prefix and they can be combined into a new prefix;
27
+ - defines multiplication with prefixes (which is the case for the Unit
28
+ class).
29
+ """
30
+ _op_priority = 13.0
31
+ is_commutative = True
32
+
33
+ def __new__(cls, name, abbrev, exponent, base=sympify(10), latex_repr=None):
34
+
35
+ name = sympify(name)
36
+ abbrev = sympify(abbrev)
37
+ exponent = sympify(exponent)
38
+ base = sympify(base)
39
+
40
+ obj = Expr.__new__(cls, name, abbrev, exponent, base)
41
+ obj._name = name
42
+ obj._abbrev = abbrev
43
+ obj._scale_factor = base**exponent
44
+ obj._exponent = exponent
45
+ obj._base = base
46
+ obj._latex_repr = latex_repr
47
+ return obj
48
+
49
+ @property
50
+ def name(self):
51
+ return self._name
52
+
53
+ @property
54
+ def abbrev(self):
55
+ return self._abbrev
56
+
57
+ @property
58
+ def scale_factor(self):
59
+ return self._scale_factor
60
+
61
+ def _latex(self, printer):
62
+ if self._latex_repr is None:
63
+ return r'\text{%s}' % self._abbrev
64
+ return self._latex_repr
65
+
66
+ @property
67
+ def base(self):
68
+ return self._base
69
+
70
+ def __str__(self):
71
+ return str(self._abbrev)
72
+
73
+ def __repr__(self):
74
+ if self.base == 10:
75
+ return "Prefix(%r, %r, %r)" % (
76
+ str(self.name), str(self.abbrev), self._exponent)
77
+ else:
78
+ return "Prefix(%r, %r, %r, %r)" % (
79
+ str(self.name), str(self.abbrev), self._exponent, self.base)
80
+
81
+ def __mul__(self, other):
82
+ from sympy.physics.units import Quantity
83
+ if not isinstance(other, (Quantity, Prefix)):
84
+ return super().__mul__(other)
85
+
86
+ fact = self.scale_factor * other.scale_factor
87
+
88
+ if fact == 1:
89
+ return 1
90
+ elif isinstance(other, Prefix):
91
+ # simplify prefix
92
+ for p in PREFIXES:
93
+ if PREFIXES[p].scale_factor == fact:
94
+ return PREFIXES[p]
95
+ return fact
96
+
97
+ return self.scale_factor * other
98
+
99
+ def __truediv__(self, other):
100
+ if not hasattr(other, "scale_factor"):
101
+ return super().__truediv__(other)
102
+
103
+ fact = self.scale_factor / other.scale_factor
104
+
105
+ if fact == 1:
106
+ return 1
107
+ elif isinstance(other, Prefix):
108
+ for p in PREFIXES:
109
+ if PREFIXES[p].scale_factor == fact:
110
+ return PREFIXES[p]
111
+ return fact
112
+
113
+ return self.scale_factor / other
114
+
115
+ def __rtruediv__(self, other):
116
+ if other == 1:
117
+ for p in PREFIXES:
118
+ if PREFIXES[p].scale_factor == 1 / self.scale_factor:
119
+ return PREFIXES[p]
120
+ return other / self.scale_factor
121
+
122
+
123
+ def prefix_unit(unit, prefixes):
124
+ """
125
+ Return a list of all units formed by unit and the given prefixes.
126
+
127
+ You can use the predefined PREFIXES or BIN_PREFIXES, but you can also
128
+ pass as argument a subdict of them if you do not want all prefixed units.
129
+
130
+ >>> from sympy.physics.units.prefixes import (PREFIXES,
131
+ ... prefix_unit)
132
+ >>> from sympy.physics.units import m
133
+ >>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
134
+ >>> prefix_unit(m, pref) # doctest: +SKIP
135
+ [millimeter, centimeter, decimeter]
136
+ """
137
+
138
+ from sympy.physics.units.quantities import Quantity
139
+ from sympy.physics.units import UnitSystem
140
+
141
+ prefixed_units = []
142
+
143
+ for prefix_abbr, prefix in prefixes.items():
144
+ quantity = Quantity(
145
+ "%s%s" % (prefix.name, unit.name),
146
+ abbrev=("%s%s" % (prefix.abbrev, unit.abbrev)),
147
+ is_prefixed=True,
148
+ )
149
+ UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit
150
+ UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit)
151
+ prefixed_units.append(quantity)
152
+
153
+ return prefixed_units
154
+
155
+
156
+ yotta = Prefix('yotta', 'Y', 24)
157
+ zetta = Prefix('zetta', 'Z', 21)
158
+ exa = Prefix('exa', 'E', 18)
159
+ peta = Prefix('peta', 'P', 15)
160
+ tera = Prefix('tera', 'T', 12)
161
+ giga = Prefix('giga', 'G', 9)
162
+ mega = Prefix('mega', 'M', 6)
163
+ kilo = Prefix('kilo', 'k', 3)
164
+ hecto = Prefix('hecto', 'h', 2)
165
+ deca = Prefix('deca', 'da', 1)
166
+ deci = Prefix('deci', 'd', -1)
167
+ centi = Prefix('centi', 'c', -2)
168
+ milli = Prefix('milli', 'm', -3)
169
+ micro = Prefix('micro', 'mu', -6, latex_repr=r"\mu")
170
+ nano = Prefix('nano', 'n', -9)
171
+ pico = Prefix('pico', 'p', -12)
172
+ femto = Prefix('femto', 'f', -15)
173
+ atto = Prefix('atto', 'a', -18)
174
+ zepto = Prefix('zepto', 'z', -21)
175
+ yocto = Prefix('yocto', 'y', -24)
176
+
177
+
178
+ # https://physics.nist.gov/cuu/Units/prefixes.html
179
+ PREFIXES = {
180
+ 'Y': yotta,
181
+ 'Z': zetta,
182
+ 'E': exa,
183
+ 'P': peta,
184
+ 'T': tera,
185
+ 'G': giga,
186
+ 'M': mega,
187
+ 'k': kilo,
188
+ 'h': hecto,
189
+ 'da': deca,
190
+ 'd': deci,
191
+ 'c': centi,
192
+ 'm': milli,
193
+ 'mu': micro,
194
+ 'n': nano,
195
+ 'p': pico,
196
+ 'f': femto,
197
+ 'a': atto,
198
+ 'z': zepto,
199
+ 'y': yocto,
200
+ }
201
+
202
+
203
+ kibi = Prefix('kibi', 'Y', 10, 2)
204
+ mebi = Prefix('mebi', 'Y', 20, 2)
205
+ gibi = Prefix('gibi', 'Y', 30, 2)
206
+ tebi = Prefix('tebi', 'Y', 40, 2)
207
+ pebi = Prefix('pebi', 'Y', 50, 2)
208
+ exbi = Prefix('exbi', 'Y', 60, 2)
209
+
210
+
211
+ # https://physics.nist.gov/cuu/Units/binary.html
212
+ BIN_PREFIXES = {
213
+ 'Ki': kibi,
214
+ 'Mi': mebi,
215
+ 'Gi': gibi,
216
+ 'Ti': tebi,
217
+ 'Pi': pebi,
218
+ 'Ei': exbi,
219
+ }