applied-ai-018 commited on
Commit
8dd840a
·
verified ·
1 Parent(s): 6e19154

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/diffgeom/rn.py +143 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py +33 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py +342 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/external/gmpy.py +104 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/external/importtools.py +187 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_decompositions.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_determinant.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_eigen.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_graph.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_immutable.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_interactions.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_normalforms.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_solvers.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_sparse.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_sparsetools.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_subspaces.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/test_determinant.py +414 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/simplify/combsimp.py +114 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/simplify/cse_opts.py +52 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/simplify/epathtools.py +356 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/simplify/powsimp.py +714 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/simplify/ratsimp.py +222 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/simplify/sqrtdenest.py +679 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py +0 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_combsimp.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_cse.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_epathtools.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_fu.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_function.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/rn.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Predefined R^n manifolds together with common coord. systems.
2
+
3
+ Coordinate systems are predefined as well as the transformation laws between
4
+ them.
5
+
6
+ Coordinate functions can be accessed as attributes of the manifold (eg `R2.x`),
7
+ as attributes of the coordinate systems (eg `R2_r.x` and `R2_p.theta`), or by
8
+ using the usual `coord_sys.coord_function(index, name)` interface.
9
+ """
10
+
11
+ from typing import Any
12
+ import warnings
13
+
14
+ from sympy.core.symbol import (Dummy, symbols)
15
+ from sympy.functions.elementary.miscellaneous import sqrt
16
+ from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin)
17
+ from .diffgeom import Manifold, Patch, CoordSystem
18
+
19
+ __all__ = [
20
+ 'R2', 'R2_origin', 'relations_2d', 'R2_r', 'R2_p',
21
+ 'R3', 'R3_origin', 'relations_3d', 'R3_r', 'R3_c', 'R3_s'
22
+ ]
23
+
24
+ ###############################################################################
25
+ # R2
26
+ ###############################################################################
27
+ R2: Any = Manifold('R^2', 2)
28
+
29
+ R2_origin: Any = Patch('origin', R2)
30
+
31
+ x, y = symbols('x y', real=True)
32
+ r, theta = symbols('rho theta', nonnegative=True)
33
+
34
+ relations_2d = {
35
+ ('rectangular', 'polar'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
36
+ ('polar', 'rectangular'): [(r, theta), (r*cos(theta), r*sin(theta))],
37
+ }
38
+
39
+ R2_r: Any = CoordSystem('rectangular', R2_origin, (x, y), relations_2d)
40
+ R2_p: Any = CoordSystem('polar', R2_origin, (r, theta), relations_2d)
41
+
42
+ # support deprecated feature
43
+ with warnings.catch_warnings():
44
+ warnings.simplefilter("ignore")
45
+ x, y, r, theta = symbols('x y r theta', cls=Dummy)
46
+ R2_r.connect_to(R2_p, [x, y],
47
+ [sqrt(x**2 + y**2), atan2(y, x)],
48
+ inverse=False, fill_in_gaps=False)
49
+ R2_p.connect_to(R2_r, [r, theta],
50
+ [r*cos(theta), r*sin(theta)],
51
+ inverse=False, fill_in_gaps=False)
52
+
53
+ # Defining the basis coordinate functions and adding shortcuts for them to the
54
+ # manifold and the patch.
55
+ R2.x, R2.y = R2_origin.x, R2_origin.y = R2_r.x, R2_r.y = R2_r.coord_functions()
56
+ R2.r, R2.theta = R2_origin.r, R2_origin.theta = R2_p.r, R2_p.theta = R2_p.coord_functions()
57
+
58
+ # Defining the basis vector fields and adding shortcuts for them to the
59
+ # manifold and the patch.
60
+ R2.e_x, R2.e_y = R2_origin.e_x, R2_origin.e_y = R2_r.e_x, R2_r.e_y = R2_r.base_vectors()
61
+ R2.e_r, R2.e_theta = R2_origin.e_r, R2_origin.e_theta = R2_p.e_r, R2_p.e_theta = R2_p.base_vectors()
62
+
63
+ # Defining the basis oneform fields and adding shortcuts for them to the
64
+ # manifold and the patch.
65
+ R2.dx, R2.dy = R2_origin.dx, R2_origin.dy = R2_r.dx, R2_r.dy = R2_r.base_oneforms()
66
+ R2.dr, R2.dtheta = R2_origin.dr, R2_origin.dtheta = R2_p.dr, R2_p.dtheta = R2_p.base_oneforms()
67
+
68
+ ###############################################################################
69
+ # R3
70
+ ###############################################################################
71
+ R3: Any = Manifold('R^3', 3)
72
+
73
+ R3_origin: Any = Patch('origin', R3)
74
+
75
+ x, y, z = symbols('x y z', real=True)
76
+ rho, psi, r, theta, phi = symbols('rho psi r theta phi', nonnegative=True)
77
+
78
+ relations_3d = {
79
+ ('rectangular', 'cylindrical'): [(x, y, z),
80
+ (sqrt(x**2 + y**2), atan2(y, x), z)],
81
+ ('cylindrical', 'rectangular'): [(rho, psi, z),
82
+ (rho*cos(psi), rho*sin(psi), z)],
83
+ ('rectangular', 'spherical'): [(x, y, z),
84
+ (sqrt(x**2 + y**2 + z**2),
85
+ acos(z/sqrt(x**2 + y**2 + z**2)),
86
+ atan2(y, x))],
87
+ ('spherical', 'rectangular'): [(r, theta, phi),
88
+ (r*sin(theta)*cos(phi),
89
+ r*sin(theta)*sin(phi),
90
+ r*cos(theta))],
91
+ ('cylindrical', 'spherical'): [(rho, psi, z),
92
+ (sqrt(rho**2 + z**2),
93
+ acos(z/sqrt(rho**2 + z**2)),
94
+ psi)],
95
+ ('spherical', 'cylindrical'): [(r, theta, phi),
96
+ (r*sin(theta), phi, r*cos(theta))],
97
+ }
98
+
99
+ R3_r: Any = CoordSystem('rectangular', R3_origin, (x, y, z), relations_3d)
100
+ R3_c: Any = CoordSystem('cylindrical', R3_origin, (rho, psi, z), relations_3d)
101
+ R3_s: Any = CoordSystem('spherical', R3_origin, (r, theta, phi), relations_3d)
102
+
103
+ # support deprecated feature
104
+ with warnings.catch_warnings():
105
+ warnings.simplefilter("ignore")
106
+ x, y, z, rho, psi, r, theta, phi = symbols('x y z rho psi r theta phi', cls=Dummy)
107
+ R3_r.connect_to(R3_c, [x, y, z],
108
+ [sqrt(x**2 + y**2), atan2(y, x), z],
109
+ inverse=False, fill_in_gaps=False)
110
+ R3_c.connect_to(R3_r, [rho, psi, z],
111
+ [rho*cos(psi), rho*sin(psi), z],
112
+ inverse=False, fill_in_gaps=False)
113
+ ## rectangular <-> spherical
114
+ R3_r.connect_to(R3_s, [x, y, z],
115
+ [sqrt(x**2 + y**2 + z**2), acos(z/
116
+ sqrt(x**2 + y**2 + z**2)), atan2(y, x)],
117
+ inverse=False, fill_in_gaps=False)
118
+ R3_s.connect_to(R3_r, [r, theta, phi],
119
+ [r*sin(theta)*cos(phi), r*sin(
120
+ theta)*sin(phi), r*cos(theta)],
121
+ inverse=False, fill_in_gaps=False)
122
+ ## cylindrical <-> spherical
123
+ R3_c.connect_to(R3_s, [rho, psi, z],
124
+ [sqrt(rho**2 + z**2), acos(z/sqrt(rho**2 + z**2)), psi],
125
+ inverse=False, fill_in_gaps=False)
126
+ R3_s.connect_to(R3_c, [r, theta, phi],
127
+ [r*sin(theta), phi, r*cos(theta)],
128
+ inverse=False, fill_in_gaps=False)
129
+
130
+ # Defining the basis coordinate functions.
131
+ R3_r.x, R3_r.y, R3_r.z = R3_r.coord_functions()
132
+ R3_c.rho, R3_c.psi, R3_c.z = R3_c.coord_functions()
133
+ R3_s.r, R3_s.theta, R3_s.phi = R3_s.coord_functions()
134
+
135
+ # Defining the basis vector fields.
136
+ R3_r.e_x, R3_r.e_y, R3_r.e_z = R3_r.base_vectors()
137
+ R3_c.e_rho, R3_c.e_psi, R3_c.e_z = R3_c.base_vectors()
138
+ R3_s.e_r, R3_s.e_theta, R3_s.e_phi = R3_s.base_vectors()
139
+
140
+ # Defining the basis oneform fields.
141
+ R3_r.dx, R3_r.dy, R3_r.dz = R3_r.base_oneforms()
142
+ R3_c.drho, R3_c.dpsi, R3_c.dz = R3_c.base_oneforms()
143
+ R3_s.dr, R3_s.dtheta, R3_s.dphi = R3_s.base_oneforms()
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.diffgeom import Manifold, Patch, CoordSystem, Point
2
+ from sympy.core.function import Function
3
+ from sympy.core.symbol import symbols
4
+ from sympy.testing.pytest import warns_deprecated_sympy
5
+
6
+ m = Manifold('m', 2)
7
+ p = Patch('p', m)
8
+ a, b = symbols('a b')
9
+ cs = CoordSystem('cs', p, [a, b])
10
+ x, y = symbols('x y')
11
+ f = Function('f')
12
+ s1, s2 = cs.coord_functions()
13
+ v1, v2 = cs.base_vectors()
14
+ f1, f2 = cs.base_oneforms()
15
+
16
+ def test_point():
17
+ point = Point(cs, [x, y])
18
+ assert point != Point(cs, [2, y])
19
+ #TODO assert point.subs(x, 2) == Point(cs, [2, y])
20
+ #TODO assert point.free_symbols == set([x, y])
21
+
22
+ def test_subs():
23
+ assert s1.subs(s1, s2) == s2
24
+ assert v1.subs(v1, v2) == v2
25
+ assert f1.subs(f1, f2) == f2
26
+ assert (x*f(s1) + y).subs(s1, s2) == x*f(s2) + y
27
+ assert (f(s1)*v1).subs(v1, v2) == f(s1)*v2
28
+ assert (y*f(s1)*f1).subs(f1, f2) == y*f(s1)*f2
29
+
30
+ def test_deprecated():
31
+ with warns_deprecated_sympy():
32
+ cs_wname = CoordSystem('cs', p, ['a', 'b'])
33
+ assert cs_wname == cs_wname.func(*cs_wname.args)
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Lambda, Symbol, symbols
2
+ from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin
3
+ from sympy.diffgeom import (Manifold, Patch, CoordSystem, Commutator, Differential, TensorProduct,
4
+ WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative,
5
+ covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st,
6
+ metric_to_Christoffel_2nd, metric_to_Riemann_components,
7
+ metric_to_Ricci_components, intcurve_diffequ, intcurve_series)
8
+ from sympy.simplify import trigsimp, simplify
9
+ from sympy.functions import sqrt, atan2, sin
10
+ from sympy.matrices import Matrix
11
+ from sympy.testing.pytest import raises, nocache_fail
12
+ from sympy.testing.pytest import warns_deprecated_sympy
13
+
14
+ TP = TensorProduct
15
+
16
+
17
+ def test_coordsys_transform():
18
+ # test inverse transforms
19
+ p, q, r, s = symbols('p q r s')
20
+ rel = {('first', 'second'): [(p, q), (q, -p)]}
21
+ R2_pq = CoordSystem('first', R2_origin, [p, q], rel)
22
+ R2_rs = CoordSystem('second', R2_origin, [r, s], rel)
23
+ r, s = R2_rs.symbols
24
+ assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]])
25
+
26
+ # inverse transform impossible case
27
+ a, b = symbols('a b', positive=True)
28
+ rel = {('first', 'second'): [(a,), (-a,)]}
29
+ R2_a = CoordSystem('first', R2_origin, [a], rel)
30
+ R2_b = CoordSystem('second', R2_origin, [b], rel)
31
+ # This transformation is uninvertible because there is no positive a, b satisfying a = -b
32
+ with raises(NotImplementedError):
33
+ R2_b.transform(R2_a)
34
+
35
+ # inverse transform ambiguous case
36
+ c, d = symbols('c d')
37
+ rel = {('first', 'second'): [(c,), (c**2,)]}
38
+ R2_c = CoordSystem('first', R2_origin, [c], rel)
39
+ R2_d = CoordSystem('second', R2_origin, [d], rel)
40
+ # The transform method should throw if it finds multiple inverses for a coordinate transformation.
41
+ with raises(ValueError):
42
+ R2_d.transform(R2_c)
43
+
44
+ # test indirect transformation
45
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
46
+ rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)],
47
+ ('C2', 'C3'): [(c, d), (3*c, 2*d)]}
48
+ C1 = CoordSystem('C1', R2_origin, (a, b), rel)
49
+ C2 = CoordSystem('C2', R2_origin, (c, d), rel)
50
+ C3 = CoordSystem('C3', R2_origin, (e, f), rel)
51
+ a, b = C1.symbols
52
+ c, d = C2.symbols
53
+ e, f = C3.symbols
54
+ assert C2.transform(C1) == Matrix([c/2, d/3])
55
+ assert C1.transform(C3) == Matrix([6*a, 6*b])
56
+ assert C3.transform(C1) == Matrix([e/6, f/6])
57
+ assert C3.transform(C2) == Matrix([e/3, f/2])
58
+
59
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
60
+ rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)],
61
+ ('C3', 'C2'): [(e, f), (-e - 2, 2*f)]}
62
+ C1 = CoordSystem('C1', R2_origin, (a, b), rel)
63
+ C2 = CoordSystem('C2', R2_origin, (c, d), rel)
64
+ C3 = CoordSystem('C3', R2_origin, (e, f), rel)
65
+ a, b = C1.symbols
66
+ c, d = C2.symbols
67
+ e, f = C3.symbols
68
+ assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
69
+ assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
70
+ assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
71
+ assert C3.transform(C2) == Matrix([-e - 2, 2*f])
72
+
73
+ # old signature uses Lambda
74
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
75
+ rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)),
76
+ ('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))}
77
+ C1 = CoordSystem('C1', R2_origin, (a, b), rel)
78
+ C2 = CoordSystem('C2', R2_origin, (c, d), rel)
79
+ C3 = CoordSystem('C3', R2_origin, (e, f), rel)
80
+ a, b = C1.symbols
81
+ c, d = C2.symbols
82
+ e, f = C3.symbols
83
+ assert C2.transform(C1) == Matrix([c/2, (d - 1)/3])
84
+ assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2])
85
+ assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3])
86
+ assert C3.transform(C2) == Matrix([-e - 2, 2*f])
87
+
88
+
89
+ def test_R2():
90
+ x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
91
+ point_r = R2_r.point([x0, y0])
92
+ point_p = R2_p.point([r0, theta0])
93
+
94
+ # r**2 = x**2 + y**2
95
+ assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0
96
+ assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0
97
+ assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0
98
+
99
+ # polar->rect->polar == Id
100
+ a, b = symbols('a b', positive=True)
101
+ m = Matrix([[a], [b]])
102
+
103
+ #TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify)
104
+ assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify)
105
+
106
+ # deprecated method
107
+ with warns_deprecated_sympy():
108
+ assert m == R2_p.coord_tuple_transform_to(
109
+ R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify)
110
+
111
+
112
+ def test_R3():
113
+ a, b, c = symbols('a b c', positive=True)
114
+ m = Matrix([[a], [b], [c]])
115
+
116
+ assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify)
117
+ #TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify)
118
+ assert m == R3_s.transform(
119
+ R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify)
120
+ #TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify)
121
+ assert m == R3_s.transform(
122
+ R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify)
123
+ #TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify)
124
+
125
+ with warns_deprecated_sympy():
126
+ assert m == R3_c.coord_tuple_transform_to(
127
+ R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
128
+ #TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
129
+ assert m == R3_s.coord_tuple_transform_to(
130
+ R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
131
+ #TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify)
132
+ assert m == R3_s.coord_tuple_transform_to(
133
+ R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify)
134
+ #TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify)
135
+
136
+
137
+ def test_CoordinateSymbol():
138
+ x, y = R2_r.symbols
139
+ r, theta = R2_p.symbols
140
+ assert y.rewrite(R2_p) == r*sin(theta)
141
+
142
+
143
+ def test_point():
144
+ x, y = symbols('x, y')
145
+ p = R2_r.point([x, y])
146
+ assert p.free_symbols == {x, y}
147
+ assert p.coords(R2_r) == p.coords() == Matrix([x, y])
148
+ assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)])
149
+
150
+
151
+ def test_commutator():
152
+ assert Commutator(R2.e_x, R2.e_y) == 0
153
+ assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0
154
+ assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y
155
+ c = Commutator(R2.e_x, R2.e_r)
156
+ assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta)
157
+
158
+
159
+ def test_differential():
160
+ xdy = R2.x*R2.dy
161
+ dxdy = Differential(xdy)
162
+ assert xdy.rcall(None) == xdy
163
+ assert dxdy(R2.e_x, R2.e_y) == 1
164
+ assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x
165
+ assert Differential(dxdy) == 0
166
+
167
+
168
+ def test_products():
169
+ assert TensorProduct(
170
+ R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1
171
+ assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx
172
+ assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy
173
+ assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy
174
+ assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx
175
+ assert TensorProduct(
176
+ R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1
177
+ assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x
178
+ assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y
179
+ assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y
180
+ assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
181
+ assert TensorProduct(
182
+ R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1
183
+ assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx
184
+ assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y
185
+ assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y
186
+ assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x
187
+ assert TensorProduct(
188
+ R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1
189
+ assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x
190
+ assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy
191
+ assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy
192
+ assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y
193
+
194
+ assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1
195
+ assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1
196
+
197
+
198
+ def test_lie_derivative():
199
+ assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0
200
+ assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1
201
+ assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0
202
+ assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r)
203
+ assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1
204
+ assert LieDerivative(
205
+ R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0
206
+
207
+
208
+ @nocache_fail
209
+ def test_covar_deriv():
210
+ ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
211
+ cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
212
+ assert cvd(R2.x) == 1
213
+ # This line fails if the cache is disabled:
214
+ assert cvd(R2.x*R2.e_x) == R2.e_x
215
+ cvd = CovarDerivativeOp(R2.x*R2.e_x, ch)
216
+ assert cvd(R2.x) == R2.x
217
+ assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x
218
+
219
+
220
+ def test_intcurve_diffequ():
221
+ t = symbols('t')
222
+ start_point = R2_r.point([1, 0])
223
+ vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
224
+ equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
225
+ assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]'
226
+ assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
227
+ equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
228
+ assert str(
229
+ equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]'
230
+ assert str(init_cond) == '[f_0(0) - 1, f_1(0)]'
231
+
232
+
233
+ def test_helpers_and_coordinate_dependent():
234
+ one_form = R2.dr + R2.dx
235
+ two_form = Differential(R2.x*R2.dr + R2.r*R2.dx)
236
+ three_form = Differential(
237
+ R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr))
238
+ metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy)
239
+ metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr)
240
+ misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr
241
+ misform_b = R2.dr**4
242
+ misform_c = R2.dx*R2.dy
243
+ twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy)
244
+ twoform_not_TP = WedgeProduct(R2.dx, R2.dy)
245
+
246
+ one_vector = R2.e_x + R2.e_y
247
+ two_vector = TensorProduct(R2.e_x, R2.e_y)
248
+ three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x)
249
+ two_wp = WedgeProduct(R2.e_x,R2.e_y)
250
+
251
+ assert covariant_order(one_form) == 1
252
+ assert covariant_order(two_form) == 2
253
+ assert covariant_order(three_form) == 3
254
+ assert covariant_order(two_form + metric) == 2
255
+ assert covariant_order(two_form + metric_ambig) == 2
256
+ assert covariant_order(two_form + twoform_not_sym) == 2
257
+ assert covariant_order(two_form + twoform_not_TP) == 2
258
+
259
+ assert contravariant_order(one_vector) == 1
260
+ assert contravariant_order(two_vector) == 2
261
+ assert contravariant_order(three_vector) == 3
262
+ assert contravariant_order(two_vector + two_wp) == 2
263
+
264
+ raises(ValueError, lambda: covariant_order(misform_a))
265
+ raises(ValueError, lambda: covariant_order(misform_b))
266
+ raises(ValueError, lambda: covariant_order(misform_c))
267
+
268
+ assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]])
269
+ assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]])
270
+ assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]])
271
+
272
+ raises(ValueError, lambda: twoform_to_matrix(one_form))
273
+ raises(ValueError, lambda: twoform_to_matrix(three_form))
274
+ raises(ValueError, lambda: twoform_to_matrix(metric_ambig))
275
+
276
+ raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym))
277
+ raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym))
278
+ raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym))
279
+ raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym))
280
+
281
+
282
+ def test_correct_arguments():
283
+ raises(ValueError, lambda: R2.e_x(R2.e_x))
284
+ raises(ValueError, lambda: R2.e_x(R2.dx))
285
+
286
+ raises(ValueError, lambda: Commutator(R2.e_x, R2.x))
287
+ raises(ValueError, lambda: Commutator(R2.dx, R2.e_x))
288
+
289
+ raises(ValueError, lambda: Differential(Differential(R2.e_x)))
290
+
291
+ raises(ValueError, lambda: R2.dx(R2.x))
292
+
293
+ raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx))
294
+ raises(ValueError, lambda: LieDerivative(R2.x, R2.dx))
295
+
296
+ raises(ValueError, lambda: CovarDerivativeOp(R2.dx, []))
297
+ raises(ValueError, lambda: CovarDerivativeOp(R2.x, []))
298
+
299
+ a = Symbol('a')
300
+ raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2])))
301
+ raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2])))
302
+
303
+ raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2])))
304
+ raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2])))
305
+
306
+ raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx))
307
+ raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx))
308
+
309
+ raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y))
310
+ raises(ValueError, lambda: covariant_order(R2.dx*R2.dy))
311
+
312
+ def test_simplify():
313
+ x, y = R2_r.coord_functions()
314
+ dx, dy = R2_r.base_oneforms()
315
+ ex, ey = R2_r.base_vectors()
316
+ assert simplify(x) == x
317
+ assert simplify(x*y) == x*y
318
+ assert simplify(dx*dy) == dx*dy
319
+ assert simplify(ex*ey) == ex*ey
320
+ assert ((1-x)*dx)/(1-x)**2 == dx/(1-x)
321
+
322
+
323
+ def test_issue_17917():
324
+ X = R2.x*R2.e_x - R2.y*R2.e_y
325
+ Y = (R2.x**2 + R2.y**2)*R2.e_x - R2.x*R2.y*R2.e_y
326
+ assert LieDerivative(X, Y).expand() == (
327
+ R2.x**2*R2.e_x - 3*R2.y**2*R2.e_x - R2.x*R2.y*R2.e_y)
328
+
329
+ def test_deprecations():
330
+ m = Manifold('M', 2)
331
+ p = Patch('P', m)
332
+ with warns_deprecated_sympy():
333
+ CoordSystem('Car2d', p, names=['x', 'y'])
334
+
335
+ with warns_deprecated_sympy():
336
+ c = CoordSystem('Car2d', p, ['x', 'y'])
337
+
338
+ with warns_deprecated_sympy():
339
+ list(m.patches)
340
+
341
+ with warns_deprecated_sympy():
342
+ list(c.transforms)
env-llmeval/lib/python3.10/site-packages/sympy/external/gmpy.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Tuple as tTuple, Type
3
+
4
+ import mpmath.libmp as mlib
5
+
6
+ from sympy.external import import_module
7
+
8
+ __all__ = [
9
+ # GROUND_TYPES is either 'gmpy' or 'python' depending on which is used. If
10
+ # gmpy is installed then it will be used unless the environment variable
11
+ # SYMPY_GROUND_TYPES is set to something other than 'auto', 'gmpy', or
12
+ # 'gmpy2'.
13
+ 'GROUND_TYPES',
14
+
15
+ # If HAS_GMPY is 0, no supported version of gmpy is available. Otherwise,
16
+ # HAS_GMPY will be 2 for gmpy2 if GROUND_TYPES is 'gmpy'. It used to be
17
+ # possible for HAS_GMPY to be 1 for gmpy but gmpy is no longer supported.
18
+ 'HAS_GMPY',
19
+
20
+ # SYMPY_INTS is a tuple containing the base types for valid integer types.
21
+ # This is either (int,) or (int, type(mpz(0))) depending on GROUND_TYPES.
22
+ 'SYMPY_INTS',
23
+
24
+ # MPQ is either gmpy.mpq or the Python equivalent from
25
+ # sympy.external.pythonmpq
26
+ 'MPQ',
27
+
28
+ # MPZ is either gmpy.mpz or int.
29
+ 'MPZ',
30
+
31
+ # Either the gmpy or the mpmath function
32
+ 'factorial',
33
+
34
+ # isqrt from gmpy or mpmath
35
+ 'sqrt',
36
+ ]
37
+
38
+
39
+ #
40
+ # SYMPY_GROUND_TYPES can be gmpy, gmpy2, python or auto
41
+ #
42
+ GROUND_TYPES = os.environ.get('SYMPY_GROUND_TYPES', 'auto').lower()
43
+
44
+
45
+ #
46
+ # Try to import gmpy2 by default. If gmpy or gmpy2 is specified in
47
+ # SYMPY_GROUND_TYPES then warn if gmpy2 is not found. In all cases there is a
48
+ # fallback based on pure Python int and PythonMPQ that should still work fine.
49
+ #
50
+ if GROUND_TYPES in ('auto', 'gmpy', 'gmpy2'):
51
+
52
+ # Actually import gmpy2
53
+ gmpy = import_module('gmpy2', min_module_version='2.0.0',
54
+ module_version_attr='version', module_version_attr_call_args=())
55
+
56
+ # Warn if user explicitly asked for gmpy but it isn't available.
57
+ if gmpy is None and GROUND_TYPES in ('gmpy', 'gmpy2'):
58
+ from warnings import warn
59
+ warn("gmpy library is not installed, switching to 'python' ground types")
60
+
61
+ elif GROUND_TYPES == 'python':
62
+
63
+ # The user asked for Python so ignore gmpy2 module.
64
+ gmpy = None
65
+
66
+ else:
67
+
68
+ # Invalid value for SYMPY_GROUND_TYPES. Ignore the gmpy2 module.
69
+ from warnings import warn
70
+ warn("SYMPY_GROUND_TYPES environment variable unrecognised. "
71
+ "Should be 'python', 'auto', 'gmpy', or 'gmpy2'")
72
+ gmpy = None
73
+
74
+
75
+ #
76
+ # At this point gmpy will be None if gmpy2 was not successfully imported or if
77
+ # the environment variable SYMPY_GROUND_TYPES was set to 'python' (or some
78
+ # unrecognised value). The two blocks below define the values exported by this
79
+ # module in each case.
80
+ #
81
+ SYMPY_INTS: tTuple[Type, ...]
82
+
83
+ if gmpy is not None:
84
+
85
+ HAS_GMPY = 2
86
+ GROUND_TYPES = 'gmpy'
87
+ SYMPY_INTS = (int, type(gmpy.mpz(0)))
88
+ MPZ = gmpy.mpz
89
+ MPQ = gmpy.mpq
90
+
91
+ factorial = gmpy.fac
92
+ sqrt = gmpy.isqrt
93
+
94
+ else:
95
+ from .pythonmpq import PythonMPQ
96
+
97
+ HAS_GMPY = 0
98
+ GROUND_TYPES = 'python'
99
+ SYMPY_INTS = (int,)
100
+ MPZ = int
101
+ MPQ = PythonMPQ
102
+
103
+ factorial = lambda x: int(mlib.ifac(x))
104
+ sqrt = lambda x: int(mlib.isqrt(x))
env-llmeval/lib/python3.10/site-packages/sympy/external/importtools.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools to assist importing optional external modules."""
2
+
3
+ import sys
4
+ import re
5
+
6
+ # Override these in the module to change the default warning behavior.
7
+ # For example, you might set both to False before running the tests so that
8
+ # warnings are not printed to the console, or set both to True for debugging.
9
+
10
+ WARN_NOT_INSTALLED = None # Default is False
11
+ WARN_OLD_VERSION = None # Default is True
12
+
13
+
14
+ def __sympy_debug():
15
+ # helper function from sympy/__init__.py
16
+ # We don't just import SYMPY_DEBUG from that file because we don't want to
17
+ # import all of SymPy just to use this module.
18
+ import os
19
+ debug_str = os.getenv('SYMPY_DEBUG', 'False')
20
+ if debug_str in ('True', 'False'):
21
+ return eval(debug_str)
22
+ else:
23
+ raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
24
+ debug_str)
25
+
26
+ if __sympy_debug():
27
+ WARN_OLD_VERSION = True
28
+ WARN_NOT_INSTALLED = True
29
+
30
+
31
+ _component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
32
+
33
+ def version_tuple(vstring):
34
+ # Parse a version string to a tuple e.g. '1.2' -> (1, 2)
35
+ # Simplified from distutils.version.LooseVersion which was deprecated in
36
+ # Python 3.10.
37
+ components = []
38
+ for x in _component_re.split(vstring):
39
+ if x and x != '.':
40
+ try:
41
+ x = int(x)
42
+ except ValueError:
43
+ pass
44
+ components.append(x)
45
+ return tuple(components)
46
+
47
+
48
+ def import_module(module, min_module_version=None, min_python_version=None,
49
+ warn_not_installed=None, warn_old_version=None,
50
+ module_version_attr='__version__', module_version_attr_call_args=None,
51
+ import_kwargs={}, catch=()):
52
+ """
53
+ Import and return a module if it is installed.
54
+
55
+ If the module is not installed, it returns None.
56
+
57
+ A minimum version for the module can be given as the keyword argument
58
+ min_module_version. This should be comparable against the module version.
59
+ By default, module.__version__ is used to get the module version. To
60
+ override this, set the module_version_attr keyword argument. If the
61
+ attribute of the module to get the version should be called (e.g.,
62
+ module.version()), then set module_version_attr_call_args to the args such
63
+ that module.module_version_attr(*module_version_attr_call_args) returns the
64
+ module's version.
65
+
66
+ If the module version is less than min_module_version using the Python <
67
+ comparison, None will be returned, even if the module is installed. You can
68
+ use this to keep from importing an incompatible older version of a module.
69
+
70
+ You can also specify a minimum Python version by using the
71
+ min_python_version keyword argument. This should be comparable against
72
+ sys.version_info.
73
+
74
+ If the keyword argument warn_not_installed is set to True, the function will
75
+ emit a UserWarning when the module is not installed.
76
+
77
+ If the keyword argument warn_old_version is set to True, the function will
78
+ emit a UserWarning when the library is installed, but cannot be imported
79
+ because of the min_module_version or min_python_version options.
80
+
81
+ Note that because of the way warnings are handled, a warning will be
82
+ emitted for each module only once. You can change the default warning
83
+ behavior by overriding the values of WARN_NOT_INSTALLED and WARN_OLD_VERSION
84
+ in sympy.external.importtools. By default, WARN_NOT_INSTALLED is False and
85
+ WARN_OLD_VERSION is True.
86
+
87
+ This function uses __import__() to import the module. To pass additional
88
+ options to __import__(), use the import_kwargs keyword argument. For
89
+ example, to import a submodule A.B, you must pass a nonempty fromlist option
90
+ to __import__. See the docstring of __import__().
91
+
92
+ This catches ImportError to determine if the module is not installed. To
93
+ catch additional errors, pass them as a tuple to the catch keyword
94
+ argument.
95
+
96
+ Examples
97
+ ========
98
+
99
+ >>> from sympy.external import import_module
100
+
101
+ >>> numpy = import_module('numpy')
102
+
103
+ >>> numpy = import_module('numpy', min_python_version=(2, 7),
104
+ ... warn_old_version=False)
105
+
106
+ >>> numpy = import_module('numpy', min_module_version='1.5',
107
+ ... warn_old_version=False) # numpy.__version__ is a string
108
+
109
+ >>> # gmpy does not have __version__, but it does have gmpy.version()
110
+
111
+ >>> gmpy = import_module('gmpy', min_module_version='1.14',
112
+ ... module_version_attr='version', module_version_attr_call_args=(),
113
+ ... warn_old_version=False)
114
+
115
+ >>> # To import a submodule, you must pass a nonempty fromlist to
116
+ >>> # __import__(). The values do not matter.
117
+ >>> p3 = import_module('mpl_toolkits.mplot3d',
118
+ ... import_kwargs={'fromlist':['something']})
119
+
120
+ >>> # matplotlib.pyplot can raise RuntimeError when the display cannot be opened
121
+ >>> matplotlib = import_module('matplotlib',
122
+ ... import_kwargs={'fromlist':['pyplot']}, catch=(RuntimeError,))
123
+
124
+ """
125
+ # keyword argument overrides default, and global variable overrides
126
+ # keyword argument.
127
+ warn_old_version = (WARN_OLD_VERSION if WARN_OLD_VERSION is not None
128
+ else warn_old_version or True)
129
+ warn_not_installed = (WARN_NOT_INSTALLED if WARN_NOT_INSTALLED is not None
130
+ else warn_not_installed or False)
131
+
132
+ import warnings
133
+
134
+ # Check Python first so we don't waste time importing a module we can't use
135
+ if min_python_version:
136
+ if sys.version_info < min_python_version:
137
+ if warn_old_version:
138
+ warnings.warn("Python version is too old to use %s "
139
+ "(%s or newer required)" % (
140
+ module, '.'.join(map(str, min_python_version))),
141
+ UserWarning, stacklevel=2)
142
+ return
143
+
144
+ try:
145
+ mod = __import__(module, **import_kwargs)
146
+
147
+ ## there's something funny about imports with matplotlib and py3k. doing
148
+ ## from matplotlib import collections
149
+ ## gives python's stdlib collections module. explicitly re-importing
150
+ ## the module fixes this.
151
+ from_list = import_kwargs.get('fromlist', ())
152
+ for submod in from_list:
153
+ if submod == 'collections' and mod.__name__ == 'matplotlib':
154
+ __import__(module + '.' + submod)
155
+ except ImportError:
156
+ if warn_not_installed:
157
+ warnings.warn("%s module is not installed" % module, UserWarning,
158
+ stacklevel=2)
159
+ return
160
+ except catch as e:
161
+ if warn_not_installed:
162
+ warnings.warn(
163
+ "%s module could not be used (%s)" % (module, repr(e)),
164
+ stacklevel=2)
165
+ return
166
+
167
+ if min_module_version:
168
+ modversion = getattr(mod, module_version_attr)
169
+ if module_version_attr_call_args is not None:
170
+ modversion = modversion(*module_version_attr_call_args)
171
+ if version_tuple(modversion) < version_tuple(min_module_version):
172
+ if warn_old_version:
173
+ # Attempt to create a pretty string version of the version
174
+ if isinstance(min_module_version, str):
175
+ verstr = min_module_version
176
+ elif isinstance(min_module_version, (tuple, list)):
177
+ verstr = '.'.join(map(str, min_module_version))
178
+ else:
179
+ # Either don't know what this is. Hopefully
180
+ # it's something that has a nice str version, like an int.
181
+ verstr = str(min_module_version)
182
+ warnings.warn("%s version is too old to use "
183
+ "(%s or newer required)" % (module, verstr),
184
+ UserWarning, stacklevel=2)
185
+ return
186
+
187
+ return mod
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-310.pyc ADDED
Binary file (43.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_decompositions.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_determinant.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_eigen.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_graph.cpython-310.pyc ADDED
Binary file (2.92 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_immutable.cpython-310.pyc ADDED
Binary file (5.12 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_interactions.cpython-310.pyc ADDED
Binary file (2.87 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-310.pyc ADDED
Binary file (129 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_normalforms.cpython-310.pyc ADDED
Binary file (3.36 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_solvers.cpython-310.pyc ADDED
Binary file (16.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_sparse.cpython-310.pyc ADDED
Binary file (21.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_sparsetools.cpython-310.pyc ADDED
Binary file (6.85 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_subspaces.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/matrices/tests/test_determinant.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from sympy.core.numbers import I
3
+ from sympy.core.numbers import Rational
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.polys.polytools import Poly
7
+ from sympy.matrices import Matrix, eye, ones
8
+ from sympy.abc import x, y, z
9
+ from sympy.testing.pytest import raises
10
+ from sympy.matrices.common import NonSquareMatrixError
11
+ from sympy.functions.combinatorial.factorials import factorial, subfactorial
12
+
13
+
14
+ def test_determinant():
15
+ M = Matrix()
16
+
17
+ assert M.det() == 1
18
+ # Evaluating these directly because they are never reached via M.det()
19
+ assert M._eval_det_bareiss() == 1
20
+ assert M._eval_det_berkowitz() == 1
21
+ assert M._eval_det_lu() == 1
22
+
23
+ M = Matrix([ [0] ])
24
+
25
+ assert M.det() == 0
26
+ assert M._eval_det_bareiss() == 0
27
+ assert M._eval_det_berkowitz() == 0
28
+ assert M._eval_det_lu() == 0
29
+
30
+ M = Matrix([ [5] ])
31
+
32
+ assert M.det() == 5
33
+ assert M._eval_det_bareiss() == 5
34
+ assert M._eval_det_berkowitz() == 5
35
+ assert M._eval_det_lu() == 5
36
+
37
+ M = Matrix(( (-3, 2),
38
+ ( 8, -5) ))
39
+
40
+ assert M.det(method="domain-ge") == -1
41
+ assert M.det(method="bareiss") == -1
42
+ assert M.det(method="berkowitz") == -1
43
+ assert M.det(method="lu") == -1
44
+
45
+ M = Matrix(( (x, 1),
46
+ (y, 2*y) ))
47
+
48
+ assert M.det(method="domain-ge") == 2*x*y - y
49
+ assert M.det(method="bareiss") == 2*x*y - y
50
+ assert M.det(method="berkowitz") == 2*x*y - y
51
+ assert M.det(method="lu") == 2*x*y - y
52
+
53
+ M = Matrix(( (1, 1, 1),
54
+ (1, 2, 3),
55
+ (1, 3, 6) ))
56
+
57
+ assert M.det(method="domain-ge") == 1
58
+ assert M.det(method="bareiss") == 1
59
+ assert M.det(method="berkowitz") == 1
60
+ assert M.det(method="lu") == 1
61
+
62
+ M = Matrix(( ( 3, -2, 0, 5),
63
+ (-2, 1, -2, 2),
64
+ ( 0, -2, 5, 0),
65
+ ( 5, 0, 3, 4) ))
66
+
67
+ assert M.det(method="domain-ge") == -289
68
+ assert M.det(method="bareiss") == -289
69
+ assert M.det(method="berkowitz") == -289
70
+ assert M.det(method="lu") == -289
71
+
72
+ M = Matrix(( ( 1, 2, 3, 4),
73
+ ( 5, 6, 7, 8),
74
+ ( 9, 10, 11, 12),
75
+ (13, 14, 15, 16) ))
76
+
77
+ assert M.det(method="domain-ge") == 0
78
+ assert M.det(method="bareiss") == 0
79
+ assert M.det(method="berkowitz") == 0
80
+ assert M.det(method="lu") == 0
81
+
82
+ M = Matrix(( (3, 2, 0, 0, 0),
83
+ (0, 3, 2, 0, 0),
84
+ (0, 0, 3, 2, 0),
85
+ (0, 0, 0, 3, 2),
86
+ (2, 0, 0, 0, 3) ))
87
+
88
+ assert M.det(method="domain-ge") == 275
89
+ assert M.det(method="bareiss") == 275
90
+ assert M.det(method="berkowitz") == 275
91
+ assert M.det(method="lu") == 275
92
+
93
+ M = Matrix(( ( 3, 0, 0, 0),
94
+ (-2, 1, 0, 0),
95
+ ( 0, -2, 5, 0),
96
+ ( 5, 0, 3, 4) ))
97
+
98
+ assert M.det(method="domain-ge") == 60
99
+ assert M.det(method="bareiss") == 60
100
+ assert M.det(method="berkowitz") == 60
101
+ assert M.det(method="lu") == 60
102
+
103
+ M = Matrix(( ( 1, 0, 0, 0),
104
+ ( 5, 0, 0, 0),
105
+ ( 9, 10, 11, 0),
106
+ (13, 14, 15, 16) ))
107
+
108
+ assert M.det(method="domain-ge") == 0
109
+ assert M.det(method="bareiss") == 0
110
+ assert M.det(method="berkowitz") == 0
111
+ assert M.det(method="lu") == 0
112
+
113
+ M = Matrix(( (3, 2, 0, 0, 0),
114
+ (0, 3, 2, 0, 0),
115
+ (0, 0, 3, 2, 0),
116
+ (0, 0, 0, 3, 2),
117
+ (0, 0, 0, 0, 3) ))
118
+
119
+ assert M.det(method="domain-ge") == 243
120
+ assert M.det(method="bareiss") == 243
121
+ assert M.det(method="berkowitz") == 243
122
+ assert M.det(method="lu") == 243
123
+
124
+ M = Matrix(( (1, 0, 1, 2, 12),
125
+ (2, 0, 1, 1, 4),
126
+ (2, 1, 1, -1, 3),
127
+ (3, 2, -1, 1, 8),
128
+ (1, 1, 1, 0, 6) ))
129
+
130
+ assert M.det(method="domain-ge") == -55
131
+ assert M.det(method="bareiss") == -55
132
+ assert M.det(method="berkowitz") == -55
133
+ assert M.det(method="lu") == -55
134
+
135
+ M = Matrix(( (-5, 2, 3, 4, 5),
136
+ ( 1, -4, 3, 4, 5),
137
+ ( 1, 2, -3, 4, 5),
138
+ ( 1, 2, 3, -2, 5),
139
+ ( 1, 2, 3, 4, -1) ))
140
+
141
+ assert M.det(method="domain-ge") == 11664
142
+ assert M.det(method="bareiss") == 11664
143
+ assert M.det(method="berkowitz") == 11664
144
+ assert M.det(method="lu") == 11664
145
+
146
+ M = Matrix(( ( 2, 7, -1, 3, 2),
147
+ ( 0, 0, 1, 0, 1),
148
+ (-2, 0, 7, 0, 2),
149
+ (-3, -2, 4, 5, 3),
150
+ ( 1, 0, 0, 0, 1) ))
151
+
152
+ assert M.det(method="domain-ge") == 123
153
+ assert M.det(method="bareiss") == 123
154
+ assert M.det(method="berkowitz") == 123
155
+ assert M.det(method="lu") == 123
156
+
157
+ M = Matrix(( (x, y, z),
158
+ (1, 0, 0),
159
+ (y, z, x) ))
160
+
161
+ assert M.det(method="domain-ge") == z**2 - x*y
162
+ assert M.det(method="bareiss") == z**2 - x*y
163
+ assert M.det(method="berkowitz") == z**2 - x*y
164
+ assert M.det(method="lu") == z**2 - x*y
165
+
166
+ # issue 13835
167
+ a = symbols('a')
168
+ M = lambda n: Matrix([[i + a*j for i in range(n)]
169
+ for j in range(n)])
170
+ assert M(5).det() == 0
171
+ assert M(6).det() == 0
172
+ assert M(7).det() == 0
173
+
174
+ def test_issue_14517():
175
+ M = Matrix([
176
+ [ 0, 10*I, 10*I, 0],
177
+ [10*I, 0, 0, 10*I],
178
+ [10*I, 0, 5 + 2*I, 10*I],
179
+ [ 0, 10*I, 10*I, 5 + 2*I]])
180
+ ev = M.eigenvals()
181
+ # test one random eigenvalue, the computation is a little slow
182
+ test_ev = random.choice(list(ev.keys()))
183
+ assert (M - test_ev*eye(4)).det() == 0
184
+
185
+ def test_legacy_det():
186
+ # Minimal support for legacy keys for 'method' in det()
187
+ # Partially copied from test_determinant()
188
+
189
+ M = Matrix(( ( 3, -2, 0, 5),
190
+ (-2, 1, -2, 2),
191
+ ( 0, -2, 5, 0),
192
+ ( 5, 0, 3, 4) ))
193
+
194
+ assert M.det(method="bareis") == -289
195
+ assert M.det(method="det_lu") == -289
196
+ assert M.det(method="det_LU") == -289
197
+
198
+ M = Matrix(( (3, 2, 0, 0, 0),
199
+ (0, 3, 2, 0, 0),
200
+ (0, 0, 3, 2, 0),
201
+ (0, 0, 0, 3, 2),
202
+ (2, 0, 0, 0, 3) ))
203
+
204
+ assert M.det(method="bareis") == 275
205
+ assert M.det(method="det_lu") == 275
206
+ assert M.det(method="Bareis") == 275
207
+
208
+ M = Matrix(( (1, 0, 1, 2, 12),
209
+ (2, 0, 1, 1, 4),
210
+ (2, 1, 1, -1, 3),
211
+ (3, 2, -1, 1, 8),
212
+ (1, 1, 1, 0, 6) ))
213
+
214
+ assert M.det(method="bareis") == -55
215
+ assert M.det(method="det_lu") == -55
216
+ assert M.det(method="BAREISS") == -55
217
+
218
+ M = Matrix(( ( 3, 0, 0, 0),
219
+ (-2, 1, 0, 0),
220
+ ( 0, -2, 5, 0),
221
+ ( 5, 0, 3, 4) ))
222
+
223
+ assert M.det(method="bareiss") == 60
224
+ assert M.det(method="berkowitz") == 60
225
+ assert M.det(method="lu") == 60
226
+
227
+ M = Matrix(( ( 1, 0, 0, 0),
228
+ ( 5, 0, 0, 0),
229
+ ( 9, 10, 11, 0),
230
+ (13, 14, 15, 16) ))
231
+
232
+ assert M.det(method="bareiss") == 0
233
+ assert M.det(method="berkowitz") == 0
234
+ assert M.det(method="lu") == 0
235
+
236
+ M = Matrix(( (3, 2, 0, 0, 0),
237
+ (0, 3, 2, 0, 0),
238
+ (0, 0, 3, 2, 0),
239
+ (0, 0, 0, 3, 2),
240
+ (0, 0, 0, 0, 3) ))
241
+
242
+ assert M.det(method="bareiss") == 243
243
+ assert M.det(method="berkowitz") == 243
244
+ assert M.det(method="lu") == 243
245
+
246
+ M = Matrix(( (-5, 2, 3, 4, 5),
247
+ ( 1, -4, 3, 4, 5),
248
+ ( 1, 2, -3, 4, 5),
249
+ ( 1, 2, 3, -2, 5),
250
+ ( 1, 2, 3, 4, -1) ))
251
+
252
+ assert M.det(method="bareis") == 11664
253
+ assert M.det(method="det_lu") == 11664
254
+ assert M.det(method="BERKOWITZ") == 11664
255
+
256
+ M = Matrix(( ( 2, 7, -1, 3, 2),
257
+ ( 0, 0, 1, 0, 1),
258
+ (-2, 0, 7, 0, 2),
259
+ (-3, -2, 4, 5, 3),
260
+ ( 1, 0, 0, 0, 1) ))
261
+
262
+ assert M.det(method="bareis") == 123
263
+ assert M.det(method="det_lu") == 123
264
+ assert M.det(method="LU") == 123
265
+
266
+ def eye_Determinant(n):
267
+ return Matrix(n, n, lambda i, j: int(i == j))
268
+
269
+ def zeros_Determinant(n):
270
+ return Matrix(n, n, lambda i, j: 0)
271
+
272
+ def test_det():
273
+ a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
274
+ raises(NonSquareMatrixError, lambda: a.det())
275
+
276
+ z = zeros_Determinant(2)
277
+ ey = eye_Determinant(2)
278
+ assert z.det() == 0
279
+ assert ey.det() == 1
280
+
281
+ x = Symbol('x')
282
+ a = Matrix(0, 0, [])
283
+ b = Matrix(1, 1, [5])
284
+ c = Matrix(2, 2, [1, 2, 3, 4])
285
+ d = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
286
+ e = Matrix(4, 4,
287
+ [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
288
+ from sympy.abc import i, j, k, l, m, n
289
+ f = Matrix(3, 3, [i, l, m, 0, j, n, 0, 0, k])
290
+ g = Matrix(3, 3, [i, 0, 0, l, j, 0, m, n, k])
291
+ h = Matrix(3, 3, [x**3, 0, 0, i, x**-1, 0, j, k, x**-2])
292
+ # the method keyword for `det` doesn't kick in until 4x4 matrices,
293
+ # so there is no need to test all methods on smaller ones
294
+
295
+ assert a.det() == 1
296
+ assert b.det() == 5
297
+ assert c.det() == -2
298
+ assert d.det() == 3
299
+ assert e.det() == 4*x - 24
300
+ assert e.det(method="domain-ge") == 4*x - 24
301
+ assert e.det(method='bareiss') == 4*x - 24
302
+ assert e.det(method='berkowitz') == 4*x - 24
303
+ assert f.det() == i*j*k
304
+ assert g.det() == i*j*k
305
+ assert h.det() == 1
306
+ raises(ValueError, lambda: e.det(iszerofunc="test"))
307
+
308
+ def test_permanent():
309
+ M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
310
+ assert M.per() == 450
311
+ for i in range(1, 12):
312
+ assert ones(i, i).per() == ones(i, i).T.per() == factorial(i)
313
+ assert (ones(i, i)-eye(i)).per() == (ones(i, i)-eye(i)).T.per() == subfactorial(i)
314
+
315
+ a1, a2, a3, a4, a5 = symbols('a_1 a_2 a_3 a_4 a_5')
316
+ M = Matrix([a1, a2, a3, a4, a5])
317
+ assert M.per() == M.T.per() == a1 + a2 + a3 + a4 + a5
318
+
319
+ def test_adjugate():
320
+ x = Symbol('x')
321
+ e = Matrix(4, 4,
322
+ [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
323
+
324
+ adj = Matrix([
325
+ [ 4, -8, 4, 0],
326
+ [ 76, -14*x - 68, 14*x - 8, -4*x + 24],
327
+ [-122, 17*x + 142, -21*x + 4, 8*x - 48],
328
+ [ 48, -4*x - 72, 8*x, -4*x + 24]])
329
+ assert e.adjugate() == adj
330
+ assert e.adjugate(method='bareiss') == adj
331
+ assert e.adjugate(method='berkowitz') == adj
332
+
333
+ a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
334
+ raises(NonSquareMatrixError, lambda: a.adjugate())
335
+
336
+ def test_util():
337
+ R = Rational
338
+
339
+ v1 = Matrix(1, 3, [1, 2, 3])
340
+ v2 = Matrix(1, 3, [3, 4, 5])
341
+ assert v1.norm() == sqrt(14)
342
+ assert v1.project(v2) == Matrix(1, 3, [R(39)/25, R(52)/25, R(13)/5])
343
+ assert Matrix.zeros(1, 2) == Matrix(1, 2, [0, 0])
344
+ assert ones(1, 2) == Matrix(1, 2, [1, 1])
345
+ assert v1.copy() == v1
346
+ # cofactor
347
+ assert eye(3) == eye(3).cofactor_matrix()
348
+ test = Matrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
349
+ assert test.cofactor_matrix() == \
350
+ Matrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
351
+ test = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
352
+ assert test.cofactor_matrix() == \
353
+ Matrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])
354
+
355
+ def test_cofactor_and_minors():
356
+ x = Symbol('x')
357
+ e = Matrix(4, 4,
358
+ [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
359
+
360
+ m = Matrix([
361
+ [ x, 1, 3],
362
+ [ 2, 9, 11],
363
+ [12, 13, 14]])
364
+ cm = Matrix([
365
+ [ 4, 76, -122, 48],
366
+ [-8, -14*x - 68, 17*x + 142, -4*x - 72],
367
+ [ 4, 14*x - 8, -21*x + 4, 8*x],
368
+ [ 0, -4*x + 24, 8*x - 48, -4*x + 24]])
369
+ sub = Matrix([
370
+ [x, 1, 2],
371
+ [4, 5, 6],
372
+ [2, 9, 10]])
373
+
374
+ assert e.minor_submatrix(1, 2) == m
375
+ assert e.minor_submatrix(-1, -1) == sub
376
+ assert e.minor(1, 2) == -17*x - 142
377
+ assert e.cofactor(1, 2) == 17*x + 142
378
+ assert e.cofactor_matrix() == cm
379
+ assert e.cofactor_matrix(method="bareiss") == cm
380
+ assert e.cofactor_matrix(method="berkowitz") == cm
381
+
382
+ raises(ValueError, lambda: e.cofactor(4, 5))
383
+ raises(ValueError, lambda: e.minor(4, 5))
384
+ raises(ValueError, lambda: e.minor_submatrix(4, 5))
385
+
386
+ a = Matrix(2, 3, [1, 2, 3, 4, 5, 6])
387
+ assert a.minor_submatrix(0, 0) == Matrix([[5, 6]])
388
+
389
+ raises(ValueError, lambda:
390
+ Matrix(0, 0, []).minor_submatrix(0, 0))
391
+ raises(NonSquareMatrixError, lambda: a.cofactor(0, 0))
392
+ raises(NonSquareMatrixError, lambda: a.minor(0, 0))
393
+ raises(NonSquareMatrixError, lambda: a.cofactor_matrix())
394
+
395
+ def test_charpoly():
396
+ x, y = Symbol('x'), Symbol('y')
397
+ z, t = Symbol('z'), Symbol('t')
398
+
399
+ from sympy.abc import a,b,c
400
+
401
+ m = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
402
+
403
+ assert eye_Determinant(3).charpoly(x) == Poly((x - 1)**3, x)
404
+ assert eye_Determinant(3).charpoly(y) == Poly((y - 1)**3, y)
405
+ assert m.charpoly() == Poly(x**3 - 15*x**2 - 18*x, x)
406
+ raises(NonSquareMatrixError, lambda: Matrix([[1], [2]]).charpoly())
407
+ n = Matrix(4, 4, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
408
+ assert n.charpoly() == Poly(x**4, x)
409
+
410
+ n = Matrix(4, 4, [45, 0, 0, 0, 0, 23, 0, 0, 0, 0, 87, 0, 0, 0, 0, 12])
411
+ assert n.charpoly() == Poly(x**4 - 167*x**3 + 8811*x**2 - 173457*x + 1080540, x)
412
+
413
+ n = Matrix(3, 3, [x, 0, 0, a, y, 0, b, c, z])
414
+ assert n.charpoly() == Poly(t**3 - (x+y+z)*t**2 + t*(x*y+y*z+x*z) - x*y*z, t)
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc ADDED
Binary file (3.69 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc ADDED
Binary file (8.49 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc ADDED
Binary file (51.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc ADDED
Binary file (73.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc ADDED
Binary file (737 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc ADDED
Binary file (34.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc ADDED
Binary file (7.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc ADDED
Binary file (57.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc ADDED
Binary file (19.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc ADDED
Binary file (602 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc ADDED
Binary file (33.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/combsimp.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Mul
2
+ from sympy.core.function import count_ops
3
+ from sympy.core.traversal import preorder_traversal, bottom_up
4
+ from sympy.functions.combinatorial.factorials import binomial, factorial
5
+ from sympy.functions import gamma
6
+ from sympy.simplify.gammasimp import gammasimp, _gammasimp
7
+
8
+ from sympy.utilities.timeutils import timethis
9
+
10
+
11
+ @timethis('combsimp')
12
+ def combsimp(expr):
13
+ r"""
14
+ Simplify combinatorial expressions.
15
+
16
+ Explanation
17
+ ===========
18
+
19
+ This function takes as input an expression containing factorials,
20
+ binomials, Pochhammer symbol and other "combinatorial" functions,
21
+ and tries to minimize the number of those functions and reduce
22
+ the size of their arguments.
23
+
24
+ The algorithm works by rewriting all combinatorial functions as
25
+ gamma functions and applying gammasimp() except simplification
26
+ steps that may make an integer argument non-integer. See docstring
27
+ of gammasimp for more information.
28
+
29
+ Then it rewrites expression in terms of factorials and binomials by
30
+ rewriting gammas as factorials and converting (a+b)!/a!b! into
31
+ binomials.
32
+
33
+ If expression has gamma functions or combinatorial functions
34
+ with non-integer argument, it is automatically passed to gammasimp.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.simplify import combsimp
40
+ >>> from sympy import factorial, binomial, symbols
41
+ >>> n, k = symbols('n k', integer = True)
42
+
43
+ >>> combsimp(factorial(n)/factorial(n - 3))
44
+ n*(n - 2)*(n - 1)
45
+ >>> combsimp(binomial(n+1, k+1)/binomial(n, k))
46
+ (n + 1)/(k + 1)
47
+
48
+ """
49
+
50
+ expr = expr.rewrite(gamma, piecewise=False)
51
+ if any(isinstance(node, gamma) and not node.args[0].is_integer
52
+ for node in preorder_traversal(expr)):
53
+ return gammasimp(expr);
54
+
55
+ expr = _gammasimp(expr, as_comb = True)
56
+ expr = _gamma_as_comb(expr)
57
+ return expr
58
+
59
+
60
+ def _gamma_as_comb(expr):
61
+ """
62
+ Helper function for combsimp.
63
+
64
+ Rewrites expression in terms of factorials and binomials
65
+ """
66
+
67
+ expr = expr.rewrite(factorial)
68
+
69
+ def f(rv):
70
+ if not rv.is_Mul:
71
+ return rv
72
+ rvd = rv.as_powers_dict()
73
+ nd_fact_args = [[], []] # numerator, denominator
74
+
75
+ for k in rvd:
76
+ if isinstance(k, factorial) and rvd[k].is_Integer:
77
+ if rvd[k].is_positive:
78
+ nd_fact_args[0].extend([k.args[0]]*rvd[k])
79
+ else:
80
+ nd_fact_args[1].extend([k.args[0]]*-rvd[k])
81
+ rvd[k] = 0
82
+ if not nd_fact_args[0] or not nd_fact_args[1]:
83
+ return rv
84
+
85
+ hit = False
86
+ for m in range(2):
87
+ i = 0
88
+ while i < len(nd_fact_args[m]):
89
+ ai = nd_fact_args[m][i]
90
+ for j in range(i + 1, len(nd_fact_args[m])):
91
+ aj = nd_fact_args[m][j]
92
+
93
+ sum = ai + aj
94
+ if sum in nd_fact_args[1 - m]:
95
+ hit = True
96
+
97
+ nd_fact_args[1 - m].remove(sum)
98
+ del nd_fact_args[m][j]
99
+ del nd_fact_args[m][i]
100
+
101
+ rvd[binomial(sum, ai if count_ops(ai) <
102
+ count_ops(aj) else aj)] += (
103
+ -1 if m == 0 else 1)
104
+ break
105
+ else:
106
+ i += 1
107
+
108
+ if hit:
109
+ return Mul(*([k**rvd[k] for k in rvd] + [factorial(k)
110
+ for k in nd_fact_args[0]]))/Mul(*[factorial(k)
111
+ for k in nd_fact_args[1]])
112
+ return rv
113
+
114
+ return bottom_up(expr, f)
env-llmeval/lib/python3.10/site-packages/sympy/simplify/cse_opts.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Optimizations of the expression tree representation for better CSE
2
+ opportunities.
3
+ """
4
+ from sympy.core import Add, Basic, Mul
5
+ from sympy.core.singleton import S
6
+ from sympy.core.sorting import default_sort_key
7
+ from sympy.core.traversal import preorder_traversal
8
+
9
+
10
+ def sub_pre(e):
11
+ """ Replace y - x with -(x - y) if -1 can be extracted from y - x.
12
+ """
13
+ # replacing Add, A, from which -1 can be extracted with -1*-A
14
+ adds = [a for a in e.atoms(Add) if a.could_extract_minus_sign()]
15
+ reps = {}
16
+ ignore = set()
17
+ for a in adds:
18
+ na = -a
19
+ if na.is_Mul: # e.g. MatExpr
20
+ ignore.add(a)
21
+ continue
22
+ reps[a] = Mul._from_args([S.NegativeOne, na])
23
+
24
+ e = e.xreplace(reps)
25
+
26
+ # repeat again for persisting Adds but mark these with a leading 1, -1
27
+ # e.g. y - x -> 1*-1*(x - y)
28
+ if isinstance(e, Basic):
29
+ negs = {}
30
+ for a in sorted(e.atoms(Add), key=default_sort_key):
31
+ if a in ignore:
32
+ continue
33
+ if a in reps:
34
+ negs[a] = reps[a]
35
+ elif a.could_extract_minus_sign():
36
+ negs[a] = Mul._from_args([S.One, S.NegativeOne, -a])
37
+ e = e.xreplace(negs)
38
+ return e
39
+
40
+
41
+ def sub_post(e):
42
+ """ Replace 1*-1*x with -x.
43
+ """
44
+ replacements = []
45
+ for node in preorder_traversal(e):
46
+ if isinstance(node, Mul) and \
47
+ node.args[0] is S.One and node.args[1] is S.NegativeOne:
48
+ replacements.append((node, -Mul._from_args(node.args[2:])))
49
+ for node, replacement in replacements:
50
+ e = e.xreplace({node: replacement})
51
+
52
+ return e
env-llmeval/lib/python3.10/site-packages/sympy/simplify/epathtools.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for manipulation of expressions using paths. """
2
+
3
+ from sympy.core import Basic
4
+
5
+
6
+ class EPath:
7
+ r"""
8
+ Manipulate expressions using paths.
9
+
10
+ EPath grammar in EBNF notation::
11
+
12
+ literal ::= /[A-Za-z_][A-Za-z_0-9]*/
13
+ number ::= /-?\d+/
14
+ type ::= literal
15
+ attribute ::= literal "?"
16
+ all ::= "*"
17
+ slice ::= "[" number? (":" number? (":" number?)?)? "]"
18
+ range ::= all | slice
19
+ query ::= (type | attribute) ("|" (type | attribute))*
20
+ selector ::= range | query range?
21
+ path ::= "/" selector ("/" selector)*
22
+
23
+ See the docstring of the epath() function.
24
+
25
+ """
26
+
27
+ __slots__ = ("_path", "_epath")
28
+
29
+ def __new__(cls, path):
30
+ """Construct new EPath. """
31
+ if isinstance(path, EPath):
32
+ return path
33
+
34
+ if not path:
35
+ raise ValueError("empty EPath")
36
+
37
+ _path = path
38
+
39
+ if path[0] == '/':
40
+ path = path[1:]
41
+ else:
42
+ raise NotImplementedError("non-root EPath")
43
+
44
+ epath = []
45
+
46
+ for selector in path.split('/'):
47
+ selector = selector.strip()
48
+
49
+ if not selector:
50
+ raise ValueError("empty selector")
51
+
52
+ index = 0
53
+
54
+ for c in selector:
55
+ if c.isalnum() or c in ('_', '|', '?'):
56
+ index += 1
57
+ else:
58
+ break
59
+
60
+ attrs = []
61
+ types = []
62
+
63
+ if index:
64
+ elements = selector[:index]
65
+ selector = selector[index:]
66
+
67
+ for element in elements.split('|'):
68
+ element = element.strip()
69
+
70
+ if not element:
71
+ raise ValueError("empty element")
72
+
73
+ if element.endswith('?'):
74
+ attrs.append(element[:-1])
75
+ else:
76
+ types.append(element)
77
+
78
+ span = None
79
+
80
+ if selector == '*':
81
+ pass
82
+ else:
83
+ if selector.startswith('['):
84
+ try:
85
+ i = selector.index(']')
86
+ except ValueError:
87
+ raise ValueError("expected ']', got EOL")
88
+
89
+ _span, span = selector[1:i], []
90
+
91
+ if ':' not in _span:
92
+ span = int(_span)
93
+ else:
94
+ for elt in _span.split(':', 3):
95
+ if not elt:
96
+ span.append(None)
97
+ else:
98
+ span.append(int(elt))
99
+
100
+ span = slice(*span)
101
+
102
+ selector = selector[i + 1:]
103
+
104
+ if selector:
105
+ raise ValueError("trailing characters in selector")
106
+
107
+ epath.append((attrs, types, span))
108
+
109
+ obj = object.__new__(cls)
110
+
111
+ obj._path = _path
112
+ obj._epath = epath
113
+
114
+ return obj
115
+
116
+ def __repr__(self):
117
+ return "%s(%r)" % (self.__class__.__name__, self._path)
118
+
119
+ def _get_ordered_args(self, expr):
120
+ """Sort ``expr.args`` using printing order. """
121
+ if expr.is_Add:
122
+ return expr.as_ordered_terms()
123
+ elif expr.is_Mul:
124
+ return expr.as_ordered_factors()
125
+ else:
126
+ return expr.args
127
+
128
+ def _hasattrs(self, expr, attrs):
129
+ """Check if ``expr`` has any of ``attrs``. """
130
+ for attr in attrs:
131
+ if not hasattr(expr, attr):
132
+ return False
133
+
134
+ return True
135
+
136
+ def _hastypes(self, expr, types):
137
+ """Check if ``expr`` is any of ``types``. """
138
+ _types = [ cls.__name__ for cls in expr.__class__.mro() ]
139
+ return bool(set(_types).intersection(types))
140
+
141
+ def _has(self, expr, attrs, types):
142
+ """Apply ``_hasattrs`` and ``_hastypes`` to ``expr``. """
143
+ if not (attrs or types):
144
+ return True
145
+
146
+ if attrs and self._hasattrs(expr, attrs):
147
+ return True
148
+
149
+ if types and self._hastypes(expr, types):
150
+ return True
151
+
152
+ return False
153
+
154
+ def apply(self, expr, func, args=None, kwargs=None):
155
+ """
156
+ Modify parts of an expression selected by a path.
157
+
158
+ Examples
159
+ ========
160
+
161
+ >>> from sympy.simplify.epathtools import EPath
162
+ >>> from sympy import sin, cos, E
163
+ >>> from sympy.abc import x, y, z, t
164
+
165
+ >>> path = EPath("/*/[0]/Symbol")
166
+ >>> expr = [((x, 1), 2), ((3, y), z)]
167
+
168
+ >>> path.apply(expr, lambda expr: expr**2)
169
+ [((x**2, 1), 2), ((3, y**2), z)]
170
+
171
+ >>> path = EPath("/*/*/Symbol")
172
+ >>> expr = t + sin(x + 1) + cos(x + y + E)
173
+
174
+ >>> path.apply(expr, lambda expr: 2*expr)
175
+ t + sin(2*x + 1) + cos(2*x + 2*y + E)
176
+
177
+ """
178
+ def _apply(path, expr, func):
179
+ if not path:
180
+ return func(expr)
181
+ else:
182
+ selector, path = path[0], path[1:]
183
+ attrs, types, span = selector
184
+
185
+ if isinstance(expr, Basic):
186
+ if not expr.is_Atom:
187
+ args, basic = self._get_ordered_args(expr), True
188
+ else:
189
+ return expr
190
+ elif hasattr(expr, '__iter__'):
191
+ args, basic = expr, False
192
+ else:
193
+ return expr
194
+
195
+ args = list(args)
196
+
197
+ if span is not None:
198
+ if isinstance(span, slice):
199
+ indices = range(*span.indices(len(args)))
200
+ else:
201
+ indices = [span]
202
+ else:
203
+ indices = range(len(args))
204
+
205
+ for i in indices:
206
+ try:
207
+ arg = args[i]
208
+ except IndexError:
209
+ continue
210
+
211
+ if self._has(arg, attrs, types):
212
+ args[i] = _apply(path, arg, func)
213
+
214
+ if basic:
215
+ return expr.func(*args)
216
+ else:
217
+ return expr.__class__(args)
218
+
219
+ _args, _kwargs = args or (), kwargs or {}
220
+ _func = lambda expr: func(expr, *_args, **_kwargs)
221
+
222
+ return _apply(self._epath, expr, _func)
223
+
224
+ def select(self, expr):
225
+ """
226
+ Retrieve parts of an expression selected by a path.
227
+
228
+ Examples
229
+ ========
230
+
231
+ >>> from sympy.simplify.epathtools import EPath
232
+ >>> from sympy import sin, cos, E
233
+ >>> from sympy.abc import x, y, z, t
234
+
235
+ >>> path = EPath("/*/[0]/Symbol")
236
+ >>> expr = [((x, 1), 2), ((3, y), z)]
237
+
238
+ >>> path.select(expr)
239
+ [x, y]
240
+
241
+ >>> path = EPath("/*/*/Symbol")
242
+ >>> expr = t + sin(x + 1) + cos(x + y + E)
243
+
244
+ >>> path.select(expr)
245
+ [x, x, y]
246
+
247
+ """
248
+ result = []
249
+
250
+ def _select(path, expr):
251
+ if not path:
252
+ result.append(expr)
253
+ else:
254
+ selector, path = path[0], path[1:]
255
+ attrs, types, span = selector
256
+
257
+ if isinstance(expr, Basic):
258
+ args = self._get_ordered_args(expr)
259
+ elif hasattr(expr, '__iter__'):
260
+ args = expr
261
+ else:
262
+ return
263
+
264
+ if span is not None:
265
+ if isinstance(span, slice):
266
+ args = args[span]
267
+ else:
268
+ try:
269
+ args = [args[span]]
270
+ except IndexError:
271
+ return
272
+
273
+ for arg in args:
274
+ if self._has(arg, attrs, types):
275
+ _select(path, arg)
276
+
277
+ _select(self._epath, expr)
278
+ return result
279
+
280
+
281
+ def epath(path, expr=None, func=None, args=None, kwargs=None):
282
+ r"""
283
+ Manipulate parts of an expression selected by a path.
284
+
285
+ Explanation
286
+ ===========
287
+
288
+ This function allows to manipulate large nested expressions in single
289
+ line of code, utilizing techniques to those applied in XML processing
290
+ standards (e.g. XPath).
291
+
292
+ If ``func`` is ``None``, :func:`epath` retrieves elements selected by
293
+ the ``path``. Otherwise it applies ``func`` to each matching element.
294
+
295
+ Note that it is more efficient to create an EPath object and use the select
296
+ and apply methods of that object, since this will compile the path string
297
+ only once. This function should only be used as a convenient shortcut for
298
+ interactive use.
299
+
300
+ This is the supported syntax:
301
+
302
+ * select all: ``/*``
303
+ Equivalent of ``for arg in args:``.
304
+ * select slice: ``/[0]`` or ``/[1:5]`` or ``/[1:5:2]``
305
+ Supports standard Python's slice syntax.
306
+ * select by type: ``/list`` or ``/list|tuple``
307
+ Emulates ``isinstance()``.
308
+ * select by attribute: ``/__iter__?``
309
+ Emulates ``hasattr()``.
310
+
311
+ Parameters
312
+ ==========
313
+
314
+ path : str | EPath
315
+ A path as a string or a compiled EPath.
316
+ expr : Basic | iterable
317
+ An expression or a container of expressions.
318
+ func : callable (optional)
319
+ A callable that will be applied to matching parts.
320
+ args : tuple (optional)
321
+ Additional positional arguments to ``func``.
322
+ kwargs : dict (optional)
323
+ Additional keyword arguments to ``func``.
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.simplify.epathtools import epath
329
+ >>> from sympy import sin, cos, E
330
+ >>> from sympy.abc import x, y, z, t
331
+
332
+ >>> path = "/*/[0]/Symbol"
333
+ >>> expr = [((x, 1), 2), ((3, y), z)]
334
+
335
+ >>> epath(path, expr)
336
+ [x, y]
337
+ >>> epath(path, expr, lambda expr: expr**2)
338
+ [((x**2, 1), 2), ((3, y**2), z)]
339
+
340
+ >>> path = "/*/*/Symbol"
341
+ >>> expr = t + sin(x + 1) + cos(x + y + E)
342
+
343
+ >>> epath(path, expr)
344
+ [x, x, y]
345
+ >>> epath(path, expr, lambda expr: 2*expr)
346
+ t + sin(2*x + 1) + cos(2*x + 2*y + E)
347
+
348
+ """
349
+ _epath = EPath(path)
350
+
351
+ if expr is None:
352
+ return _epath
353
+ if func is None:
354
+ return _epath.select(expr)
355
+ else:
356
+ return _epath.apply(expr, func, args, kwargs)
env-llmeval/lib/python3.10/site-packages/sympy/simplify/powsimp.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ from functools import reduce
3
+ from math import prod
4
+
5
+ from sympy.core.function import expand_log, count_ops, _coeff_isneg
6
+ from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms
7
+ from sympy.core.sorting import ordered, default_sort_key
8
+ from sympy.core.numbers import Integer, Rational
9
+ from sympy.core.mul import _keep_coeff
10
+ from sympy.core.rules import Transform
11
+ from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify
12
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
13
+ from sympy.polys import lcm, gcd
14
+ from sympy.ntheory.factor_ import multiplicity
15
+
16
+
17
+
18
+ def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops):
19
+ """
20
+ Reduce expression by combining powers with similar bases and exponents.
21
+
22
+ Explanation
23
+ ===========
24
+
25
+ If ``deep`` is ``True`` then powsimp() will also simplify arguments of
26
+ functions. By default ``deep`` is set to ``False``.
27
+
28
+ If ``force`` is ``True`` then bases will be combined without checking for
29
+ assumptions, e.g. sqrt(x)*sqrt(y) -> sqrt(x*y) which is not true
30
+ if x and y are both negative.
31
+
32
+ You can make powsimp() only combine bases or only combine exponents by
33
+ changing combine='base' or combine='exp'. By default, combine='all',
34
+ which does both. combine='base' will only combine::
35
+
36
+ a a a 2x x
37
+ x * y => (x*y) as well as things like 2 => 4
38
+
39
+ and combine='exp' will only combine
40
+ ::
41
+
42
+ a b (a + b)
43
+ x * x => x
44
+
45
+ combine='exp' will strictly only combine exponents in the way that used
46
+ to be automatic. Also use deep=True if you need the old behavior.
47
+
48
+ When combine='all', 'exp' is evaluated first. Consider the first
49
+ example below for when there could be an ambiguity relating to this.
50
+ This is done so things like the second example can be completely
51
+ combined. If you want 'base' combined first, do something like
52
+ powsimp(powsimp(expr, combine='base'), combine='exp').
53
+
54
+ Examples
55
+ ========
56
+
57
+ >>> from sympy import powsimp, exp, log, symbols
58
+ >>> from sympy.abc import x, y, z, n
59
+ >>> powsimp(x**y*x**z*y**z, combine='all')
60
+ x**(y + z)*y**z
61
+ >>> powsimp(x**y*x**z*y**z, combine='exp')
62
+ x**(y + z)*y**z
63
+ >>> powsimp(x**y*x**z*y**z, combine='base', force=True)
64
+ x**y*(x*y)**z
65
+
66
+ >>> powsimp(x**z*x**y*n**z*n**y, combine='all', force=True)
67
+ (n*x)**(y + z)
68
+ >>> powsimp(x**z*x**y*n**z*n**y, combine='exp')
69
+ n**(y + z)*x**(y + z)
70
+ >>> powsimp(x**z*x**y*n**z*n**y, combine='base', force=True)
71
+ (n*x)**y*(n*x)**z
72
+
73
+ >>> x, y = symbols('x y', positive=True)
74
+ >>> powsimp(log(exp(x)*exp(y)))
75
+ log(exp(x)*exp(y))
76
+ >>> powsimp(log(exp(x)*exp(y)), deep=True)
77
+ x + y
78
+
79
+ Radicals with Mul bases will be combined if combine='exp'
80
+
81
+ >>> from sympy import sqrt
82
+ >>> x, y = symbols('x y')
83
+
84
+ Two radicals are automatically joined through Mul:
85
+
86
+ >>> a=sqrt(x*sqrt(y))
87
+ >>> a*a**3 == a**4
88
+ True
89
+
90
+ But if an integer power of that radical has been
91
+ autoexpanded then Mul does not join the resulting factors:
92
+
93
+ >>> a**4 # auto expands to a Mul, no longer a Pow
94
+ x**2*y
95
+ >>> _*a # so Mul doesn't combine them
96
+ x**2*y*sqrt(x*sqrt(y))
97
+ >>> powsimp(_) # but powsimp will
98
+ (x*sqrt(y))**(5/2)
99
+ >>> powsimp(x*y*a) # but won't when doing so would violate assumptions
100
+ x*y*sqrt(x*sqrt(y))
101
+
102
+ """
103
+ def recurse(arg, **kwargs):
104
+ _deep = kwargs.get('deep', deep)
105
+ _combine = kwargs.get('combine', combine)
106
+ _force = kwargs.get('force', force)
107
+ _measure = kwargs.get('measure', measure)
108
+ return powsimp(arg, _deep, _combine, _force, _measure)
109
+
110
+ expr = sympify(expr)
111
+
112
+ if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or (
113
+ expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))):
114
+ return expr
115
+
116
+ if deep or expr.is_Add or expr.is_Mul and _y not in expr.args:
117
+ expr = expr.func(*[recurse(w) for w in expr.args])
118
+
119
+ if expr.is_Pow:
120
+ return recurse(expr*_y, deep=False)/_y
121
+
122
+ if not expr.is_Mul:
123
+ return expr
124
+
125
+ # handle the Mul
126
+ if combine in ('exp', 'all'):
127
+ # Collect base/exp data, while maintaining order in the
128
+ # non-commutative parts of the product
129
+ c_powers = defaultdict(list)
130
+ nc_part = []
131
+ newexpr = []
132
+ coeff = S.One
133
+ for term in expr.args:
134
+ if term.is_Rational:
135
+ coeff *= term
136
+ continue
137
+ if term.is_Pow:
138
+ term = _denest_pow(term)
139
+ if term.is_commutative:
140
+ b, e = term.as_base_exp()
141
+ if deep:
142
+ b, e = [recurse(i) for i in [b, e]]
143
+ if b.is_Pow or isinstance(b, exp):
144
+ # don't let smthg like sqrt(x**a) split into x**a, 1/2
145
+ # or else it will be joined as x**(a/2) later
146
+ b, e = b**e, S.One
147
+ c_powers[b].append(e)
148
+ else:
149
+ # This is the logic that combines exponents for equal,
150
+ # but non-commutative bases: A**x*A**y == A**(x+y).
151
+ if nc_part:
152
+ b1, e1 = nc_part[-1].as_base_exp()
153
+ b2, e2 = term.as_base_exp()
154
+ if (b1 == b2 and
155
+ e1.is_commutative and e2.is_commutative):
156
+ nc_part[-1] = Pow(b1, Add(e1, e2))
157
+ continue
158
+ nc_part.append(term)
159
+
160
+ # add up exponents of common bases
161
+ for b, e in ordered(iter(c_powers.items())):
162
+ # allow 2**x/4 -> 2**(x - 2); don't do this when b and e are
163
+ # Numbers since autoevaluation will undo it, e.g.
164
+ # 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4
165
+ if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \
166
+ coeff is not S.One and
167
+ b not in (S.One, S.NegativeOne)):
168
+ m = multiplicity(abs(b), abs(coeff))
169
+ if m:
170
+ e.append(m)
171
+ coeff /= b**m
172
+ c_powers[b] = Add(*e)
173
+ if coeff is not S.One:
174
+ if coeff in c_powers:
175
+ c_powers[coeff] += S.One
176
+ else:
177
+ c_powers[coeff] = S.One
178
+
179
+ # convert to plain dictionary
180
+ c_powers = dict(c_powers)
181
+
182
+ # check for base and inverted base pairs
183
+ be = list(c_powers.items())
184
+ skip = set() # skip if we already saw them
185
+ for b, e in be:
186
+ if b in skip:
187
+ continue
188
+ bpos = b.is_positive or b.is_polar
189
+ if bpos:
190
+ binv = 1/b
191
+ if b != binv and binv in c_powers:
192
+ if b.as_numer_denom()[0] is S.One:
193
+ c_powers.pop(b)
194
+ c_powers[binv] -= e
195
+ else:
196
+ skip.add(binv)
197
+ e = c_powers.pop(binv)
198
+ c_powers[b] -= e
199
+
200
+ # check for base and negated base pairs
201
+ be = list(c_powers.items())
202
+ _n = S.NegativeOne
203
+ for b, e in be:
204
+ if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers:
205
+ if (b.is_positive is not None or e.is_integer):
206
+ if e.is_integer or b.is_negative:
207
+ c_powers[-b] += c_powers.pop(b)
208
+ else: # (-b).is_positive so use its e
209
+ e = c_powers.pop(-b)
210
+ c_powers[b] += e
211
+ if _n in c_powers:
212
+ c_powers[_n] += e
213
+ else:
214
+ c_powers[_n] = e
215
+
216
+ # filter c_powers and convert to a list
217
+ c_powers = [(b, e) for b, e in c_powers.items() if e]
218
+
219
+ # ==============================================================
220
+ # check for Mul bases of Rational powers that can be combined with
221
+ # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) ->
222
+ # (x*sqrt(x*y))**(3/2)
223
+ # ---------------- helper functions
224
+
225
+ def ratq(x):
226
+ '''Return Rational part of x's exponent as it appears in the bkey.
227
+ '''
228
+ return bkey(x)[0][1]
229
+
230
+ def bkey(b, e=None):
231
+ '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then
232
+ it will be taken by using as_base_exp() on the input b.
233
+ e.g.
234
+ x**3/2 -> (x, 2), 3
235
+ x**y -> (x**y, 1), 1
236
+ x**(2*y/3) -> (x**y, 3), 2
237
+ exp(x/2) -> (exp(a), 2), 1
238
+
239
+ '''
240
+ if e is not None: # coming from c_powers or from below
241
+ if e.is_Integer:
242
+ return (b, S.One), e
243
+ elif e.is_Rational:
244
+ return (b, Integer(e.q)), Integer(e.p)
245
+ else:
246
+ c, m = e.as_coeff_Mul(rational=True)
247
+ if c is not S.One:
248
+ if m.is_integer:
249
+ return (b, Integer(c.q)), m*Integer(c.p)
250
+ return (b**m, Integer(c.q)), Integer(c.p)
251
+ else:
252
+ return (b**e, S.One), S.One
253
+ else:
254
+ return bkey(*b.as_base_exp())
255
+
256
+ def update(b):
257
+ '''Decide what to do with base, b. If its exponent is now an
258
+ integer multiple of the Rational denominator, then remove it
259
+ and put the factors of its base in the common_b dictionary or
260
+ update the existing bases if necessary. If it has been zeroed
261
+ out, simply remove the base.
262
+ '''
263
+ newe, r = divmod(common_b[b], b[1])
264
+ if not r:
265
+ common_b.pop(b)
266
+ if newe:
267
+ for m in Mul.make_args(b[0]**newe):
268
+ b, e = bkey(m)
269
+ if b not in common_b:
270
+ common_b[b] = 0
271
+ common_b[b] += e
272
+ if b[1] != 1:
273
+ bases.append(b)
274
+ # ---------------- end of helper functions
275
+
276
+ # assemble a dictionary of the factors having a Rational power
277
+ common_b = {}
278
+ done = []
279
+ bases = []
280
+ for b, e in c_powers:
281
+ b, e = bkey(b, e)
282
+ if b in common_b:
283
+ common_b[b] = common_b[b] + e
284
+ else:
285
+ common_b[b] = e
286
+ if b[1] != 1 and b[0].is_Mul:
287
+ bases.append(b)
288
+ bases.sort(key=default_sort_key) # this makes tie-breaking canonical
289
+ bases.sort(key=measure, reverse=True) # handle longest first
290
+ for base in bases:
291
+ if base not in common_b: # it may have been removed already
292
+ continue
293
+ b, exponent = base
294
+ last = False # True when no factor of base is a radical
295
+ qlcm = 1 # the lcm of the radical denominators
296
+ while True:
297
+ bstart = b
298
+ qstart = qlcm
299
+
300
+ bb = [] # list of factors
301
+ ee = [] # (factor's expo. and it's current value in common_b)
302
+ for bi in Mul.make_args(b):
303
+ bib, bie = bkey(bi)
304
+ if bib not in common_b or common_b[bib] < bie:
305
+ ee = bb = [] # failed
306
+ break
307
+ ee.append([bie, common_b[bib]])
308
+ bb.append(bib)
309
+ if ee:
310
+ # find the number of integral extractions possible
311
+ # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1
312
+ min1 = ee[0][1]//ee[0][0]
313
+ for i in range(1, len(ee)):
314
+ rat = ee[i][1]//ee[i][0]
315
+ if rat < 1:
316
+ break
317
+ min1 = min(min1, rat)
318
+ else:
319
+ # update base factor counts
320
+ # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2
321
+ # and the new base counts will be 5-2*2 and 6-2*3
322
+ for i in range(len(bb)):
323
+ common_b[bb[i]] -= min1*ee[i][0]
324
+ update(bb[i])
325
+ # update the count of the base
326
+ # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y)
327
+ # will increase by 4 to give bkey (x*sqrt(y), 2, 5)
328
+ common_b[base] += min1*qstart*exponent
329
+ if (last # no more radicals in base
330
+ or len(common_b) == 1 # nothing left to join with
331
+ or all(k[1] == 1 for k in common_b) # no rad's in common_b
332
+ ):
333
+ break
334
+ # see what we can exponentiate base by to remove any radicals
335
+ # so we know what to search for
336
+ # e.g. if base were x**(1/2)*y**(1/3) then we should
337
+ # exponentiate by 6 and look for powers of x and y in the ratio
338
+ # of 2 to 3
339
+ qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)])
340
+ if qlcm == 1:
341
+ break # we are done
342
+ b = bstart**qlcm
343
+ qlcm *= qstart
344
+ if all(ratq(bi) == 1 for bi in Mul.make_args(b)):
345
+ last = True # we are going to be done after this next pass
346
+ # this base no longer can find anything to join with and
347
+ # since it was longer than any other we are done with it
348
+ b, q = base
349
+ done.append((b, common_b.pop(base)*Rational(1, q)))
350
+
351
+ # update c_powers and get ready to continue with powsimp
352
+ c_powers = done
353
+ # there may be terms still in common_b that were bases that were
354
+ # identified as needing processing, so remove those, too
355
+ for (b, q), e in common_b.items():
356
+ if (b.is_Pow or isinstance(b, exp)) and \
357
+ q is not S.One and not b.exp.is_Rational:
358
+ b, be = b.as_base_exp()
359
+ b = b**(be/q)
360
+ else:
361
+ b = root(b, q)
362
+ c_powers.append((b, e))
363
+ check = len(c_powers)
364
+ c_powers = dict(c_powers)
365
+ assert len(c_powers) == check # there should have been no duplicates
366
+ # ==============================================================
367
+
368
+ # rebuild the expression
369
+ newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()]))
370
+ if combine == 'exp':
371
+ return expr.func(newexpr, expr.func(*nc_part))
372
+ else:
373
+ return recurse(expr.func(*nc_part), combine='base') * \
374
+ recurse(newexpr, combine='base')
375
+
376
+ elif combine == 'base':
377
+
378
+ # Build c_powers and nc_part. These must both be lists not
379
+ # dicts because exp's are not combined.
380
+ c_powers = []
381
+ nc_part = []
382
+ for term in expr.args:
383
+ if term.is_commutative:
384
+ c_powers.append(list(term.as_base_exp()))
385
+ else:
386
+ nc_part.append(term)
387
+
388
+ # Pull out numerical coefficients from exponent if assumptions allow
389
+ # e.g., 2**(2*x) => 4**x
390
+ for i in range(len(c_powers)):
391
+ b, e = c_powers[i]
392
+ if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar):
393
+ continue
394
+ exp_c, exp_t = e.as_coeff_Mul(rational=True)
395
+ if exp_c is not S.One and exp_t is not S.One:
396
+ c_powers[i] = [Pow(b, exp_c), exp_t]
397
+
398
+ # Combine bases whenever they have the same exponent and
399
+ # assumptions allow
400
+ # first gather the potential bases under the common exponent
401
+ c_exp = defaultdict(list)
402
+ for b, e in c_powers:
403
+ if deep:
404
+ e = recurse(e)
405
+ if e.is_Add and (b.is_positive or e.is_integer):
406
+ e = factor_terms(e)
407
+ if _coeff_isneg(e):
408
+ e = -e
409
+ b = 1/b
410
+ c_exp[e].append(b)
411
+ del c_powers
412
+
413
+ # Merge back in the results of the above to form a new product
414
+ c_powers = defaultdict(list)
415
+ for e in c_exp:
416
+ bases = c_exp[e]
417
+
418
+ # calculate the new base for e
419
+
420
+ if len(bases) == 1:
421
+ new_base = bases[0]
422
+ elif e.is_integer or force:
423
+ new_base = expr.func(*bases)
424
+ else:
425
+ # see which ones can be joined
426
+ unk = []
427
+ nonneg = []
428
+ neg = []
429
+ for bi in bases:
430
+ if bi.is_negative:
431
+ neg.append(bi)
432
+ elif bi.is_nonnegative:
433
+ nonneg.append(bi)
434
+ elif bi.is_polar:
435
+ nonneg.append(
436
+ bi) # polar can be treated like non-negative
437
+ else:
438
+ unk.append(bi)
439
+ if len(unk) == 1 and not neg or len(neg) == 1 and not unk:
440
+ # a single neg or a single unk can join the rest
441
+ nonneg.extend(unk + neg)
442
+ unk = neg = []
443
+ elif neg:
444
+ # their negative signs cancel in groups of 2*q if we know
445
+ # that e = p/q else we have to treat them as unknown
446
+ israt = False
447
+ if e.is_Rational:
448
+ israt = True
449
+ else:
450
+ p, d = e.as_numer_denom()
451
+ if p.is_integer and d.is_integer:
452
+ israt = True
453
+ if israt:
454
+ neg = [-w for w in neg]
455
+ unk.extend([S.NegativeOne]*len(neg))
456
+ else:
457
+ unk.extend(neg)
458
+ neg = []
459
+ del israt
460
+
461
+ # these shouldn't be joined
462
+ for b in unk:
463
+ c_powers[b].append(e)
464
+ # here is a new joined base
465
+ new_base = expr.func(*(nonneg + neg))
466
+ # if there are positive parts they will just get separated
467
+ # again unless some change is made
468
+
469
+ def _terms(e):
470
+ # return the number of terms of this expression
471
+ # when multiplied out -- assuming no joining of terms
472
+ if e.is_Add:
473
+ return sum([_terms(ai) for ai in e.args])
474
+ if e.is_Mul:
475
+ return prod([_terms(mi) for mi in e.args])
476
+ return 1
477
+ xnew_base = expand_mul(new_base, deep=False)
478
+ if len(Add.make_args(xnew_base)) < _terms(new_base):
479
+ new_base = factor_terms(xnew_base)
480
+
481
+ c_powers[new_base].append(e)
482
+
483
+ # break out the powers from c_powers now
484
+ c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e]
485
+
486
+ # we're done
487
+ return expr.func(*(c_part + nc_part))
488
+
489
+ else:
490
+ raise ValueError("combine must be one of ('all', 'exp', 'base').")
491
+
492
+
493
+ def powdenest(eq, force=False, polar=False):
494
+ r"""
495
+ Collect exponents on powers as assumptions allow.
496
+
497
+ Explanation
498
+ ===========
499
+
500
+ Given ``(bb**be)**e``, this can be simplified as follows:
501
+ * if ``bb`` is positive, or
502
+ * ``e`` is an integer, or
503
+ * ``|be| < 1`` then this simplifies to ``bb**(be*e)``
504
+
505
+ Given a product of powers raised to a power, ``(bb1**be1 *
506
+ bb2**be2...)**e``, simplification can be done as follows:
507
+
508
+ - if e is positive, the gcd of all bei can be joined with e;
509
+ - all non-negative bb can be separated from those that are negative
510
+ and their gcd can be joined with e; autosimplification already
511
+ handles this separation.
512
+ - integer factors from powers that have integers in the denominator
513
+ of the exponent can be removed from any term and the gcd of such
514
+ integers can be joined with e
515
+
516
+ Setting ``force`` to ``True`` will make symbols that are not explicitly
517
+ negative behave as though they are positive, resulting in more
518
+ denesting.
519
+
520
+ Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of
521
+ the logarithm, also resulting in more denestings.
522
+
523
+ When there are sums of logs in exp() then a product of powers may be
524
+ obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``.
525
+
526
+ Examples
527
+ ========
528
+
529
+ >>> from sympy.abc import a, b, x, y, z
530
+ >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest
531
+
532
+ >>> powdenest((x**(2*a/3))**(3*x))
533
+ (x**(2*a/3))**(3*x)
534
+ >>> powdenest(exp(3*x*log(2)))
535
+ 2**(3*x)
536
+
537
+ Assumptions may prevent expansion:
538
+
539
+ >>> powdenest(sqrt(x**2))
540
+ sqrt(x**2)
541
+
542
+ >>> p = symbols('p', positive=True)
543
+ >>> powdenest(sqrt(p**2))
544
+ p
545
+
546
+ No other expansion is done.
547
+
548
+ >>> i, j = symbols('i,j', integer=True)
549
+ >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j
550
+ x**(x*(i + j))
551
+
552
+ But exp() will be denested by moving all non-log terms outside of
553
+ the function; this may result in the collapsing of the exp to a power
554
+ with a different base:
555
+
556
+ >>> powdenest(exp(3*y*log(x)))
557
+ x**(3*y)
558
+ >>> powdenest(exp(y*(log(a) + log(b))))
559
+ (a*b)**y
560
+ >>> powdenest(exp(3*(log(a) + log(b))))
561
+ a**3*b**3
562
+
563
+ If assumptions allow, symbols can also be moved to the outermost exponent:
564
+
565
+ >>> i = Symbol('i', integer=True)
566
+ >>> powdenest(((x**(2*i))**(3*y))**x)
567
+ ((x**(2*i))**(3*y))**x
568
+ >>> powdenest(((x**(2*i))**(3*y))**x, force=True)
569
+ x**(6*i*x*y)
570
+
571
+ >>> powdenest(((x**(2*a/3))**(3*y/i))**x)
572
+ ((x**(2*a/3))**(3*y/i))**x
573
+ >>> powdenest((x**(2*i)*y**(4*i))**z, force=True)
574
+ (x*y**2)**(2*i*z)
575
+
576
+ >>> n = Symbol('n', negative=True)
577
+
578
+ >>> powdenest((x**i)**y, force=True)
579
+ x**(i*y)
580
+ >>> powdenest((n**i)**x, force=True)
581
+ (n**i)**x
582
+
583
+ """
584
+ from sympy.simplify.simplify import posify
585
+
586
+ if force:
587
+ def _denest(b, e):
588
+ if not isinstance(b, (Pow, exp)):
589
+ return b.is_positive, Pow(b, e, evaluate=False)
590
+ return _denest(b.base, b.exp*e)
591
+ reps = []
592
+ for p in eq.atoms(Pow, exp):
593
+ if isinstance(p.base, (Pow, exp)):
594
+ ok, dp = _denest(*p.args)
595
+ if ok is not False:
596
+ reps.append((p, dp))
597
+ if reps:
598
+ eq = eq.subs(reps)
599
+ eq, reps = posify(eq)
600
+ return powdenest(eq, force=False, polar=polar).xreplace(reps)
601
+
602
+ if polar:
603
+ eq, rep = polarify(eq)
604
+ return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep)
605
+
606
+ new = powsimp(eq)
607
+ return new.xreplace(Transform(
608
+ _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp)))
609
+
610
+ _y = Dummy('y')
611
+
612
+
613
+ def _denest_pow(eq):
614
+ """
615
+ Denest powers.
616
+
617
+ This is a helper function for powdenest that performs the actual
618
+ transformation.
619
+ """
620
+ from sympy.simplify.simplify import logcombine
621
+
622
+ b, e = eq.as_base_exp()
623
+ if b.is_Pow or isinstance(b, exp) and e != 1:
624
+ new = b._eval_power(e)
625
+ if new is not None:
626
+ eq = new
627
+ b, e = new.as_base_exp()
628
+
629
+ # denest exp with log terms in exponent
630
+ if b is S.Exp1 and e.is_Mul:
631
+ logs = []
632
+ other = []
633
+ for ei in e.args:
634
+ if any(isinstance(ai, log) for ai in Add.make_args(ei)):
635
+ logs.append(ei)
636
+ else:
637
+ other.append(ei)
638
+ logs = logcombine(Mul(*logs))
639
+ return Pow(exp(logs), Mul(*other))
640
+
641
+ _, be = b.as_base_exp()
642
+ if be is S.One and not (b.is_Mul or
643
+ b.is_Rational and b.q != 1 or
644
+ b.is_positive):
645
+ return eq
646
+
647
+ # denest eq which is either pos**e or Pow**e or Mul**e or
648
+ # Mul(b1**e1, b2**e2)
649
+
650
+ # handle polar numbers specially
651
+ polars, nonpolars = [], []
652
+ for bb in Mul.make_args(b):
653
+ if bb.is_polar:
654
+ polars.append(bb.as_base_exp())
655
+ else:
656
+ nonpolars.append(bb)
657
+ if len(polars) == 1 and not polars[0][0].is_Mul:
658
+ return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e)
659
+ elif polars:
660
+ return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \
661
+ *powdenest(Mul(*nonpolars)**e)
662
+
663
+ if b.is_Integer:
664
+ # use log to see if there is a power here
665
+ logb = expand_log(log(b))
666
+ if logb.is_Mul:
667
+ c, logb = logb.args
668
+ e *= c
669
+ base = logb.args[0]
670
+ return Pow(base, e)
671
+
672
+ # if b is not a Mul or any factor is an atom then there is nothing to do
673
+ if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)):
674
+ return eq
675
+
676
+ # let log handle the case of the base of the argument being a Mul, e.g.
677
+ # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we
678
+ # will take the log, expand it, and then factor out the common powers that
679
+ # now appear as coefficient. We do this manually since terms_gcd pulls out
680
+ # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2;
681
+ # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but
682
+ # we want 3*x. Neither work with noncommutatives.
683
+
684
+ def nc_gcd(aa, bb):
685
+ a, b = [i.as_coeff_Mul() for i in [aa, bb]]
686
+ c = gcd(a[0], b[0]).as_numer_denom()[0]
687
+ g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0]))
688
+ return _keep_coeff(c, g)
689
+
690
+ glogb = expand_log(log(b))
691
+ if glogb.is_Add:
692
+ args = glogb.args
693
+ g = reduce(nc_gcd, args)
694
+ if g != 1:
695
+ cg, rg = g.as_coeff_Mul()
696
+ glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args]))
697
+
698
+ # now put the log back together again
699
+ if isinstance(glogb, log) or not glogb.is_Mul:
700
+ if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp):
701
+ glogb = _denest_pow(glogb.args[0])
702
+ if (abs(glogb.exp) < 1) == True:
703
+ return Pow(glogb.base, glogb.exp*e)
704
+ return eq
705
+
706
+ # the log(b) was a Mul so join any adds with logcombine
707
+ add = []
708
+ other = []
709
+ for a in glogb.args:
710
+ if a.is_Add:
711
+ add.append(a)
712
+ else:
713
+ other.append(a)
714
+ return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
env-llmeval/lib/python3.10/site-packages/sympy/simplify/ratsimp.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations_with_replacement
2
+ from sympy.core import symbols, Add, Dummy
3
+ from sympy.core.numbers import Rational
4
+ from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly
5
+ from sympy.polys.monomials import Monomial, monomial_div
6
+ from sympy.polys.polyerrors import DomainError, PolificationFailed
7
+ from sympy.utilities.misc import debug, debugf
8
+
9
+ def ratsimp(expr):
10
+ """
11
+ Put an expression over a common denominator, cancel and reduce.
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy import ratsimp
17
+ >>> from sympy.abc import x, y
18
+ >>> ratsimp(1/x + 1/y)
19
+ (x + y)/(x*y)
20
+ """
21
+
22
+ f, g = cancel(expr).as_numer_denom()
23
+ try:
24
+ Q, r = reduced(f, [g], field=True, expand=False)
25
+ except ComputationFailed:
26
+ return f/g
27
+
28
+ return Add(*Q) + cancel(r/g)
29
+
30
+
31
+ def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args):
32
+ """
33
+ Simplifies a rational expression ``expr`` modulo the prime ideal
34
+ generated by ``G``. ``G`` should be a Groebner basis of the
35
+ ideal.
36
+
37
+ Examples
38
+ ========
39
+
40
+ >>> from sympy.simplify.ratsimp import ratsimpmodprime
41
+ >>> from sympy.abc import x, y
42
+ >>> eq = (x + y**5 + y)/(x - y)
43
+ >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex')
44
+ (-x**2 - x*y - x - y)/(-x**2 + x*y)
45
+
46
+ If ``polynomial`` is ``False``, the algorithm computes a rational
47
+ simplification which minimizes the sum of the total degrees of
48
+ the numerator and the denominator.
49
+
50
+ If ``polynomial`` is ``True``, this function just brings numerator and
51
+ denominator into a canonical form. This is much faster, but has
52
+ potentially worse results.
53
+
54
+ References
55
+ ==========
56
+
57
+ .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial
58
+ Ideal, https://dl.acm.org/doi/pdf/10.1145/1145768.1145809
59
+ (specifically, the second algorithm)
60
+ """
61
+ from sympy.solvers.solvers import solve
62
+
63
+ debug('ratsimpmodprime', expr)
64
+
65
+ # usual preparation of polynomials:
66
+
67
+ num, denom = cancel(expr).as_numer_denom()
68
+
69
+ try:
70
+ polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args)
71
+ except PolificationFailed:
72
+ return expr
73
+
74
+ domain = opt.domain
75
+
76
+ if domain.has_assoc_Field:
77
+ opt.domain = domain.get_field()
78
+ else:
79
+ raise DomainError(
80
+ "Cannot compute rational simplification over %s" % domain)
81
+
82
+ # compute only once
83
+ leading_monomials = [g.LM(opt.order) for g in polys[2:]]
84
+ tested = set()
85
+
86
+ def staircase(n):
87
+ """
88
+ Compute all monomials with degree less than ``n`` that are
89
+ not divisible by any element of ``leading_monomials``.
90
+ """
91
+ if n == 0:
92
+ return [1]
93
+ S = []
94
+ for mi in combinations_with_replacement(range(len(opt.gens)), n):
95
+ m = [0]*len(opt.gens)
96
+ for i in mi:
97
+ m[i] += 1
98
+ if all(monomial_div(m, lmg) is None for lmg in
99
+ leading_monomials):
100
+ S.append(m)
101
+
102
+ return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1)
103
+
104
+ def _ratsimpmodprime(a, b, allsol, N=0, D=0):
105
+ r"""
106
+ Computes a rational simplification of ``a/b`` which minimizes
107
+ the sum of the total degrees of the numerator and the denominator.
108
+
109
+ Explanation
110
+ ===========
111
+
112
+ The algorithm proceeds by looking at ``a * d - b * c`` modulo
113
+ the ideal generated by ``G`` for some ``c`` and ``d`` with degree
114
+ less than ``a`` and ``b`` respectively.
115
+ The coefficients of ``c`` and ``d`` are indeterminates and thus
116
+ the coefficients of the normalform of ``a * d - b * c`` are
117
+ linear polynomials in these indeterminates.
118
+ If these linear polynomials, considered as system of
119
+ equations, have a nontrivial solution, then `\frac{a}{b}
120
+ \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So,
121
+ by construction, the degree of ``c`` and ``d`` is less than
122
+ the degree of ``a`` and ``b``, so a simpler representation
123
+ has been found.
124
+ After a simpler representation has been found, the algorithm
125
+ tries to reduce the degree of the numerator and denominator
126
+ and returns the result afterwards.
127
+
128
+ As an extension, if quick=False, we look at all possible degrees such
129
+ that the total degree is less than *or equal to* the best current
130
+ solution. We retain a list of all solutions of minimal degree, and try
131
+ to find the best one at the end.
132
+ """
133
+ c, d = a, b
134
+ steps = 0
135
+
136
+ maxdeg = a.total_degree() + b.total_degree()
137
+ if quick:
138
+ bound = maxdeg - 1
139
+ else:
140
+ bound = maxdeg
141
+ while N + D <= bound:
142
+ if (N, D) in tested:
143
+ break
144
+ tested.add((N, D))
145
+
146
+ M1 = staircase(N)
147
+ M2 = staircase(D)
148
+ debugf('%s / %s: %s, %s', (N, D, M1, M2))
149
+
150
+ Cs = symbols("c:%d" % len(M1), cls=Dummy)
151
+ Ds = symbols("d:%d" % len(M2), cls=Dummy)
152
+ ng = Cs + Ds
153
+
154
+ c_hat = Poly(
155
+ sum([Cs[i] * M1[i] for i in range(len(M1))]), opt.gens + ng)
156
+ d_hat = Poly(
157
+ sum([Ds[i] * M2[i] for i in range(len(M2))]), opt.gens + ng)
158
+
159
+ r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng,
160
+ order=opt.order, polys=True)[1]
161
+
162
+ S = Poly(r, gens=opt.gens).coeffs()
163
+ sol = solve(S, Cs + Ds, particular=True, quick=True)
164
+
165
+ if sol and not all(s == 0 for s in sol.values()):
166
+ c = c_hat.subs(sol)
167
+ d = d_hat.subs(sol)
168
+
169
+ # The "free" variables occurring before as parameters
170
+ # might still be in the substituted c, d, so set them
171
+ # to the value chosen before:
172
+ c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds))))))
173
+ d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds))))))
174
+
175
+ c = Poly(c, opt.gens)
176
+ d = Poly(d, opt.gens)
177
+ if d == 0:
178
+ raise ValueError('Ideal not prime?')
179
+
180
+ allsol.append((c_hat, d_hat, S, Cs + Ds))
181
+ if N + D != maxdeg:
182
+ allsol = [allsol[-1]]
183
+
184
+ break
185
+
186
+ steps += 1
187
+ N += 1
188
+ D += 1
189
+
190
+ if steps > 0:
191
+ c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps)
192
+ c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D)
193
+
194
+ return c, d, allsol
195
+
196
+ # preprocessing. this improves performance a bit when deg(num)
197
+ # and deg(denom) are large:
198
+ num = reduced(num, G, opt.gens, order=opt.order)[1]
199
+ denom = reduced(denom, G, opt.gens, order=opt.order)[1]
200
+
201
+ if polynomial:
202
+ return (num/denom).cancel()
203
+
204
+ c, d, allsol = _ratsimpmodprime(
205
+ Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), [])
206
+ if not quick and allsol:
207
+ debugf('Looking for best minimal solution. Got: %s', len(allsol))
208
+ newsol = []
209
+ for c_hat, d_hat, S, ng in allsol:
210
+ sol = solve(S, ng, particular=True, quick=False)
211
+ # all values of sol should be numbers; if not, solve is broken
212
+ newsol.append((c_hat.subs(sol), d_hat.subs(sol)))
213
+ c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms()))
214
+
215
+ if not domain.is_Field:
216
+ cn, c = c.clear_denoms(convert=True)
217
+ dn, d = d.clear_denoms(convert=True)
218
+ r = Rational(cn, dn)
219
+ else:
220
+ r = Rational(1)
221
+
222
+ return (c*r.q)/(d*r.p)
env-llmeval/lib/python3.10/site-packages/sympy/simplify/sqrtdenest.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Add, Expr, Mul, S, sympify
2
+ from sympy.core.function import _mexpand, count_ops, expand_mul
3
+ from sympy.core.sorting import default_sort_key
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.functions import root, sign, sqrt
6
+ from sympy.polys import Poly, PolynomialError
7
+
8
+
9
+ def is_sqrt(expr):
10
+ """Return True if expr is a sqrt, otherwise False."""
11
+
12
+ return expr.is_Pow and expr.exp.is_Rational and abs(expr.exp) is S.Half
13
+
14
+
15
+ def sqrt_depth(p):
16
+ """Return the maximum depth of any square root argument of p.
17
+
18
+ >>> from sympy.functions.elementary.miscellaneous import sqrt
19
+ >>> from sympy.simplify.sqrtdenest import sqrt_depth
20
+
21
+ Neither of these square roots contains any other square roots
22
+ so the depth is 1:
23
+
24
+ >>> sqrt_depth(1 + sqrt(2)*(1 + sqrt(3)))
25
+ 1
26
+
27
+ The sqrt(3) is contained within a square root so the depth is
28
+ 2:
29
+
30
+ >>> sqrt_depth(1 + sqrt(2)*sqrt(1 + sqrt(3)))
31
+ 2
32
+ """
33
+ if p is S.ImaginaryUnit:
34
+ return 1
35
+ if p.is_Atom:
36
+ return 0
37
+ elif p.is_Add or p.is_Mul:
38
+ return max([sqrt_depth(x) for x in p.args], key=default_sort_key)
39
+ elif is_sqrt(p):
40
+ return sqrt_depth(p.base) + 1
41
+ else:
42
+ return 0
43
+
44
+
45
+ def is_algebraic(p):
46
+ """Return True if p is comprised of only Rationals or square roots
47
+ of Rationals and algebraic operations.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy.functions.elementary.miscellaneous import sqrt
53
+ >>> from sympy.simplify.sqrtdenest import is_algebraic
54
+ >>> from sympy import cos
55
+ >>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*sqrt(2))))
56
+ True
57
+ >>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*cos(2))))
58
+ False
59
+ """
60
+
61
+ if p.is_Rational:
62
+ return True
63
+ elif p.is_Atom:
64
+ return False
65
+ elif is_sqrt(p) or p.is_Pow and p.exp.is_Integer:
66
+ return is_algebraic(p.base)
67
+ elif p.is_Add or p.is_Mul:
68
+ return all(is_algebraic(x) for x in p.args)
69
+ else:
70
+ return False
71
+
72
+
73
+ def _subsets(n):
74
+ """
75
+ Returns all possible subsets of the set (0, 1, ..., n-1) except the
76
+ empty set, listed in reversed lexicographical order according to binary
77
+ representation, so that the case of the fourth root is treated last.
78
+
79
+ Examples
80
+ ========
81
+
82
+ >>> from sympy.simplify.sqrtdenest import _subsets
83
+ >>> _subsets(2)
84
+ [[1, 0], [0, 1], [1, 1]]
85
+
86
+ """
87
+ if n == 1:
88
+ a = [[1]]
89
+ elif n == 2:
90
+ a = [[1, 0], [0, 1], [1, 1]]
91
+ elif n == 3:
92
+ a = [[1, 0, 0], [0, 1, 0], [1, 1, 0],
93
+ [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
94
+ else:
95
+ b = _subsets(n - 1)
96
+ a0 = [x + [0] for x in b]
97
+ a1 = [x + [1] for x in b]
98
+ a = a0 + [[0]*(n - 1) + [1]] + a1
99
+ return a
100
+
101
+
102
+ def sqrtdenest(expr, max_iter=3):
103
+ """Denests sqrts in an expression that contain other square roots
104
+ if possible, otherwise returns the expr unchanged. This is based on the
105
+ algorithms of [1].
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy.simplify.sqrtdenest import sqrtdenest
111
+ >>> from sympy import sqrt
112
+ >>> sqrtdenest(sqrt(5 + 2 * sqrt(6)))
113
+ sqrt(2) + sqrt(3)
114
+
115
+ See Also
116
+ ========
117
+
118
+ sympy.solvers.solvers.unrad
119
+
120
+ References
121
+ ==========
122
+
123
+ .. [1] https://web.archive.org/web/20210806201615/https://researcher.watson.ibm.com/researcher/files/us-fagin/symb85.pdf
124
+
125
+ .. [2] D. J. Jeffrey and A. D. Rich, 'Symplifying Square Roots of Square Roots
126
+ by Denesting' (available at https://www.cybertester.com/data/denest.pdf)
127
+
128
+ """
129
+ expr = expand_mul(expr)
130
+ for i in range(max_iter):
131
+ z = _sqrtdenest0(expr)
132
+ if expr == z:
133
+ return expr
134
+ expr = z
135
+ return expr
136
+
137
+
138
+ def _sqrt_match(p):
139
+ """Return [a, b, r] for p.match(a + b*sqrt(r)) where, in addition to
140
+ matching, sqrt(r) also has then maximal sqrt_depth among addends of p.
141
+
142
+ Examples
143
+ ========
144
+
145
+ >>> from sympy.functions.elementary.miscellaneous import sqrt
146
+ >>> from sympy.simplify.sqrtdenest import _sqrt_match
147
+ >>> _sqrt_match(1 + sqrt(2) + sqrt(2)*sqrt(3) + 2*sqrt(1+sqrt(5)))
148
+ [1 + sqrt(2) + sqrt(6), 2, 1 + sqrt(5)]
149
+ """
150
+ from sympy.simplify.radsimp import split_surds
151
+
152
+ p = _mexpand(p)
153
+ if p.is_Number:
154
+ res = (p, S.Zero, S.Zero)
155
+ elif p.is_Add:
156
+ pargs = sorted(p.args, key=default_sort_key)
157
+ sqargs = [x**2 for x in pargs]
158
+ if all(sq.is_Rational and sq.is_positive for sq in sqargs):
159
+ r, b, a = split_surds(p)
160
+ res = a, b, r
161
+ return list(res)
162
+ # to make the process canonical, the argument is included in the tuple
163
+ # so when the max is selected, it will be the largest arg having a
164
+ # given depth
165
+ v = [(sqrt_depth(x), x, i) for i, x in enumerate(pargs)]
166
+ nmax = max(v, key=default_sort_key)
167
+ if nmax[0] == 0:
168
+ res = []
169
+ else:
170
+ # select r
171
+ depth, _, i = nmax
172
+ r = pargs.pop(i)
173
+ v.pop(i)
174
+ b = S.One
175
+ if r.is_Mul:
176
+ bv = []
177
+ rv = []
178
+ for x in r.args:
179
+ if sqrt_depth(x) < depth:
180
+ bv.append(x)
181
+ else:
182
+ rv.append(x)
183
+ b = Mul._from_args(bv)
184
+ r = Mul._from_args(rv)
185
+ # collect terms comtaining r
186
+ a1 = []
187
+ b1 = [b]
188
+ for x in v:
189
+ if x[0] < depth:
190
+ a1.append(x[1])
191
+ else:
192
+ x1 = x[1]
193
+ if x1 == r:
194
+ b1.append(1)
195
+ else:
196
+ if x1.is_Mul:
197
+ x1args = list(x1.args)
198
+ if r in x1args:
199
+ x1args.remove(r)
200
+ b1.append(Mul(*x1args))
201
+ else:
202
+ a1.append(x[1])
203
+ else:
204
+ a1.append(x[1])
205
+ a = Add(*a1)
206
+ b = Add(*b1)
207
+ res = (a, b, r**2)
208
+ else:
209
+ b, r = p.as_coeff_Mul()
210
+ if is_sqrt(r):
211
+ res = (S.Zero, b, r**2)
212
+ else:
213
+ res = []
214
+ return list(res)
215
+
216
+
217
+ class SqrtdenestStopIteration(StopIteration):
218
+ pass
219
+
220
+
221
+ def _sqrtdenest0(expr):
222
+ """Returns expr after denesting its arguments."""
223
+
224
+ if is_sqrt(expr):
225
+ n, d = expr.as_numer_denom()
226
+ if d is S.One: # n is a square root
227
+ if n.base.is_Add:
228
+ args = sorted(n.base.args, key=default_sort_key)
229
+ if len(args) > 2 and all((x**2).is_Integer for x in args):
230
+ try:
231
+ return _sqrtdenest_rec(n)
232
+ except SqrtdenestStopIteration:
233
+ pass
234
+ expr = sqrt(_mexpand(Add(*[_sqrtdenest0(x) for x in args])))
235
+ return _sqrtdenest1(expr)
236
+ else:
237
+ n, d = [_sqrtdenest0(i) for i in (n, d)]
238
+ return n/d
239
+
240
+ if isinstance(expr, Add):
241
+ cs = []
242
+ args = []
243
+ for arg in expr.args:
244
+ c, a = arg.as_coeff_Mul()
245
+ cs.append(c)
246
+ args.append(a)
247
+
248
+ if all(c.is_Rational for c in cs) and all(is_sqrt(arg) for arg in args):
249
+ return _sqrt_ratcomb(cs, args)
250
+
251
+ if isinstance(expr, Expr):
252
+ args = expr.args
253
+ if args:
254
+ return expr.func(*[_sqrtdenest0(a) for a in args])
255
+ return expr
256
+
257
+
258
+ def _sqrtdenest_rec(expr):
259
+ """Helper that denests the square root of three or more surds.
260
+
261
+ Explanation
262
+ ===========
263
+
264
+ It returns the denested expression; if it cannot be denested it
265
+ throws SqrtdenestStopIteration
266
+
267
+ Algorithm: expr.base is in the extension Q_m = Q(sqrt(r_1),..,sqrt(r_k));
268
+ split expr.base = a + b*sqrt(r_k), where `a` and `b` are on
269
+ Q_(m-1) = Q(sqrt(r_1),..,sqrt(r_(k-1))); then a**2 - b**2*r_k is
270
+ on Q_(m-1); denest sqrt(a**2 - b**2*r_k) and so on.
271
+ See [1], section 6.
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import sqrt
277
+ >>> from sympy.simplify.sqrtdenest import _sqrtdenest_rec
278
+ >>> _sqrtdenest_rec(sqrt(-72*sqrt(2) + 158*sqrt(5) + 498))
279
+ -sqrt(10) + sqrt(2) + 9 + 9*sqrt(5)
280
+ >>> w=-6*sqrt(55)-6*sqrt(35)-2*sqrt(22)-2*sqrt(14)+2*sqrt(77)+6*sqrt(10)+65
281
+ >>> _sqrtdenest_rec(sqrt(w))
282
+ -sqrt(11) - sqrt(7) + sqrt(2) + 3*sqrt(5)
283
+ """
284
+ from sympy.simplify.radsimp import radsimp, rad_rationalize, split_surds
285
+ if not expr.is_Pow:
286
+ return sqrtdenest(expr)
287
+ if expr.base < 0:
288
+ return sqrt(-1)*_sqrtdenest_rec(sqrt(-expr.base))
289
+ g, a, b = split_surds(expr.base)
290
+ a = a*sqrt(g)
291
+ if a < b:
292
+ a, b = b, a
293
+ c2 = _mexpand(a**2 - b**2)
294
+ if len(c2.args) > 2:
295
+ g, a1, b1 = split_surds(c2)
296
+ a1 = a1*sqrt(g)
297
+ if a1 < b1:
298
+ a1, b1 = b1, a1
299
+ c2_1 = _mexpand(a1**2 - b1**2)
300
+ c_1 = _sqrtdenest_rec(sqrt(c2_1))
301
+ d_1 = _sqrtdenest_rec(sqrt(a1 + c_1))
302
+ num, den = rad_rationalize(b1, d_1)
303
+ c = _mexpand(d_1/sqrt(2) + num/(den*sqrt(2)))
304
+ else:
305
+ c = _sqrtdenest1(sqrt(c2))
306
+
307
+ if sqrt_depth(c) > 1:
308
+ raise SqrtdenestStopIteration
309
+ ac = a + c
310
+ if len(ac.args) >= len(expr.args):
311
+ if count_ops(ac) >= count_ops(expr.base):
312
+ raise SqrtdenestStopIteration
313
+ d = sqrtdenest(sqrt(ac))
314
+ if sqrt_depth(d) > 1:
315
+ raise SqrtdenestStopIteration
316
+ num, den = rad_rationalize(b, d)
317
+ r = d/sqrt(2) + num/(den*sqrt(2))
318
+ r = radsimp(r)
319
+ return _mexpand(r)
320
+
321
+
322
+ def _sqrtdenest1(expr, denester=True):
323
+ """Return denested expr after denesting with simpler methods or, that
324
+ failing, using the denester."""
325
+
326
+ from sympy.simplify.simplify import radsimp
327
+
328
+ if not is_sqrt(expr):
329
+ return expr
330
+
331
+ a = expr.base
332
+ if a.is_Atom:
333
+ return expr
334
+ val = _sqrt_match(a)
335
+ if not val:
336
+ return expr
337
+
338
+ a, b, r = val
339
+ # try a quick numeric denesting
340
+ d2 = _mexpand(a**2 - b**2*r)
341
+ if d2.is_Rational:
342
+ if d2.is_positive:
343
+ z = _sqrt_numeric_denest(a, b, r, d2)
344
+ if z is not None:
345
+ return z
346
+ else:
347
+ # fourth root case
348
+ # sqrtdenest(sqrt(3 + 2*sqrt(3))) =
349
+ # sqrt(2)*3**(1/4)/2 + sqrt(2)*3**(3/4)/2
350
+ dr2 = _mexpand(-d2*r)
351
+ dr = sqrt(dr2)
352
+ if dr.is_Rational:
353
+ z = _sqrt_numeric_denest(_mexpand(b*r), a, r, dr2)
354
+ if z is not None:
355
+ return z/root(r, 4)
356
+
357
+ else:
358
+ z = _sqrt_symbolic_denest(a, b, r)
359
+ if z is not None:
360
+ return z
361
+
362
+ if not denester or not is_algebraic(expr):
363
+ return expr
364
+
365
+ res = sqrt_biquadratic_denest(expr, a, b, r, d2)
366
+ if res:
367
+ return res
368
+
369
+ # now call to the denester
370
+ av0 = [a, b, r, d2]
371
+ z = _denester([radsimp(expr**2)], av0, 0, sqrt_depth(expr))[0]
372
+ if av0[1] is None:
373
+ return expr
374
+ if z is not None:
375
+ if sqrt_depth(z) == sqrt_depth(expr) and count_ops(z) > count_ops(expr):
376
+ return expr
377
+ return z
378
+ return expr
379
+
380
+
381
+ def _sqrt_symbolic_denest(a, b, r):
382
+ """Given an expression, sqrt(a + b*sqrt(b)), return the denested
383
+ expression or None.
384
+
385
+ Explanation
386
+ ===========
387
+
388
+ If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
389
+ (y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
390
+ (cb + b)**2 - 4*ca*cc is 0, then sqrt(a + b*sqrt(r)) can be rewritten as
391
+ sqrt(ca*(sqrt(r) + (cb + b)/(2*ca))**2).
392
+
393
+ Examples
394
+ ========
395
+
396
+ >>> from sympy.simplify.sqrtdenest import _sqrt_symbolic_denest, sqrtdenest
397
+ >>> from sympy import sqrt, Symbol
398
+ >>> from sympy.abc import x
399
+
400
+ >>> a, b, r = 16 - 2*sqrt(29), 2, -10*sqrt(29) + 55
401
+ >>> _sqrt_symbolic_denest(a, b, r)
402
+ sqrt(11 - 2*sqrt(29)) + sqrt(5)
403
+
404
+ If the expression is numeric, it will be simplified:
405
+
406
+ >>> w = sqrt(sqrt(sqrt(3) + 1) + 1) + 1 + sqrt(2)
407
+ >>> sqrtdenest(sqrt((w**2).expand()))
408
+ 1 + sqrt(2) + sqrt(1 + sqrt(1 + sqrt(3)))
409
+
410
+ Otherwise, it will only be simplified if assumptions allow:
411
+
412
+ >>> w = w.subs(sqrt(3), sqrt(x + 3))
413
+ >>> sqrtdenest(sqrt((w**2).expand()))
414
+ sqrt((sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2))**2)
415
+
416
+ Notice that the argument of the sqrt is a square. If x is made positive
417
+ then the sqrt of the square is resolved:
418
+
419
+ >>> _.subs(x, Symbol('x', positive=True))
420
+ sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2)
421
+ """
422
+
423
+ a, b, r = map(sympify, (a, b, r))
424
+ rval = _sqrt_match(r)
425
+ if not rval:
426
+ return None
427
+ ra, rb, rr = rval
428
+ if rb:
429
+ y = Dummy('y', positive=True)
430
+ try:
431
+ newa = Poly(a.subs(sqrt(rr), (y**2 - ra)/rb), y)
432
+ except PolynomialError:
433
+ return None
434
+ if newa.degree() == 2:
435
+ ca, cb, cc = newa.all_coeffs()
436
+ cb += b
437
+ if _mexpand(cb**2 - 4*ca*cc).equals(0):
438
+ z = sqrt(ca*(sqrt(r) + cb/(2*ca))**2)
439
+ if z.is_number:
440
+ z = _mexpand(Mul._from_args(z.as_content_primitive()))
441
+ return z
442
+
443
+
444
+ def _sqrt_numeric_denest(a, b, r, d2):
445
+ r"""Helper that denest
446
+ $\sqrt{a + b \sqrt{r}}, d^2 = a^2 - b^2 r > 0$
447
+
448
+ If it cannot be denested, it returns ``None``.
449
+ """
450
+ d = sqrt(d2)
451
+ s = a + d
452
+ # sqrt_depth(res) <= sqrt_depth(s) + 1
453
+ # sqrt_depth(expr) = sqrt_depth(r) + 2
454
+ # there is denesting if sqrt_depth(s) + 1 < sqrt_depth(r) + 2
455
+ # if s**2 is Number there is a fourth root
456
+ if sqrt_depth(s) < sqrt_depth(r) + 1 or (s**2).is_Rational:
457
+ s1, s2 = sign(s), sign(b)
458
+ if s1 == s2 == -1:
459
+ s1 = s2 = 1
460
+ res = (s1 * sqrt(a + d) + s2 * sqrt(a - d)) * sqrt(2) / 2
461
+ return res.expand()
462
+
463
+
464
+ def sqrt_biquadratic_denest(expr, a, b, r, d2):
465
+ """denest expr = sqrt(a + b*sqrt(r))
466
+ where a, b, r are linear combinations of square roots of
467
+ positive rationals on the rationals (SQRR) and r > 0, b != 0,
468
+ d2 = a**2 - b**2*r > 0
469
+
470
+ If it cannot denest it returns None.
471
+
472
+ Explanation
473
+ ===========
474
+
475
+ Search for a solution A of type SQRR of the biquadratic equation
476
+ 4*A**4 - 4*a*A**2 + b**2*r = 0 (1)
477
+ sqd = sqrt(a**2 - b**2*r)
478
+ Choosing the sqrt to be positive, the possible solutions are
479
+ A = sqrt(a/2 +/- sqd/2)
480
+ Since a, b, r are SQRR, then a**2 - b**2*r is a SQRR,
481
+ so if sqd can be denested, it is done by
482
+ _sqrtdenest_rec, and the result is a SQRR.
483
+ Similarly for A.
484
+ Examples of solutions (in both cases a and sqd are positive):
485
+
486
+ Example of expr with solution sqrt(a/2 + sqd/2) but not
487
+ solution sqrt(a/2 - sqd/2):
488
+ expr = sqrt(-sqrt(15) - sqrt(2)*sqrt(-sqrt(5) + 5) - sqrt(3) + 8)
489
+ a = -sqrt(15) - sqrt(3) + 8; sqd = -2*sqrt(5) - 2 + 4*sqrt(3)
490
+
491
+ Example of expr with solution sqrt(a/2 - sqd/2) but not
492
+ solution sqrt(a/2 + sqd/2):
493
+ w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3)
494
+ expr = sqrt((w**2).expand())
495
+ a = 4*sqrt(6) + 8*sqrt(2) + 47 + 28*sqrt(3)
496
+ sqd = 29 + 20*sqrt(3)
497
+
498
+ Define B = b/2*A; eq.(1) implies a = A**2 + B**2*r; then
499
+ expr**2 = a + b*sqrt(r) = (A + B*sqrt(r))**2
500
+
501
+ Examples
502
+ ========
503
+
504
+ >>> from sympy import sqrt
505
+ >>> from sympy.simplify.sqrtdenest import _sqrt_match, sqrt_biquadratic_denest
506
+ >>> z = sqrt((2*sqrt(2) + 4)*sqrt(2 + sqrt(2)) + 5*sqrt(2) + 8)
507
+ >>> a, b, r = _sqrt_match(z**2)
508
+ >>> d2 = a**2 - b**2*r
509
+ >>> sqrt_biquadratic_denest(z, a, b, r, d2)
510
+ sqrt(2) + sqrt(sqrt(2) + 2) + 2
511
+ """
512
+ from sympy.simplify.radsimp import radsimp, rad_rationalize
513
+ if r <= 0 or d2 < 0 or not b or sqrt_depth(expr.base) < 2:
514
+ return None
515
+ for x in (a, b, r):
516
+ for y in x.args:
517
+ y2 = y**2
518
+ if not y2.is_Integer or not y2.is_positive:
519
+ return None
520
+ sqd = _mexpand(sqrtdenest(sqrt(radsimp(d2))))
521
+ if sqrt_depth(sqd) > 1:
522
+ return None
523
+ x1, x2 = [a/2 + sqd/2, a/2 - sqd/2]
524
+ # look for a solution A with depth 1
525
+ for x in (x1, x2):
526
+ A = sqrtdenest(sqrt(x))
527
+ if sqrt_depth(A) > 1:
528
+ continue
529
+ Bn, Bd = rad_rationalize(b, _mexpand(2*A))
530
+ B = Bn/Bd
531
+ z = A + B*sqrt(r)
532
+ if z < 0:
533
+ z = -z
534
+ return _mexpand(z)
535
+ return None
536
+
537
+
538
+ def _denester(nested, av0, h, max_depth_level):
539
+ """Denests a list of expressions that contain nested square roots.
540
+
541
+ Explanation
542
+ ===========
543
+
544
+ Algorithm based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>.
545
+
546
+ It is assumed that all of the elements of 'nested' share the same
547
+ bottom-level radicand. (This is stated in the paper, on page 177, in
548
+ the paragraph immediately preceding the algorithm.)
549
+
550
+ When evaluating all of the arguments in parallel, the bottom-level
551
+ radicand only needs to be denested once. This means that calling
552
+ _denester with x arguments results in a recursive invocation with x+1
553
+ arguments; hence _denester has polynomial complexity.
554
+
555
+ However, if the arguments were evaluated separately, each call would
556
+ result in two recursive invocations, and the algorithm would have
557
+ exponential complexity.
558
+
559
+ This is discussed in the paper in the middle paragraph of page 179.
560
+ """
561
+ from sympy.simplify.simplify import radsimp
562
+ if h > max_depth_level:
563
+ return None, None
564
+ if av0[1] is None:
565
+ return None, None
566
+ if (av0[0] is None and
567
+ all(n.is_Number for n in nested)): # no arguments are nested
568
+ for f in _subsets(len(nested)): # test subset 'f' of nested
569
+ p = _mexpand(Mul(*[nested[i] for i in range(len(f)) if f[i]]))
570
+ if f.count(1) > 1 and f[-1]:
571
+ p = -p
572
+ sqp = sqrt(p)
573
+ if sqp.is_Rational:
574
+ return sqp, f # got a perfect square so return its square root.
575
+ # Otherwise, return the radicand from the previous invocation.
576
+ return sqrt(nested[-1]), [0]*len(nested)
577
+ else:
578
+ R = None
579
+ if av0[0] is not None:
580
+ values = [av0[:2]]
581
+ R = av0[2]
582
+ nested2 = [av0[3], R]
583
+ av0[0] = None
584
+ else:
585
+ values = list(filter(None, [_sqrt_match(expr) for expr in nested]))
586
+ for v in values:
587
+ if v[2]: # Since if b=0, r is not defined
588
+ if R is not None:
589
+ if R != v[2]:
590
+ av0[1] = None
591
+ return None, None
592
+ else:
593
+ R = v[2]
594
+ if R is None:
595
+ # return the radicand from the previous invocation
596
+ return sqrt(nested[-1]), [0]*len(nested)
597
+ nested2 = [_mexpand(v[0]**2) -
598
+ _mexpand(R*v[1]**2) for v in values] + [R]
599
+ d, f = _denester(nested2, av0, h + 1, max_depth_level)
600
+ if not f:
601
+ return None, None
602
+ if not any(f[i] for i in range(len(nested))):
603
+ v = values[-1]
604
+ return sqrt(v[0] + _mexpand(v[1]*d)), f
605
+ else:
606
+ p = Mul(*[nested[i] for i in range(len(nested)) if f[i]])
607
+ v = _sqrt_match(p)
608
+ if 1 in f and f.index(1) < len(nested) - 1 and f[len(nested) - 1]:
609
+ v[0] = -v[0]
610
+ v[1] = -v[1]
611
+ if not f[len(nested)]: # Solution denests with square roots
612
+ vad = _mexpand(v[0] + d)
613
+ if vad <= 0:
614
+ # return the radicand from the previous invocation.
615
+ return sqrt(nested[-1]), [0]*len(nested)
616
+ if not(sqrt_depth(vad) <= sqrt_depth(R) + 1 or
617
+ (vad**2).is_Number):
618
+ av0[1] = None
619
+ return None, None
620
+
621
+ sqvad = _sqrtdenest1(sqrt(vad), denester=False)
622
+ if not (sqrt_depth(sqvad) <= sqrt_depth(R) + 1):
623
+ av0[1] = None
624
+ return None, None
625
+ sqvad1 = radsimp(1/sqvad)
626
+ res = _mexpand(sqvad/sqrt(2) + (v[1]*sqrt(R)*sqvad1/sqrt(2)))
627
+ return res, f
628
+
629
+ # sign(v[1])*sqrt(_mexpand(v[1]**2*R*vad1/2))), f
630
+ else: # Solution requires a fourth root
631
+ s2 = _mexpand(v[1]*R) + d
632
+ if s2 <= 0:
633
+ return sqrt(nested[-1]), [0]*len(nested)
634
+ FR, s = root(_mexpand(R), 4), sqrt(s2)
635
+ return _mexpand(s/(sqrt(2)*FR) + v[0]*FR/(sqrt(2)*s)), f
636
+
637
+
638
+ def _sqrt_ratcomb(cs, args):
639
+ """Denest rational combinations of radicals.
640
+
641
+ Based on section 5 of [1].
642
+
643
+ Examples
644
+ ========
645
+
646
+ >>> from sympy import sqrt
647
+ >>> from sympy.simplify.sqrtdenest import sqrtdenest
648
+ >>> z = sqrt(1+sqrt(3)) + sqrt(3+3*sqrt(3)) - sqrt(10+6*sqrt(3))
649
+ >>> sqrtdenest(z)
650
+ 0
651
+ """
652
+ from sympy.simplify.radsimp import radsimp
653
+
654
+ # check if there exists a pair of sqrt that can be denested
655
+ def find(a):
656
+ n = len(a)
657
+ for i in range(n - 1):
658
+ for j in range(i + 1, n):
659
+ s1 = a[i].base
660
+ s2 = a[j].base
661
+ p = _mexpand(s1 * s2)
662
+ s = sqrtdenest(sqrt(p))
663
+ if s != sqrt(p):
664
+ return s, i, j
665
+
666
+ indices = find(args)
667
+ if indices is None:
668
+ return Add(*[c * arg for c, arg in zip(cs, args)])
669
+
670
+ s, i1, i2 = indices
671
+
672
+ c2 = cs.pop(i2)
673
+ args.pop(i2)
674
+ a1 = args[i1]
675
+
676
+ # replace a2 by s/a1
677
+ cs[i1] += radsimp(c2 * s / a1.base)
678
+
679
+ return _sqrt_ratcomb(cs, args)
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_combsimp.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_cse.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_epathtools.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_fu.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (2.38 kB). View file