Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py +83 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py +261 -0
- env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py +134 -0
- env-llmeval/lib/python3.10/site-packages/sympy/interactive/__init__.py +8 -0
- env-llmeval/lib/python3.10/site-packages/sympy/interactive/printing.py +562 -0
- env-llmeval/lib/python3.10/site-packages/sympy/interactive/traversal.py +95 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py +12 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_polysys.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_constantsimp.py +179 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_decompogen.py +59 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_pde.py +239 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_polysys.py +178 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_solvers.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_solveset.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/basisdependent.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/deloperator.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/dyadic.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/implicitregion.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/integrals.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/operators.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/orienters.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/parametricregion.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/point.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/scalar.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/vector.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/deloperator.py +121 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/functions.py +517 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/implicitregion.py +506 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/integrals.py +206 -0
- env-llmeval/lib/python3.10/site-packages/sympy/vector/orienters.py +398 -0
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (181 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_discrete_log.cpython-310.pyc
ADDED
Binary file (2.01 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-310.pyc
ADDED
Binary file (10.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_symbench.cpython-310.pyc
ADDED
Binary file (5.14 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from time import time
|
3 |
+
from sympy.ntheory.residue_ntheory import (discrete_log,
|
4 |
+
_discrete_log_trial_mul, _discrete_log_shanks_steps,
|
5 |
+
_discrete_log_pollard_rho, _discrete_log_pohlig_hellman)
|
6 |
+
|
7 |
+
|
8 |
+
# Cyclic group (Z/pZ)* with p prime, order p - 1 and generator g
|
9 |
+
data_set_1 = [
|
10 |
+
# p, p - 1, g
|
11 |
+
[191, 190, 19],
|
12 |
+
[46639, 46638, 6],
|
13 |
+
[14789363, 14789362, 2],
|
14 |
+
[4254225211, 4254225210, 2],
|
15 |
+
[432751500361, 432751500360, 7],
|
16 |
+
[158505390797053, 158505390797052, 2],
|
17 |
+
[6575202655312007, 6575202655312006, 5],
|
18 |
+
[8430573471995353769, 8430573471995353768, 3],
|
19 |
+
[3938471339744997827267, 3938471339744997827266, 2],
|
20 |
+
[875260951364705563393093, 875260951364705563393092, 5],
|
21 |
+
]
|
22 |
+
|
23 |
+
|
24 |
+
# Cyclic sub-groups of (Z/nZ)* with prime order p and generator g
|
25 |
+
# (n, p are primes and n = 2 * p + 1)
|
26 |
+
data_set_2 = [
|
27 |
+
# n, p, g
|
28 |
+
[227, 113, 3],
|
29 |
+
[2447, 1223, 2],
|
30 |
+
[24527, 12263, 2],
|
31 |
+
[245639, 122819, 2],
|
32 |
+
[2456747, 1228373, 3],
|
33 |
+
[24567899, 12283949, 3],
|
34 |
+
[245679023, 122839511, 2],
|
35 |
+
[2456791307, 1228395653, 3],
|
36 |
+
[24567913439, 12283956719, 2],
|
37 |
+
[245679135407, 122839567703, 2],
|
38 |
+
[2456791354763, 1228395677381, 3],
|
39 |
+
[24567913550903, 12283956775451, 2],
|
40 |
+
[245679135509519, 122839567754759, 2],
|
41 |
+
]
|
42 |
+
|
43 |
+
|
44 |
+
# Cyclic sub-groups of (Z/nZ)* with smooth order o and generator g
|
45 |
+
data_set_3 = [
|
46 |
+
# n, o, g
|
47 |
+
[2**118, 2**116, 3],
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
def bench_discrete_log(data_set, algo=None):
|
52 |
+
if algo is None:
|
53 |
+
f = discrete_log
|
54 |
+
elif algo == 'trial':
|
55 |
+
f = _discrete_log_trial_mul
|
56 |
+
elif algo == 'shanks':
|
57 |
+
f = _discrete_log_shanks_steps
|
58 |
+
elif algo == 'rho':
|
59 |
+
f = _discrete_log_pollard_rho
|
60 |
+
elif algo == 'ph':
|
61 |
+
f = _discrete_log_pohlig_hellman
|
62 |
+
else:
|
63 |
+
raise ValueError("Argument 'algo' should be one"
|
64 |
+
" of ('trial', 'shanks', 'rho' or 'ph')")
|
65 |
+
|
66 |
+
for i, data in enumerate(data_set):
|
67 |
+
for j, (n, p, g) in enumerate(data):
|
68 |
+
t = time()
|
69 |
+
l = f(n, pow(g, p - 1, n), g, p)
|
70 |
+
t = time() - t
|
71 |
+
print('[%02d-%03d] %15.10f' % (i, j, t))
|
72 |
+
assert l == p - 1
|
73 |
+
|
74 |
+
|
75 |
+
if __name__ == '__main__':
|
76 |
+
algo = sys.argv[1] \
|
77 |
+
if len(sys.argv) > 1 else None
|
78 |
+
data_set = [
|
79 |
+
data_set_1,
|
80 |
+
data_set_2,
|
81 |
+
data_set_3,
|
82 |
+
]
|
83 |
+
bench_discrete_log(data_set, algo)
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py
ADDED
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# conceal the implicit import from the code quality tester
|
2 |
+
from sympy.core.numbers import (oo, pi)
|
3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
4 |
+
from sympy.functions.elementary.exponential import exp
|
5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
6 |
+
from sympy.functions.special.bessel import besseli
|
7 |
+
from sympy.functions.special.gamma_functions import gamma
|
8 |
+
from sympy.integrals.integrals import integrate
|
9 |
+
from sympy.integrals.transforms import (mellin_transform,
|
10 |
+
inverse_fourier_transform, inverse_mellin_transform,
|
11 |
+
laplace_transform, inverse_laplace_transform, fourier_transform)
|
12 |
+
|
13 |
+
LT = laplace_transform
|
14 |
+
FT = fourier_transform
|
15 |
+
MT = mellin_transform
|
16 |
+
IFT = inverse_fourier_transform
|
17 |
+
ILT = inverse_laplace_transform
|
18 |
+
IMT = inverse_mellin_transform
|
19 |
+
|
20 |
+
from sympy.abc import x, y
|
21 |
+
nu, beta, rho = symbols('nu beta rho')
|
22 |
+
|
23 |
+
apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True)
|
24 |
+
k = Symbol('k', real=True)
|
25 |
+
negk = Symbol('k', negative=True)
|
26 |
+
|
27 |
+
mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True)
|
28 |
+
sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True,
|
29 |
+
finite=True, positive=True)
|
30 |
+
rate = Symbol('lambda', positive=True)
|
31 |
+
|
32 |
+
|
33 |
+
def normal(x, mu, sigma):
|
34 |
+
return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
|
35 |
+
|
36 |
+
|
37 |
+
def exponential(x, rate):
|
38 |
+
return rate*exp(-rate*x)
|
39 |
+
alpha, beta = symbols('alpha beta', positive=True)
|
40 |
+
betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
|
41 |
+
/gamma(alpha)/gamma(beta)
|
42 |
+
kint = Symbol('k', integer=True, positive=True)
|
43 |
+
chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2)
|
44 |
+
chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
|
45 |
+
dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1)
|
46 |
+
d1, d2 = symbols('d1 d2', positive=True)
|
47 |
+
f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
|
48 |
+
/gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
|
49 |
+
nupos, sigmapos = symbols('nu sigma', positive=True)
|
50 |
+
rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x*
|
51 |
+
nupos/sigmapos**2)
|
52 |
+
mu = Symbol('mu', real=True)
|
53 |
+
laplace = exp(-abs(x - mu)/bpos)/2/bpos
|
54 |
+
|
55 |
+
u = Symbol('u', polar=True)
|
56 |
+
tpos = Symbol('t', positive=True)
|
57 |
+
|
58 |
+
|
59 |
+
def E(expr):
|
60 |
+
integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
|
61 |
+
(x, 0, oo), (y, -oo, oo), meijerg=True)
|
62 |
+
integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
|
63 |
+
(y, -oo, oo), (x, 0, oo), meijerg=True)
|
64 |
+
|
65 |
+
bench = [
|
66 |
+
'MT(x**nu*Heaviside(x - 1), x, s)',
|
67 |
+
'MT(x**nu*Heaviside(1 - x), x, s)',
|
68 |
+
'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)',
|
69 |
+
'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)',
|
70 |
+
'MT((1+x)**(-rho), x, s)',
|
71 |
+
'MT(abs(1-x)**(-rho), x, s)',
|
72 |
+
'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)',
|
73 |
+
'MT((x**a-b**a)/(x-b), x, s)',
|
74 |
+
'MT((x**a-bpos**a)/(x-bpos), x, s)',
|
75 |
+
'MT(exp(-x), x, s)',
|
76 |
+
'MT(exp(-1/x), x, s)',
|
77 |
+
'MT(log(x)**4*Heaviside(1-x), x, s)',
|
78 |
+
'MT(log(x)**3*Heaviside(x-1), x, s)',
|
79 |
+
'MT(log(x + 1), x, s)',
|
80 |
+
'MT(log(1/x + 1), x, s)',
|
81 |
+
'MT(log(abs(1 - x)), x, s)',
|
82 |
+
'MT(log(abs(1 - 1/x)), x, s)',
|
83 |
+
'MT(log(x)/(x+1), x, s)',
|
84 |
+
'MT(log(x)**2/(x+1), x, s)',
|
85 |
+
'MT(log(x)/(x+1)**2, x, s)',
|
86 |
+
'MT(erf(sqrt(x)), x, s)',
|
87 |
+
|
88 |
+
'MT(besselj(a, 2*sqrt(x)), x, s)',
|
89 |
+
'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)',
|
90 |
+
'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)',
|
91 |
+
'MT(besselj(a, sqrt(x))**2, x, s)',
|
92 |
+
'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)',
|
93 |
+
'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)',
|
94 |
+
'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)',
|
95 |
+
'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)',
|
96 |
+
'MT(bessely(a, 2*sqrt(x)), x, s)',
|
97 |
+
'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)',
|
98 |
+
'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)',
|
99 |
+
'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)',
|
100 |
+
'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)',
|
101 |
+
'MT(bessely(a, sqrt(x))**2, x, s)',
|
102 |
+
|
103 |
+
'MT(besselk(a, 2*sqrt(x)), x, s)',
|
104 |
+
'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)',
|
105 |
+
'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)',
|
106 |
+
'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)',
|
107 |
+
'MT(exp(-x/2)*besselk(a, x/2), x, s)',
|
108 |
+
|
109 |
+
# later: ILT, IMT
|
110 |
+
|
111 |
+
'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)',
|
112 |
+
'LT(t**apos, t, s)',
|
113 |
+
'LT(Heaviside(t), t, s)',
|
114 |
+
'LT(Heaviside(t - apos), t, s)',
|
115 |
+
'LT(1 - exp(-apos*t), t, s)',
|
116 |
+
'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)',
|
117 |
+
'LT(exp(t), t, s)',
|
118 |
+
'LT(exp(2*t), t, s)',
|
119 |
+
'LT(exp(apos*t), t, s)',
|
120 |
+
'LT(log(t/apos), t, s)',
|
121 |
+
'LT(erf(t), t, s)',
|
122 |
+
'LT(sin(apos*t), t, s)',
|
123 |
+
'LT(cos(apos*t), t, s)',
|
124 |
+
'LT(exp(-apos*t)*sin(bpos*t), t, s)',
|
125 |
+
'LT(exp(-apos*t)*cos(bpos*t), t, s)',
|
126 |
+
'LT(besselj(0, t), t, s, noconds=True)',
|
127 |
+
'LT(besselj(1, t), t, s, noconds=True)',
|
128 |
+
|
129 |
+
'FT(Heaviside(1 - abs(2*apos*x)), x, k)',
|
130 |
+
'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)',
|
131 |
+
'FT(exp(-apos*x)*Heaviside(x), x, k)',
|
132 |
+
'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)',
|
133 |
+
'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)',
|
134 |
+
'IFT(1/(apos + 2*pi*I*x), x, negk)',
|
135 |
+
'FT(x*exp(-apos*x)*Heaviside(x), x, k)',
|
136 |
+
'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)',
|
137 |
+
'FT(exp(-apos*x**2), x, k)',
|
138 |
+
'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)',
|
139 |
+
'FT(exp(-apos*abs(x)), x, k)',
|
140 |
+
|
141 |
+
'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
142 |
+
'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
143 |
+
'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
144 |
+
'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
145 |
+
'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
146 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
147 |
+
'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
148 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
149 |
+
'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
150 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
151 |
+
'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
152 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
153 |
+
'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
154 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
155 |
+
'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
156 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
157 |
+
'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
158 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
159 |
+
'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
160 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
161 |
+
'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)',
|
162 |
+
'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)',
|
163 |
+
'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)',
|
164 |
+
'E(1)',
|
165 |
+
'E(x*y)',
|
166 |
+
'E(x*y**2)',
|
167 |
+
'E((x+y+1)**2)',
|
168 |
+
'E(x+y+1)',
|
169 |
+
'E((x+y-1)**2)',
|
170 |
+
'integrate(betadist, (x, 0, oo), meijerg=True)',
|
171 |
+
'integrate(x*betadist, (x, 0, oo), meijerg=True)',
|
172 |
+
'integrate(x**2*betadist, (x, 0, oo), meijerg=True)',
|
173 |
+
'integrate(chi, (x, 0, oo), meijerg=True)',
|
174 |
+
'integrate(x*chi, (x, 0, oo), meijerg=True)',
|
175 |
+
'integrate(x**2*chi, (x, 0, oo), meijerg=True)',
|
176 |
+
'integrate(chisquared, (x, 0, oo), meijerg=True)',
|
177 |
+
'integrate(x*chisquared, (x, 0, oo), meijerg=True)',
|
178 |
+
'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)',
|
179 |
+
'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)',
|
180 |
+
'integrate(dagum, (x, 0, oo), meijerg=True)',
|
181 |
+
'integrate(x*dagum, (x, 0, oo), meijerg=True)',
|
182 |
+
'integrate(x**2*dagum, (x, 0, oo), meijerg=True)',
|
183 |
+
'integrate(f, (x, 0, oo), meijerg=True)',
|
184 |
+
'integrate(x*f, (x, 0, oo), meijerg=True)',
|
185 |
+
'integrate(x**2*f, (x, 0, oo), meijerg=True)',
|
186 |
+
'integrate(rice, (x, 0, oo), meijerg=True)',
|
187 |
+
'integrate(laplace, (x, -oo, oo), meijerg=True)',
|
188 |
+
'integrate(x*laplace, (x, -oo, oo), meijerg=True)',
|
189 |
+
'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)',
|
190 |
+
'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))',
|
191 |
+
|
192 |
+
'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)',
|
193 |
+
'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
|
194 |
+
'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)',
|
195 |
+
'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
|
196 |
+
'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)',
|
197 |
+
|
198 |
+
'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))',
|
199 |
+
"gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))",
|
200 |
+
|
201 |
+
'mellin_transform(E1(x), x, s)',
|
202 |
+
'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))',
|
203 |
+
'mellin_transform(expint(a, x), x, s)',
|
204 |
+
'mellin_transform(Si(x), x, s)',
|
205 |
+
'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))',
|
206 |
+
'mellin_transform(Ci(sqrt(x)), x, s)',
|
207 |
+
'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))',
|
208 |
+
'laplace_transform(Ci(x), x, s)',
|
209 |
+
'laplace_transform(expint(a, x), x, s)',
|
210 |
+
'laplace_transform(expint(1, x), x, s)',
|
211 |
+
'laplace_transform(expint(2, x), x, s)',
|
212 |
+
'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)',
|
213 |
+
'inverse_laplace_transform(log(s + 1)/s, s, x)',
|
214 |
+
'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)',
|
215 |
+
'laplace_transform(Chi(x), x, s)',
|
216 |
+
'laplace_transform(Shi(x), x, s)',
|
217 |
+
|
218 |
+
'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")',
|
219 |
+
'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")',
|
220 |
+
'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")',
|
221 |
+
'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)',
|
222 |
+
'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)',
|
223 |
+
'integrate(sin(x)/x, (x, 0, z), meijerg=True)',
|
224 |
+
'integrate(sinh(x)/x, (x, 0, z), meijerg=True)',
|
225 |
+
'integrate(exp(-x)/x, x, meijerg=True)',
|
226 |
+
'integrate(exp(-x)/x**2, x, meijerg=True)',
|
227 |
+
'integrate(cos(u)/u, u, meijerg=True)',
|
228 |
+
'integrate(cosh(u)/u, u, meijerg=True)',
|
229 |
+
'integrate(expint(1, x), x, meijerg=True)',
|
230 |
+
'integrate(expint(2, x), x, meijerg=True)',
|
231 |
+
'integrate(Si(x), x, meijerg=True)',
|
232 |
+
'integrate(Ci(u), u, meijerg=True)',
|
233 |
+
'integrate(Shi(x), x, meijerg=True)',
|
234 |
+
'integrate(Chi(u), u, meijerg=True)',
|
235 |
+
'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)',
|
236 |
+
'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)'
|
237 |
+
]
|
238 |
+
|
239 |
+
from time import time
|
240 |
+
from sympy.core.cache import clear_cache
|
241 |
+
import sys
|
242 |
+
|
243 |
+
timings = []
|
244 |
+
|
245 |
+
if __name__ == '__main__':
|
246 |
+
for n, string in enumerate(bench):
|
247 |
+
clear_cache()
|
248 |
+
_t = time()
|
249 |
+
exec(string)
|
250 |
+
_t = time() - _t
|
251 |
+
timings += [(_t, string)]
|
252 |
+
sys.stdout.write('.')
|
253 |
+
sys.stdout.flush()
|
254 |
+
if n % (len(bench) // 10) == 0:
|
255 |
+
sys.stdout.write('%s' % (10*n // len(bench)))
|
256 |
+
print()
|
257 |
+
|
258 |
+
timings.sort(key=lambda x: -x[0])
|
259 |
+
|
260 |
+
for ti, string in timings:
|
261 |
+
print('%.2fs %s' % (ti, string))
|
env-llmeval/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
from sympy.core.random import random
|
3 |
+
from sympy.core.numbers import (I, Integer, pi)
|
4 |
+
from sympy.core.symbol import Symbol
|
5 |
+
from sympy.core.sympify import sympify
|
6 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
7 |
+
from sympy.functions.elementary.trigonometric import sin
|
8 |
+
from sympy.polys.polytools import factor
|
9 |
+
from sympy.simplify.simplify import simplify
|
10 |
+
from sympy.abc import x, y, z
|
11 |
+
from timeit import default_timer as clock
|
12 |
+
|
13 |
+
|
14 |
+
def bench_R1():
|
15 |
+
"real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))"
|
16 |
+
def f(z):
|
17 |
+
return sqrt(Integer(1)/3)*z**2 + I/3
|
18 |
+
f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0]
|
19 |
+
|
20 |
+
|
21 |
+
def bench_R2():
|
22 |
+
"Hermite polynomial hermite(15, y)"
|
23 |
+
def hermite(n, y):
|
24 |
+
if n == 1:
|
25 |
+
return 2*y
|
26 |
+
if n == 0:
|
27 |
+
return 1
|
28 |
+
return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand()
|
29 |
+
|
30 |
+
hermite(15, y)
|
31 |
+
|
32 |
+
|
33 |
+
def bench_R3():
|
34 |
+
"a = [bool(f==f) for _ in range(10)]"
|
35 |
+
f = x + y + z
|
36 |
+
[bool(f == f) for _ in range(10)]
|
37 |
+
|
38 |
+
|
39 |
+
def bench_R4():
|
40 |
+
# we don't have Tuples
|
41 |
+
pass
|
42 |
+
|
43 |
+
|
44 |
+
def bench_R5():
|
45 |
+
"blowup(L, 8); L=uniq(L)"
|
46 |
+
def blowup(L, n):
|
47 |
+
for i in range(n):
|
48 |
+
L.append( (L[i] + L[i + 1]) * L[i + 2] )
|
49 |
+
|
50 |
+
def uniq(x):
|
51 |
+
v = set(x)
|
52 |
+
return v
|
53 |
+
L = [x, y, z]
|
54 |
+
blowup(L, 8)
|
55 |
+
L = uniq(L)
|
56 |
+
|
57 |
+
|
58 |
+
def bench_R6():
|
59 |
+
"sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))"
|
60 |
+
sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100))
|
61 |
+
|
62 |
+
|
63 |
+
def bench_R7():
|
64 |
+
"[f.subs(x, random()) for _ in range(10**4)]"
|
65 |
+
f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21
|
66 |
+
[f.subs(x, random()) for _ in range(10**4)]
|
67 |
+
|
68 |
+
|
69 |
+
def bench_R8():
|
70 |
+
"right(x^2,0,5,10^4)"
|
71 |
+
def right(f, a, b, n):
|
72 |
+
a = sympify(a)
|
73 |
+
b = sympify(b)
|
74 |
+
n = sympify(n)
|
75 |
+
x = f.atoms(Symbol).pop()
|
76 |
+
Deltax = (b - a)/n
|
77 |
+
c = a
|
78 |
+
est = 0
|
79 |
+
for i in range(n):
|
80 |
+
c += Deltax
|
81 |
+
est += f.subs(x, c)
|
82 |
+
return est*Deltax
|
83 |
+
|
84 |
+
right(x**2, 0, 5, 10**4)
|
85 |
+
|
86 |
+
|
87 |
+
def _bench_R9():
|
88 |
+
"factor(x^20 - pi^5*y^20)"
|
89 |
+
factor(x**20 - pi**5*y**20)
|
90 |
+
|
91 |
+
|
92 |
+
def bench_R10():
|
93 |
+
"v = [-pi,-pi+1/10..,pi]"
|
94 |
+
def srange(min, max, step):
|
95 |
+
v = [min]
|
96 |
+
while (max - v[-1]).evalf() > 0:
|
97 |
+
v.append(v[-1] + step)
|
98 |
+
return v[:-1]
|
99 |
+
srange(-pi, pi, sympify(1)/10)
|
100 |
+
|
101 |
+
|
102 |
+
def bench_R11():
|
103 |
+
"a = [random() + random()*I for w in [0..1000]]"
|
104 |
+
[random() + random()*I for w in range(1000)]
|
105 |
+
|
106 |
+
|
107 |
+
def bench_S1():
|
108 |
+
"e=(x+y+z+1)**7;f=e*(e+1);f.expand()"
|
109 |
+
e = (x + y + z + 1)**7
|
110 |
+
f = e*(e + 1)
|
111 |
+
f.expand()
|
112 |
+
|
113 |
+
|
114 |
+
if __name__ == '__main__':
|
115 |
+
benchmarks = [
|
116 |
+
bench_R1,
|
117 |
+
bench_R2,
|
118 |
+
bench_R3,
|
119 |
+
bench_R5,
|
120 |
+
bench_R6,
|
121 |
+
bench_R7,
|
122 |
+
bench_R8,
|
123 |
+
#_bench_R9,
|
124 |
+
bench_R10,
|
125 |
+
bench_R11,
|
126 |
+
#bench_S1,
|
127 |
+
]
|
128 |
+
|
129 |
+
report = []
|
130 |
+
for b in benchmarks:
|
131 |
+
t = clock()
|
132 |
+
b()
|
133 |
+
t = clock() - t
|
134 |
+
print("%s%65s: %f" % (b.__name__, b.__doc__, t))
|
env-llmeval/lib/python3.10/site-packages/sympy/interactive/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Helper module for setting up interactive SymPy sessions. """
|
2 |
+
|
3 |
+
from .printing import init_printing
|
4 |
+
from .session import init_session
|
5 |
+
from .traversal import interactive_traversal
|
6 |
+
|
7 |
+
|
8 |
+
__all__ = ['init_printing', 'init_session', 'interactive_traversal']
|
env-llmeval/lib/python3.10/site-packages/sympy/interactive/printing.py
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tools for setting up printing in interactive sessions. """
|
2 |
+
|
3 |
+
from sympy.external.importtools import version_tuple
|
4 |
+
from io import BytesIO
|
5 |
+
|
6 |
+
from sympy.printing.latex import latex as default_latex
|
7 |
+
from sympy.printing.preview import preview
|
8 |
+
from sympy.utilities.misc import debug
|
9 |
+
from sympy.printing.defaults import Printable
|
10 |
+
|
11 |
+
|
12 |
+
def _init_python_printing(stringify_func, **settings):
|
13 |
+
"""Setup printing in Python interactive session. """
|
14 |
+
import sys
|
15 |
+
import builtins
|
16 |
+
|
17 |
+
def _displayhook(arg):
|
18 |
+
"""Python's pretty-printer display hook.
|
19 |
+
|
20 |
+
This function was adapted from:
|
21 |
+
|
22 |
+
https://www.python.org/dev/peps/pep-0217/
|
23 |
+
|
24 |
+
"""
|
25 |
+
if arg is not None:
|
26 |
+
builtins._ = None
|
27 |
+
print(stringify_func(arg, **settings))
|
28 |
+
builtins._ = arg
|
29 |
+
|
30 |
+
sys.displayhook = _displayhook
|
31 |
+
|
32 |
+
|
33 |
+
def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor,
|
34 |
+
backcolor, fontsize, latex_mode, print_builtin,
|
35 |
+
latex_printer, scale, **settings):
|
36 |
+
"""Setup printing in IPython interactive session. """
|
37 |
+
try:
|
38 |
+
from IPython.lib.latextools import latex_to_png
|
39 |
+
except ImportError:
|
40 |
+
pass
|
41 |
+
|
42 |
+
# Guess best font color if none was given based on the ip.colors string.
|
43 |
+
# From the IPython documentation:
|
44 |
+
# It has four case-insensitive values: 'nocolor', 'neutral', 'linux',
|
45 |
+
# 'lightbg'. The default is neutral, which should be legible on either
|
46 |
+
# dark or light terminal backgrounds. linux is optimised for dark
|
47 |
+
# backgrounds and lightbg for light ones.
|
48 |
+
if forecolor is None:
|
49 |
+
color = ip.colors.lower()
|
50 |
+
if color == 'lightbg':
|
51 |
+
forecolor = 'Black'
|
52 |
+
elif color == 'linux':
|
53 |
+
forecolor = 'White'
|
54 |
+
else:
|
55 |
+
# No idea, go with gray.
|
56 |
+
forecolor = 'Gray'
|
57 |
+
debug("init_printing: Automatic foreground color:", forecolor)
|
58 |
+
|
59 |
+
if use_latex == "svg":
|
60 |
+
extra_preamble = "\n\\special{color %s}" % forecolor
|
61 |
+
else:
|
62 |
+
extra_preamble = ""
|
63 |
+
|
64 |
+
imagesize = 'tight'
|
65 |
+
offset = "0cm,0cm"
|
66 |
+
resolution = round(150*scale)
|
67 |
+
dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % (
|
68 |
+
imagesize, resolution, backcolor, forecolor, offset)
|
69 |
+
dvioptions = dvi.split()
|
70 |
+
|
71 |
+
svg_scale = 150/72*scale
|
72 |
+
dvioptions_svg = ["--no-fonts", "--scale={}".format(svg_scale)]
|
73 |
+
|
74 |
+
debug("init_printing: DVIOPTIONS:", dvioptions)
|
75 |
+
debug("init_printing: DVIOPTIONS_SVG:", dvioptions_svg)
|
76 |
+
|
77 |
+
latex = latex_printer or default_latex
|
78 |
+
|
79 |
+
def _print_plain(arg, p, cycle):
|
80 |
+
"""caller for pretty, for use in IPython 0.11"""
|
81 |
+
if _can_print(arg):
|
82 |
+
p.text(stringify_func(arg))
|
83 |
+
else:
|
84 |
+
p.text(IPython.lib.pretty.pretty(arg))
|
85 |
+
|
86 |
+
def _preview_wrapper(o):
|
87 |
+
exprbuffer = BytesIO()
|
88 |
+
try:
|
89 |
+
preview(o, output='png', viewer='BytesIO', euler=euler,
|
90 |
+
outputbuffer=exprbuffer, extra_preamble=extra_preamble,
|
91 |
+
dvioptions=dvioptions, fontsize=fontsize)
|
92 |
+
except Exception as e:
|
93 |
+
# IPython swallows exceptions
|
94 |
+
debug("png printing:", "_preview_wrapper exception raised:",
|
95 |
+
repr(e))
|
96 |
+
raise
|
97 |
+
return exprbuffer.getvalue()
|
98 |
+
|
99 |
+
def _svg_wrapper(o):
|
100 |
+
exprbuffer = BytesIO()
|
101 |
+
try:
|
102 |
+
preview(o, output='svg', viewer='BytesIO', euler=euler,
|
103 |
+
outputbuffer=exprbuffer, extra_preamble=extra_preamble,
|
104 |
+
dvioptions=dvioptions_svg, fontsize=fontsize)
|
105 |
+
except Exception as e:
|
106 |
+
# IPython swallows exceptions
|
107 |
+
debug("svg printing:", "_preview_wrapper exception raised:",
|
108 |
+
repr(e))
|
109 |
+
raise
|
110 |
+
return exprbuffer.getvalue().decode('utf-8')
|
111 |
+
|
112 |
+
def _matplotlib_wrapper(o):
|
113 |
+
# mathtext can't render some LaTeX commands. For example, it can't
|
114 |
+
# render any LaTeX environments such as array or matrix. So here we
|
115 |
+
# ensure that if mathtext fails to render, we return None.
|
116 |
+
try:
|
117 |
+
try:
|
118 |
+
return latex_to_png(o, color=forecolor, scale=scale)
|
119 |
+
except TypeError: # Old IPython version without color and scale
|
120 |
+
return latex_to_png(o)
|
121 |
+
except ValueError as e:
|
122 |
+
debug('matplotlib exception caught:', repr(e))
|
123 |
+
return None
|
124 |
+
|
125 |
+
|
126 |
+
# Hook methods for builtin SymPy printers
|
127 |
+
printing_hooks = ('_latex', '_sympystr', '_pretty', '_sympyrepr')
|
128 |
+
|
129 |
+
|
130 |
+
def _can_print(o):
|
131 |
+
"""Return True if type o can be printed with one of the SymPy printers.
|
132 |
+
|
133 |
+
If o is a container type, this is True if and only if every element of
|
134 |
+
o can be printed in this way.
|
135 |
+
"""
|
136 |
+
|
137 |
+
try:
|
138 |
+
# If you're adding another type, make sure you add it to printable_types
|
139 |
+
# later in this file as well
|
140 |
+
|
141 |
+
builtin_types = (list, tuple, set, frozenset)
|
142 |
+
if isinstance(o, builtin_types):
|
143 |
+
# If the object is a custom subclass with a custom str or
|
144 |
+
# repr, use that instead.
|
145 |
+
if (type(o).__str__ not in (i.__str__ for i in builtin_types) or
|
146 |
+
type(o).__repr__ not in (i.__repr__ for i in builtin_types)):
|
147 |
+
return False
|
148 |
+
return all(_can_print(i) for i in o)
|
149 |
+
elif isinstance(o, dict):
|
150 |
+
return all(_can_print(i) and _can_print(o[i]) for i in o)
|
151 |
+
elif isinstance(o, bool):
|
152 |
+
return False
|
153 |
+
elif isinstance(o, Printable):
|
154 |
+
# types known to SymPy
|
155 |
+
return True
|
156 |
+
elif any(hasattr(o, hook) for hook in printing_hooks):
|
157 |
+
# types which add support themselves
|
158 |
+
return True
|
159 |
+
elif isinstance(o, (float, int)) and print_builtin:
|
160 |
+
return True
|
161 |
+
return False
|
162 |
+
except RuntimeError:
|
163 |
+
return False
|
164 |
+
# This is in case maximum recursion depth is reached.
|
165 |
+
# Since RecursionError is for versions of Python 3.5+
|
166 |
+
# so this is to guard against RecursionError for older versions.
|
167 |
+
|
168 |
+
def _print_latex_png(o):
|
169 |
+
"""
|
170 |
+
A function that returns a png rendered by an external latex
|
171 |
+
distribution, falling back to matplotlib rendering
|
172 |
+
"""
|
173 |
+
if _can_print(o):
|
174 |
+
s = latex(o, mode=latex_mode, **settings)
|
175 |
+
if latex_mode == 'plain':
|
176 |
+
s = '$\\displaystyle %s$' % s
|
177 |
+
try:
|
178 |
+
return _preview_wrapper(s)
|
179 |
+
except RuntimeError as e:
|
180 |
+
debug('preview failed with:', repr(e),
|
181 |
+
' Falling back to matplotlib backend')
|
182 |
+
if latex_mode != 'inline':
|
183 |
+
s = latex(o, mode='inline', **settings)
|
184 |
+
return _matplotlib_wrapper(s)
|
185 |
+
|
186 |
+
def _print_latex_svg(o):
|
187 |
+
"""
|
188 |
+
A function that returns a svg rendered by an external latex
|
189 |
+
distribution, no fallback available.
|
190 |
+
"""
|
191 |
+
if _can_print(o):
|
192 |
+
s = latex(o, mode=latex_mode, **settings)
|
193 |
+
if latex_mode == 'plain':
|
194 |
+
s = '$\\displaystyle %s$' % s
|
195 |
+
try:
|
196 |
+
return _svg_wrapper(s)
|
197 |
+
except RuntimeError as e:
|
198 |
+
debug('preview failed with:', repr(e),
|
199 |
+
' No fallback available.')
|
200 |
+
|
201 |
+
def _print_latex_matplotlib(o):
|
202 |
+
"""
|
203 |
+
A function that returns a png rendered by mathtext
|
204 |
+
"""
|
205 |
+
if _can_print(o):
|
206 |
+
s = latex(o, mode='inline', **settings)
|
207 |
+
return _matplotlib_wrapper(s)
|
208 |
+
|
209 |
+
def _print_latex_text(o):
|
210 |
+
"""
|
211 |
+
A function to generate the latex representation of SymPy expressions.
|
212 |
+
"""
|
213 |
+
if _can_print(o):
|
214 |
+
s = latex(o, mode=latex_mode, **settings)
|
215 |
+
if latex_mode == 'plain':
|
216 |
+
return '$\\displaystyle %s$' % s
|
217 |
+
return s
|
218 |
+
|
219 |
+
def _result_display(self, arg):
|
220 |
+
"""IPython's pretty-printer display hook, for use in IPython 0.10
|
221 |
+
|
222 |
+
This function was adapted from:
|
223 |
+
|
224 |
+
ipython/IPython/hooks.py:155
|
225 |
+
|
226 |
+
"""
|
227 |
+
if self.rc.pprint:
|
228 |
+
out = stringify_func(arg)
|
229 |
+
|
230 |
+
if '\n' in out:
|
231 |
+
print()
|
232 |
+
|
233 |
+
print(out)
|
234 |
+
else:
|
235 |
+
print(repr(arg))
|
236 |
+
|
237 |
+
import IPython
|
238 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
239 |
+
|
240 |
+
# Printable is our own type, so we handle it with methods instead of
|
241 |
+
# the approach required by builtin types. This allows downstream
|
242 |
+
# packages to override the methods in their own subclasses of Printable,
|
243 |
+
# which avoids the effects of gh-16002.
|
244 |
+
printable_types = [float, tuple, list, set, frozenset, dict, int]
|
245 |
+
|
246 |
+
plaintext_formatter = ip.display_formatter.formatters['text/plain']
|
247 |
+
|
248 |
+
# Exception to the rule above: IPython has better dispatching rules
|
249 |
+
# for plaintext printing (xref ipython/ipython#8938), and we can't
|
250 |
+
# use `_repr_pretty_` without hitting a recursion error in _print_plain.
|
251 |
+
for cls in printable_types + [Printable]:
|
252 |
+
plaintext_formatter.for_type(cls, _print_plain)
|
253 |
+
|
254 |
+
svg_formatter = ip.display_formatter.formatters['image/svg+xml']
|
255 |
+
if use_latex in ('svg', ):
|
256 |
+
debug("init_printing: using svg formatter")
|
257 |
+
for cls in printable_types:
|
258 |
+
svg_formatter.for_type(cls, _print_latex_svg)
|
259 |
+
Printable._repr_svg_ = _print_latex_svg
|
260 |
+
else:
|
261 |
+
debug("init_printing: not using any svg formatter")
|
262 |
+
for cls in printable_types:
|
263 |
+
# Better way to set this, but currently does not work in IPython
|
264 |
+
#png_formatter.for_type(cls, None)
|
265 |
+
if cls in svg_formatter.type_printers:
|
266 |
+
svg_formatter.type_printers.pop(cls)
|
267 |
+
Printable._repr_svg_ = Printable._repr_disabled
|
268 |
+
|
269 |
+
png_formatter = ip.display_formatter.formatters['image/png']
|
270 |
+
if use_latex in (True, 'png'):
|
271 |
+
debug("init_printing: using png formatter")
|
272 |
+
for cls in printable_types:
|
273 |
+
png_formatter.for_type(cls, _print_latex_png)
|
274 |
+
Printable._repr_png_ = _print_latex_png
|
275 |
+
elif use_latex == 'matplotlib':
|
276 |
+
debug("init_printing: using matplotlib formatter")
|
277 |
+
for cls in printable_types:
|
278 |
+
png_formatter.for_type(cls, _print_latex_matplotlib)
|
279 |
+
Printable._repr_png_ = _print_latex_matplotlib
|
280 |
+
else:
|
281 |
+
debug("init_printing: not using any png formatter")
|
282 |
+
for cls in printable_types:
|
283 |
+
# Better way to set this, but currently does not work in IPython
|
284 |
+
#png_formatter.for_type(cls, None)
|
285 |
+
if cls in png_formatter.type_printers:
|
286 |
+
png_formatter.type_printers.pop(cls)
|
287 |
+
Printable._repr_png_ = Printable._repr_disabled
|
288 |
+
|
289 |
+
latex_formatter = ip.display_formatter.formatters['text/latex']
|
290 |
+
if use_latex in (True, 'mathjax'):
|
291 |
+
debug("init_printing: using mathjax formatter")
|
292 |
+
for cls in printable_types:
|
293 |
+
latex_formatter.for_type(cls, _print_latex_text)
|
294 |
+
Printable._repr_latex_ = _print_latex_text
|
295 |
+
else:
|
296 |
+
debug("init_printing: not using text/latex formatter")
|
297 |
+
for cls in printable_types:
|
298 |
+
# Better way to set this, but currently does not work in IPython
|
299 |
+
#latex_formatter.for_type(cls, None)
|
300 |
+
if cls in latex_formatter.type_printers:
|
301 |
+
latex_formatter.type_printers.pop(cls)
|
302 |
+
Printable._repr_latex_ = Printable._repr_disabled
|
303 |
+
|
304 |
+
else:
|
305 |
+
ip.set_hook('result_display', _result_display)
|
306 |
+
|
307 |
+
def _is_ipython(shell):
|
308 |
+
"""Is a shell instance an IPython shell?"""
|
309 |
+
# shortcut, so we don't import IPython if we don't have to
|
310 |
+
from sys import modules
|
311 |
+
if 'IPython' not in modules:
|
312 |
+
return False
|
313 |
+
try:
|
314 |
+
from IPython.core.interactiveshell import InteractiveShell
|
315 |
+
except ImportError:
|
316 |
+
# IPython < 0.11
|
317 |
+
try:
|
318 |
+
from IPython.iplib import InteractiveShell
|
319 |
+
except ImportError:
|
320 |
+
# Reaching this points means IPython has changed in a backward-incompatible way
|
321 |
+
# that we don't know about. Warn?
|
322 |
+
return False
|
323 |
+
return isinstance(shell, InteractiveShell)
|
324 |
+
|
325 |
+
# Used by the doctester to override the default for no_global
|
326 |
+
NO_GLOBAL = False
|
327 |
+
|
328 |
+
def init_printing(pretty_print=True, order=None, use_unicode=None,
|
329 |
+
use_latex=None, wrap_line=None, num_columns=None,
|
330 |
+
no_global=False, ip=None, euler=False, forecolor=None,
|
331 |
+
backcolor='Transparent', fontsize='10pt',
|
332 |
+
latex_mode='plain', print_builtin=True,
|
333 |
+
str_printer=None, pretty_printer=None,
|
334 |
+
latex_printer=None, scale=1.0, **settings):
|
335 |
+
r"""
|
336 |
+
Initializes pretty-printer depending on the environment.
|
337 |
+
|
338 |
+
Parameters
|
339 |
+
==========
|
340 |
+
|
341 |
+
pretty_print : bool, default=True
|
342 |
+
If ``True``, use :func:`~.pretty_print` to stringify or the provided pretty
|
343 |
+
printer; if ``False``, use :func:`~.sstrrepr` to stringify or the provided string
|
344 |
+
printer.
|
345 |
+
order : string or None, default='lex'
|
346 |
+
There are a few different settings for this parameter:
|
347 |
+
``'lex'`` (default), which is lexographic order;
|
348 |
+
``'grlex'``, which is graded lexographic order;
|
349 |
+
``'grevlex'``, which is reversed graded lexographic order;
|
350 |
+
``'old'``, which is used for compatibility reasons and for long expressions;
|
351 |
+
``None``, which sets it to lex.
|
352 |
+
use_unicode : bool or None, default=None
|
353 |
+
If ``True``, use unicode characters;
|
354 |
+
if ``False``, do not use unicode characters;
|
355 |
+
if ``None``, make a guess based on the environment.
|
356 |
+
use_latex : string, bool, or None, default=None
|
357 |
+
If ``True``, use default LaTeX rendering in GUI interfaces (png and
|
358 |
+
mathjax);
|
359 |
+
if ``False``, do not use LaTeX rendering;
|
360 |
+
if ``None``, make a guess based on the environment;
|
361 |
+
if ``'png'``, enable LaTeX rendering with an external LaTeX compiler,
|
362 |
+
falling back to matplotlib if external compilation fails;
|
363 |
+
if ``'matplotlib'``, enable LaTeX rendering with matplotlib;
|
364 |
+
if ``'mathjax'``, enable LaTeX text generation, for example MathJax
|
365 |
+
rendering in IPython notebook or text rendering in LaTeX documents;
|
366 |
+
if ``'svg'``, enable LaTeX rendering with an external latex compiler,
|
367 |
+
no fallback
|
368 |
+
wrap_line : bool
|
369 |
+
If True, lines will wrap at the end; if False, they will not wrap
|
370 |
+
but continue as one line. This is only relevant if ``pretty_print`` is
|
371 |
+
True.
|
372 |
+
num_columns : int or None, default=None
|
373 |
+
If ``int``, number of columns before wrapping is set to num_columns; if
|
374 |
+
``None``, number of columns before wrapping is set to terminal width.
|
375 |
+
This is only relevant if ``pretty_print`` is ``True``.
|
376 |
+
no_global : bool, default=False
|
377 |
+
If ``True``, the settings become system wide;
|
378 |
+
if ``False``, use just for this console/session.
|
379 |
+
ip : An interactive console
|
380 |
+
This can either be an instance of IPython,
|
381 |
+
or a class that derives from code.InteractiveConsole.
|
382 |
+
euler : bool, optional, default=False
|
383 |
+
Loads the euler package in the LaTeX preamble for handwritten style
|
384 |
+
fonts (https://www.ctan.org/pkg/euler).
|
385 |
+
forecolor : string or None, optional, default=None
|
386 |
+
DVI setting for foreground color. ``None`` means that either ``'Black'``,
|
387 |
+
``'White'``, or ``'Gray'`` will be selected based on a guess of the IPython
|
388 |
+
terminal color setting. See notes.
|
389 |
+
backcolor : string, optional, default='Transparent'
|
390 |
+
DVI setting for background color. See notes.
|
391 |
+
fontsize : string or int, optional, default='10pt'
|
392 |
+
A font size to pass to the LaTeX documentclass function in the
|
393 |
+
preamble. Note that the options are limited by the documentclass.
|
394 |
+
Consider using scale instead.
|
395 |
+
latex_mode : string, optional, default='plain'
|
396 |
+
The mode used in the LaTeX printer. Can be one of:
|
397 |
+
``{'inline'|'plain'|'equation'|'equation*'}``.
|
398 |
+
print_builtin : boolean, optional, default=True
|
399 |
+
If ``True`` then floats and integers will be printed. If ``False`` the
|
400 |
+
printer will only print SymPy types.
|
401 |
+
str_printer : function, optional, default=None
|
402 |
+
A custom string printer function. This should mimic
|
403 |
+
:func:`~.sstrrepr()`.
|
404 |
+
pretty_printer : function, optional, default=None
|
405 |
+
A custom pretty printer. This should mimic :func:`~.pretty()`.
|
406 |
+
latex_printer : function, optional, default=None
|
407 |
+
A custom LaTeX printer. This should mimic :func:`~.latex()`.
|
408 |
+
scale : float, optional, default=1.0
|
409 |
+
Scale the LaTeX output when using the ``'png'`` or ``'svg'`` backends.
|
410 |
+
Useful for high dpi screens.
|
411 |
+
settings :
|
412 |
+
Any additional settings for the ``latex`` and ``pretty`` commands can
|
413 |
+
be used to fine-tune the output.
|
414 |
+
|
415 |
+
Examples
|
416 |
+
========
|
417 |
+
|
418 |
+
>>> from sympy.interactive import init_printing
|
419 |
+
>>> from sympy import Symbol, sqrt
|
420 |
+
>>> from sympy.abc import x, y
|
421 |
+
>>> sqrt(5)
|
422 |
+
sqrt(5)
|
423 |
+
>>> init_printing(pretty_print=True) # doctest: +SKIP
|
424 |
+
>>> sqrt(5) # doctest: +SKIP
|
425 |
+
___
|
426 |
+
\/ 5
|
427 |
+
>>> theta = Symbol('theta') # doctest: +SKIP
|
428 |
+
>>> init_printing(use_unicode=True) # doctest: +SKIP
|
429 |
+
>>> theta # doctest: +SKIP
|
430 |
+
\u03b8
|
431 |
+
>>> init_printing(use_unicode=False) # doctest: +SKIP
|
432 |
+
>>> theta # doctest: +SKIP
|
433 |
+
theta
|
434 |
+
>>> init_printing(order='lex') # doctest: +SKIP
|
435 |
+
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
|
436 |
+
x**2 + x + y**2 + y
|
437 |
+
>>> init_printing(order='grlex') # doctest: +SKIP
|
438 |
+
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
|
439 |
+
x**2 + x + y**2 + y
|
440 |
+
>>> init_printing(order='grevlex') # doctest: +SKIP
|
441 |
+
>>> str(y * x**2 + x * y**2) # doctest: +SKIP
|
442 |
+
x**2*y + x*y**2
|
443 |
+
>>> init_printing(order='old') # doctest: +SKIP
|
444 |
+
>>> str(x**2 + y**2 + x + y) # doctest: +SKIP
|
445 |
+
x**2 + x + y**2 + y
|
446 |
+
>>> init_printing(num_columns=10) # doctest: +SKIP
|
447 |
+
>>> x**2 + x + y**2 + y # doctest: +SKIP
|
448 |
+
x + y +
|
449 |
+
x**2 + y**2
|
450 |
+
|
451 |
+
Notes
|
452 |
+
=====
|
453 |
+
|
454 |
+
The foreground and background colors can be selected when using ``'png'`` or
|
455 |
+
``'svg'`` LaTeX rendering. Note that before the ``init_printing`` command is
|
456 |
+
executed, the LaTeX rendering is handled by the IPython console and not SymPy.
|
457 |
+
|
458 |
+
The colors can be selected among the 68 standard colors known to ``dvips``,
|
459 |
+
for a list see [1]_. In addition, the background color can be
|
460 |
+
set to ``'Transparent'`` (which is the default value).
|
461 |
+
|
462 |
+
When using the ``'Auto'`` foreground color, the guess is based on the
|
463 |
+
``colors`` variable in the IPython console, see [2]_. Hence, if
|
464 |
+
that variable is set correctly in your IPython console, there is a high
|
465 |
+
chance that the output will be readable, although manual settings may be
|
466 |
+
needed.
|
467 |
+
|
468 |
+
|
469 |
+
References
|
470 |
+
==========
|
471 |
+
|
472 |
+
.. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
|
473 |
+
|
474 |
+
.. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors
|
475 |
+
|
476 |
+
See Also
|
477 |
+
========
|
478 |
+
|
479 |
+
sympy.printing.latex
|
480 |
+
sympy.printing.pretty
|
481 |
+
|
482 |
+
"""
|
483 |
+
import sys
|
484 |
+
from sympy.printing.printer import Printer
|
485 |
+
|
486 |
+
if pretty_print:
|
487 |
+
if pretty_printer is not None:
|
488 |
+
stringify_func = pretty_printer
|
489 |
+
else:
|
490 |
+
from sympy.printing import pretty as stringify_func
|
491 |
+
else:
|
492 |
+
if str_printer is not None:
|
493 |
+
stringify_func = str_printer
|
494 |
+
else:
|
495 |
+
from sympy.printing import sstrrepr as stringify_func
|
496 |
+
|
497 |
+
# Even if ip is not passed, double check that not in IPython shell
|
498 |
+
in_ipython = False
|
499 |
+
if ip is None:
|
500 |
+
try:
|
501 |
+
ip = get_ipython()
|
502 |
+
except NameError:
|
503 |
+
pass
|
504 |
+
else:
|
505 |
+
in_ipython = (ip is not None)
|
506 |
+
|
507 |
+
if ip and not in_ipython:
|
508 |
+
in_ipython = _is_ipython(ip)
|
509 |
+
|
510 |
+
if in_ipython and pretty_print:
|
511 |
+
try:
|
512 |
+
import IPython
|
513 |
+
# IPython 1.0 deprecates the frontend module, so we import directly
|
514 |
+
# from the terminal module to prevent a deprecation message from being
|
515 |
+
# shown.
|
516 |
+
if version_tuple(IPython.__version__) >= version_tuple('1.0'):
|
517 |
+
from IPython.terminal.interactiveshell import TerminalInteractiveShell
|
518 |
+
else:
|
519 |
+
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
|
520 |
+
from code import InteractiveConsole
|
521 |
+
except ImportError:
|
522 |
+
pass
|
523 |
+
else:
|
524 |
+
# This will be True if we are in the qtconsole or notebook
|
525 |
+
if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \
|
526 |
+
and 'ipython-console' not in ''.join(sys.argv):
|
527 |
+
if use_unicode is None:
|
528 |
+
debug("init_printing: Setting use_unicode to True")
|
529 |
+
use_unicode = True
|
530 |
+
if use_latex is None:
|
531 |
+
debug("init_printing: Setting use_latex to True")
|
532 |
+
use_latex = True
|
533 |
+
|
534 |
+
if not NO_GLOBAL and not no_global:
|
535 |
+
Printer.set_global_settings(order=order, use_unicode=use_unicode,
|
536 |
+
wrap_line=wrap_line, num_columns=num_columns)
|
537 |
+
else:
|
538 |
+
_stringify_func = stringify_func
|
539 |
+
|
540 |
+
if pretty_print:
|
541 |
+
stringify_func = lambda expr, **settings: \
|
542 |
+
_stringify_func(expr, order=order,
|
543 |
+
use_unicode=use_unicode,
|
544 |
+
wrap_line=wrap_line,
|
545 |
+
num_columns=num_columns,
|
546 |
+
**settings)
|
547 |
+
else:
|
548 |
+
stringify_func = \
|
549 |
+
lambda expr, **settings: _stringify_func(
|
550 |
+
expr, order=order, **settings)
|
551 |
+
|
552 |
+
if in_ipython:
|
553 |
+
mode_in_settings = settings.pop("mode", None)
|
554 |
+
if mode_in_settings:
|
555 |
+
debug("init_printing: Mode is not able to be set due to internals"
|
556 |
+
"of IPython printing")
|
557 |
+
_init_ipython_printing(ip, stringify_func, use_latex, euler,
|
558 |
+
forecolor, backcolor, fontsize, latex_mode,
|
559 |
+
print_builtin, latex_printer, scale,
|
560 |
+
**settings)
|
561 |
+
else:
|
562 |
+
_init_python_printing(stringify_func, **settings)
|
env-llmeval/lib/python3.10/site-packages/sympy/interactive/traversal.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.printing import pprint
|
3 |
+
|
4 |
+
import random
|
5 |
+
|
6 |
+
def interactive_traversal(expr):
|
7 |
+
"""Traverse a tree asking a user which branch to choose. """
|
8 |
+
|
9 |
+
RED, BRED = '\033[0;31m', '\033[1;31m'
|
10 |
+
GREEN, BGREEN = '\033[0;32m', '\033[1;32m'
|
11 |
+
YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m' # noqa
|
12 |
+
BLUE, BBLUE = '\033[0;34m', '\033[1;34m' # noqa
|
13 |
+
MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'# noqa
|
14 |
+
CYAN, BCYAN = '\033[0;36m', '\033[1;36m' # noqa
|
15 |
+
END = '\033[0m'
|
16 |
+
|
17 |
+
def cprint(*args):
|
18 |
+
print("".join(map(str, args)) + END)
|
19 |
+
|
20 |
+
def _interactive_traversal(expr, stage):
|
21 |
+
if stage > 0:
|
22 |
+
print()
|
23 |
+
|
24 |
+
cprint("Current expression (stage ", BYELLOW, stage, END, "):")
|
25 |
+
print(BCYAN)
|
26 |
+
pprint(expr)
|
27 |
+
print(END)
|
28 |
+
|
29 |
+
if isinstance(expr, Basic):
|
30 |
+
if expr.is_Add:
|
31 |
+
args = expr.as_ordered_terms()
|
32 |
+
elif expr.is_Mul:
|
33 |
+
args = expr.as_ordered_factors()
|
34 |
+
else:
|
35 |
+
args = expr.args
|
36 |
+
elif hasattr(expr, "__iter__"):
|
37 |
+
args = list(expr)
|
38 |
+
else:
|
39 |
+
return expr
|
40 |
+
|
41 |
+
n_args = len(args)
|
42 |
+
|
43 |
+
if not n_args:
|
44 |
+
return expr
|
45 |
+
|
46 |
+
for i, arg in enumerate(args):
|
47 |
+
cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END)
|
48 |
+
pprint(arg)
|
49 |
+
print()
|
50 |
+
|
51 |
+
if n_args == 1:
|
52 |
+
choices = '0'
|
53 |
+
else:
|
54 |
+
choices = '0-%d' % (n_args - 1)
|
55 |
+
|
56 |
+
try:
|
57 |
+
choice = input("Your choice [%s,f,l,r,d,?]: " % choices)
|
58 |
+
except EOFError:
|
59 |
+
result = expr
|
60 |
+
print()
|
61 |
+
else:
|
62 |
+
if choice == '?':
|
63 |
+
cprint(RED, "%s - select subexpression with the given index" %
|
64 |
+
choices)
|
65 |
+
cprint(RED, "f - select the first subexpression")
|
66 |
+
cprint(RED, "l - select the last subexpression")
|
67 |
+
cprint(RED, "r - select a random subexpression")
|
68 |
+
cprint(RED, "d - done\n")
|
69 |
+
|
70 |
+
result = _interactive_traversal(expr, stage)
|
71 |
+
elif choice in ('d', ''):
|
72 |
+
result = expr
|
73 |
+
elif choice == 'f':
|
74 |
+
result = _interactive_traversal(args[0], stage + 1)
|
75 |
+
elif choice == 'l':
|
76 |
+
result = _interactive_traversal(args[-1], stage + 1)
|
77 |
+
elif choice == 'r':
|
78 |
+
result = _interactive_traversal(random.choice(args), stage + 1)
|
79 |
+
else:
|
80 |
+
try:
|
81 |
+
choice = int(choice)
|
82 |
+
except ValueError:
|
83 |
+
cprint(BRED,
|
84 |
+
"Choice must be a number in %s range\n" % choices)
|
85 |
+
result = _interactive_traversal(expr, stage)
|
86 |
+
else:
|
87 |
+
if choice < 0 or choice >= n_args:
|
88 |
+
cprint(BRED, "Choice must be in %s range\n" % choices)
|
89 |
+
result = _interactive_traversal(expr, stage)
|
90 |
+
else:
|
91 |
+
result = _interactive_traversal(args[choice], stage + 1)
|
92 |
+
|
93 |
+
return result
|
94 |
+
|
95 |
+
return _interactive_traversal(expr, 0)
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.94 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc
ADDED
Binary file (3.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc
ADDED
Binary file (23.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc
ADDED
Binary file (29.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc
ADDED
Binary file (12.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc
ADDED
Binary file (22.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc
ADDED
Binary file (105 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (189 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc
ADDED
Binary file (729 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import Symbol
|
2 |
+
from sympy.matrices.dense import (eye, zeros)
|
3 |
+
from sympy.solvers.solvers import solve_linear_system
|
4 |
+
|
5 |
+
N = 8
|
6 |
+
M = zeros(N, N + 1)
|
7 |
+
M[:, :N] = eye(N)
|
8 |
+
S = [Symbol('A%i' % i) for i in range(N)]
|
9 |
+
|
10 |
+
|
11 |
+
def timeit_linsolve_trivial():
|
12 |
+
solve_linear_system(M, *S)
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (184 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_polysys.cpython-310.pyc
ADDED
Binary file (7.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc
ADDED
Binary file (106 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_constantsimp.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
If the arbitrary constant class from issue 4435 is ever implemented, this
|
3 |
+
should serve as a set of test cases.
|
4 |
+
"""
|
5 |
+
|
6 |
+
from sympy.core.function import Function
|
7 |
+
from sympy.core.numbers import I
|
8 |
+
from sympy.core.power import Pow
|
9 |
+
from sympy.core.relational import Eq
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.core.symbol import Symbol
|
12 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
13 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh)
|
14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
15 |
+
from sympy.functions.elementary.trigonometric import (acos, cos, sin)
|
16 |
+
from sympy.integrals.integrals import Integral
|
17 |
+
from sympy.solvers.ode.ode import constantsimp, constant_renumber
|
18 |
+
from sympy.testing.pytest import XFAIL
|
19 |
+
|
20 |
+
|
21 |
+
x = Symbol('x')
|
22 |
+
y = Symbol('y')
|
23 |
+
z = Symbol('z')
|
24 |
+
u2 = Symbol('u2')
|
25 |
+
_a = Symbol('_a')
|
26 |
+
C1 = Symbol('C1')
|
27 |
+
C2 = Symbol('C2')
|
28 |
+
C3 = Symbol('C3')
|
29 |
+
f = Function('f')
|
30 |
+
|
31 |
+
|
32 |
+
def test_constant_mul():
|
33 |
+
# We want C1 (Constant) below to absorb the y's, but not the x's
|
34 |
+
assert constant_renumber(constantsimp(y*C1, [C1])) == C1*y
|
35 |
+
assert constant_renumber(constantsimp(C1*y, [C1])) == C1*y
|
36 |
+
assert constant_renumber(constantsimp(x*C1, [C1])) == x*C1
|
37 |
+
assert constant_renumber(constantsimp(C1*x, [C1])) == x*C1
|
38 |
+
assert constant_renumber(constantsimp(2*C1, [C1])) == C1
|
39 |
+
assert constant_renumber(constantsimp(C1*2, [C1])) == C1
|
40 |
+
assert constant_renumber(constantsimp(y*C1*x, [C1, y])) == C1*x
|
41 |
+
assert constant_renumber(constantsimp(x*y*C1, [C1, y])) == x*C1
|
42 |
+
assert constant_renumber(constantsimp(y*x*C1, [C1, y])) == x*C1
|
43 |
+
assert constant_renumber(constantsimp(C1*x*y, [C1, y])) == C1*x
|
44 |
+
assert constant_renumber(constantsimp(x*C1*y, [C1, y])) == x*C1
|
45 |
+
assert constant_renumber(constantsimp(C1*y*(y + 1), [C1])) == C1*y*(y+1)
|
46 |
+
assert constant_renumber(constantsimp(y*C1*(y + 1), [C1])) == C1*y*(y+1)
|
47 |
+
assert constant_renumber(constantsimp(x*(y*C1), [C1])) == x*y*C1
|
48 |
+
assert constant_renumber(constantsimp(x*(C1*y), [C1])) == x*y*C1
|
49 |
+
assert constant_renumber(constantsimp(C1*(x*y), [C1, y])) == C1*x
|
50 |
+
assert constant_renumber(constantsimp((x*y)*C1, [C1, y])) == x*C1
|
51 |
+
assert constant_renumber(constantsimp((y*x)*C1, [C1, y])) == x*C1
|
52 |
+
assert constant_renumber(constantsimp(y*(y + 1)*C1, [C1, y])) == C1
|
53 |
+
assert constant_renumber(constantsimp((C1*x)*y, [C1, y])) == C1*x
|
54 |
+
assert constant_renumber(constantsimp(y*(x*C1), [C1, y])) == x*C1
|
55 |
+
assert constant_renumber(constantsimp((x*C1)*y, [C1, y])) == x*C1
|
56 |
+
assert constant_renumber(constantsimp(C1*x*y*x*y*2, [C1, y])) == C1*x**2
|
57 |
+
assert constant_renumber(constantsimp(C1*x*y*z, [C1, y, z])) == C1*x
|
58 |
+
assert constant_renumber(constantsimp(C1*x*y**2*sin(z), [C1, y, z])) == C1*x
|
59 |
+
assert constant_renumber(constantsimp(C1*C1, [C1])) == C1
|
60 |
+
assert constant_renumber(constantsimp(C1*C2, [C1, C2])) == C1
|
61 |
+
assert constant_renumber(constantsimp(C2*C2, [C1, C2])) == C1
|
62 |
+
assert constant_renumber(constantsimp(C1*C1*C2, [C1, C2])) == C1
|
63 |
+
assert constant_renumber(constantsimp(C1*x*2**x, [C1])) == C1*x*2**x
|
64 |
+
|
65 |
+
def test_constant_add():
|
66 |
+
assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1
|
67 |
+
assert constant_renumber(constantsimp(C1 + 2, [C1])) == C1
|
68 |
+
assert constant_renumber(constantsimp(2 + C1, [C1])) == C1
|
69 |
+
assert constant_renumber(constantsimp(C1 + y, [C1, y])) == C1
|
70 |
+
assert constant_renumber(constantsimp(C1 + x, [C1])) == C1 + x
|
71 |
+
assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1
|
72 |
+
assert constant_renumber(constantsimp(C1 + C2, [C1, C2])) == C1
|
73 |
+
assert constant_renumber(constantsimp(C2 + C1, [C1, C2])) == C1
|
74 |
+
assert constant_renumber(constantsimp(C1 + C2 + C1, [C1, C2])) == C1
|
75 |
+
|
76 |
+
|
77 |
+
def test_constant_power_as_base():
|
78 |
+
assert constant_renumber(constantsimp(C1**C1, [C1])) == C1
|
79 |
+
assert constant_renumber(constantsimp(Pow(C1, C1), [C1])) == C1
|
80 |
+
assert constant_renumber(constantsimp(C1**C1, [C1])) == C1
|
81 |
+
assert constant_renumber(constantsimp(C1**C2, [C1, C2])) == C1
|
82 |
+
assert constant_renumber(constantsimp(C2**C1, [C1, C2])) == C1
|
83 |
+
assert constant_renumber(constantsimp(C2**C2, [C1, C2])) == C1
|
84 |
+
assert constant_renumber(constantsimp(C1**y, [C1, y])) == C1
|
85 |
+
assert constant_renumber(constantsimp(C1**x, [C1])) == C1**x
|
86 |
+
assert constant_renumber(constantsimp(C1**2, [C1])) == C1
|
87 |
+
assert constant_renumber(
|
88 |
+
constantsimp(C1**(x*y), [C1])) == C1**(x*y)
|
89 |
+
|
90 |
+
|
91 |
+
def test_constant_power_as_exp():
|
92 |
+
assert constant_renumber(constantsimp(x**C1, [C1])) == x**C1
|
93 |
+
assert constant_renumber(constantsimp(y**C1, [C1, y])) == C1
|
94 |
+
assert constant_renumber(constantsimp(x**y**C1, [C1, y])) == x**C1
|
95 |
+
assert constant_renumber(
|
96 |
+
constantsimp((x**y)**C1, [C1])) == (x**y)**C1
|
97 |
+
assert constant_renumber(
|
98 |
+
constantsimp(x**(y**C1), [C1, y])) == x**C1
|
99 |
+
assert constant_renumber(constantsimp(x**C1**y, [C1, y])) == x**C1
|
100 |
+
assert constant_renumber(
|
101 |
+
constantsimp(x**(C1**y), [C1, y])) == x**C1
|
102 |
+
assert constant_renumber(
|
103 |
+
constantsimp((x**C1)**y, [C1])) == (x**C1)**y
|
104 |
+
assert constant_renumber(constantsimp(2**C1, [C1])) == C1
|
105 |
+
assert constant_renumber(constantsimp(S(2)**C1, [C1])) == C1
|
106 |
+
assert constant_renumber(constantsimp(exp(C1), [C1])) == C1
|
107 |
+
assert constant_renumber(
|
108 |
+
constantsimp(exp(C1 + x), [C1])) == C1*exp(x)
|
109 |
+
assert constant_renumber(constantsimp(Pow(2, C1), [C1])) == C1
|
110 |
+
|
111 |
+
|
112 |
+
def test_constant_function():
|
113 |
+
assert constant_renumber(constantsimp(sin(C1), [C1])) == C1
|
114 |
+
assert constant_renumber(constantsimp(f(C1), [C1])) == C1
|
115 |
+
assert constant_renumber(constantsimp(f(C1, C1), [C1])) == C1
|
116 |
+
assert constant_renumber(constantsimp(f(C1, C2), [C1, C2])) == C1
|
117 |
+
assert constant_renumber(constantsimp(f(C2, C1), [C1, C2])) == C1
|
118 |
+
assert constant_renumber(constantsimp(f(C2, C2), [C1, C2])) == C1
|
119 |
+
assert constant_renumber(
|
120 |
+
constantsimp(f(C1, x), [C1])) == f(C1, x)
|
121 |
+
assert constant_renumber(constantsimp(f(C1, y), [C1, y])) == C1
|
122 |
+
assert constant_renumber(constantsimp(f(y, C1), [C1, y])) == C1
|
123 |
+
assert constant_renumber(constantsimp(f(C1, y, C2), [C1, C2, y])) == C1
|
124 |
+
|
125 |
+
|
126 |
+
def test_constant_function_multiple():
|
127 |
+
# The rules to not renumber in this case would be too complicated, and
|
128 |
+
# dsolve is not likely to ever encounter anything remotely like this.
|
129 |
+
assert constant_renumber(
|
130 |
+
constantsimp(f(C1, C1, x), [C1])) == f(C1, C1, x)
|
131 |
+
|
132 |
+
|
133 |
+
def test_constant_multiple():
|
134 |
+
assert constant_renumber(constantsimp(C1*2 + 2, [C1])) == C1
|
135 |
+
assert constant_renumber(constantsimp(x*2/C1, [C1])) == C1*x
|
136 |
+
assert constant_renumber(constantsimp(C1**2*2 + 2, [C1])) == C1
|
137 |
+
assert constant_renumber(
|
138 |
+
constantsimp(sin(2*C1) + x + sqrt(2), [C1])) == C1 + x
|
139 |
+
assert constant_renumber(constantsimp(2*C1 + C2, [C1, C2])) == C1
|
140 |
+
|
141 |
+
def test_constant_repeated():
|
142 |
+
assert C1 + C1*x == constant_renumber( C1 + C1*x)
|
143 |
+
|
144 |
+
def test_ode_solutions():
|
145 |
+
# only a few examples here, the rest will be tested in the actual dsolve tests
|
146 |
+
assert constant_renumber(constantsimp(C1*exp(2*x) + exp(x)*(C2 + C3), [C1, C2, C3])) == \
|
147 |
+
constant_renumber(C1*exp(x) + C2*exp(2*x))
|
148 |
+
assert constant_renumber(
|
149 |
+
constantsimp(Eq(f(x), I*C1*sinh(x/3) + C2*cosh(x/3)), [C1, C2])
|
150 |
+
) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)))
|
151 |
+
assert constant_renumber(constantsimp(Eq(f(x), acos((-C1)/cos(x))), [C1])) == \
|
152 |
+
Eq(f(x), acos(C1/cos(x)))
|
153 |
+
assert constant_renumber(
|
154 |
+
constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), [C1])
|
155 |
+
) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0)
|
156 |
+
assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x))
|
157 |
+
/C1) + x**2/(2*f(x)**2), 0), [C1])) == \
|
158 |
+
Eq(log(C1*sqrt(x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
|
159 |
+
assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) -
|
160 |
+
cos(f(x)/x)*exp(-f(x)/x)/2, 0), [C1])) == \
|
161 |
+
Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*
|
162 |
+
exp(-f(x)/x)/2, 0)
|
163 |
+
assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2),
|
164 |
+
(u2, _a, x/f(x))) + log(f(x)/C1), 0), [C1])) == \
|
165 |
+
Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) +
|
166 |
+
log(C1*f(x)), 0)
|
167 |
+
assert [constantsimp(i, [C1]) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == \
|
168 |
+
[Eq(f(x), sqrt(x*(C1 + x))), Eq(f(x), -sqrt(x*(C1 + x)))]
|
169 |
+
|
170 |
+
|
171 |
+
@XFAIL
|
172 |
+
def test_nonlocal_simplification():
|
173 |
+
assert constantsimp(C1 + C2+x*C2, [C1, C2]) == C1 + C2*x
|
174 |
+
|
175 |
+
|
176 |
+
def test_constant_Eq():
|
177 |
+
# C1 on the rhs is well-tested, but the lhs is only tested here
|
178 |
+
assert constantsimp(Eq(C1, 3 + f(x)*x), [C1]) == Eq(x*f(x), C1)
|
179 |
+
assert constantsimp(Eq(C1, 3 * f(x)*x), [C1]) == Eq(f(x)*x, C1)
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_decompogen.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.solvers.decompogen import decompogen, compogen
|
2 |
+
from sympy.core.symbol import symbols
|
3 |
+
from sympy.functions.elementary.complexes import Abs
|
4 |
+
from sympy.functions.elementary.exponential import exp
|
5 |
+
from sympy.functions.elementary.miscellaneous import sqrt, Max
|
6 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
7 |
+
from sympy.testing.pytest import XFAIL, raises
|
8 |
+
|
9 |
+
x, y = symbols('x y')
|
10 |
+
|
11 |
+
|
12 |
+
def test_decompogen():
|
13 |
+
assert decompogen(sin(cos(x)), x) == [sin(x), cos(x)]
|
14 |
+
assert decompogen(sin(x)**2 + sin(x) + 1, x) == [x**2 + x + 1, sin(x)]
|
15 |
+
assert decompogen(sqrt(6*x**2 - 5), x) == [sqrt(x), 6*x**2 - 5]
|
16 |
+
assert decompogen(sin(sqrt(cos(x**2 + 1))), x) == [sin(x), sqrt(x), cos(x), x**2 + 1]
|
17 |
+
assert decompogen(Abs(cos(x)**2 + 3*cos(x) - 4), x) == [Abs(x), x**2 + 3*x - 4, cos(x)]
|
18 |
+
assert decompogen(sin(x)**2 + sin(x) - sqrt(3)/2, x) == [x**2 + x - sqrt(3)/2, sin(x)]
|
19 |
+
assert decompogen(Abs(cos(y)**2 + 3*cos(x) - 4), x) == [Abs(x), 3*x + cos(y)**2 - 4, cos(x)]
|
20 |
+
assert decompogen(x, y) == [x]
|
21 |
+
assert decompogen(1, x) == [1]
|
22 |
+
assert decompogen(Max(3, x), x) == [Max(3, x)]
|
23 |
+
raises(TypeError, lambda: decompogen(x < 5, x))
|
24 |
+
u = 2*x + 3
|
25 |
+
assert decompogen(Max(sqrt(u),(u)**2), x) == [Max(sqrt(x), x**2), u]
|
26 |
+
assert decompogen(Max(u, u**2, y), x) == [Max(x, x**2, y), u]
|
27 |
+
assert decompogen(Max(sin(x), u), x) == [Max(2*x + 3, sin(x))]
|
28 |
+
|
29 |
+
|
30 |
+
def test_decompogen_poly():
|
31 |
+
assert decompogen(x**4 + 2*x**2 + 1, x) == [x**2 + 2*x + 1, x**2]
|
32 |
+
assert decompogen(x**4 + 2*x**3 - x - 1, x) == [x**2 - x - 1, x**2 + x]
|
33 |
+
|
34 |
+
|
35 |
+
@XFAIL
|
36 |
+
def test_decompogen_fails():
|
37 |
+
A = lambda x: x**2 + 2*x + 3
|
38 |
+
B = lambda x: 4*x**2 + 5*x + 6
|
39 |
+
assert decompogen(A(x*exp(x)), x) == [x**2 + 2*x + 3, x*exp(x)]
|
40 |
+
assert decompogen(A(B(x)), x) == [x**2 + 2*x + 3, 4*x**2 + 5*x + 6]
|
41 |
+
assert decompogen(A(1/x + 1/x**2), x) == [x**2 + 2*x + 3, 1/x + 1/x**2]
|
42 |
+
assert decompogen(A(1/x + 2/(x + 1)), x) == [x**2 + 2*x + 3, 1/x + 2/(x + 1)]
|
43 |
+
|
44 |
+
|
45 |
+
def test_compogen():
|
46 |
+
assert compogen([sin(x), cos(x)], x) == sin(cos(x))
|
47 |
+
assert compogen([x**2 + x + 1, sin(x)], x) == sin(x)**2 + sin(x) + 1
|
48 |
+
assert compogen([sqrt(x), 6*x**2 - 5], x) == sqrt(6*x**2 - 5)
|
49 |
+
assert compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x) == sin(sqrt(
|
50 |
+
cos(x**2 + 1)))
|
51 |
+
assert compogen([Abs(x), x**2 + 3*x - 4, cos(x)], x) == Abs(cos(x)**2 +
|
52 |
+
3*cos(x) - 4)
|
53 |
+
assert compogen([x**2 + x - sqrt(3)/2, sin(x)], x) == (sin(x)**2 + sin(x) -
|
54 |
+
sqrt(3)/2)
|
55 |
+
assert compogen([Abs(x), 3*x + cos(y)**2 - 4, cos(x)], x) == \
|
56 |
+
Abs(3*cos(x) + cos(y)**2 - 4)
|
57 |
+
assert compogen([x**2 + 2*x + 1, x**2], x) == x**4 + 2*x**2 + 1
|
58 |
+
# the result is in unsimplified form
|
59 |
+
assert compogen([x**2 - x - 1, x**2 + x], x) == -x**2 - x + (x**2 + x)**2 - 1
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_pde.py
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.function import (Derivative as D, Function)
|
2 |
+
from sympy.core.relational import Eq
|
3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
5 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
6 |
+
from sympy.core import S
|
7 |
+
from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul,
|
8 |
+
pdsolve, classify_pde, checkpdesol)
|
9 |
+
from sympy.testing.pytest import raises
|
10 |
+
|
11 |
+
|
12 |
+
a, b, c, x, y = symbols('a b c x y')
|
13 |
+
|
14 |
+
def test_pde_separate_add():
|
15 |
+
x, y, z, t = symbols("x,y,z,t")
|
16 |
+
F, T, X, Y, Z, u = map(Function, 'FTXYZu')
|
17 |
+
|
18 |
+
eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t)))
|
19 |
+
res = pde_separate_add(eq, u(x, t), [X(x), T(t)])
|
20 |
+
assert res == [D(X(x), x)*exp(-X(x)), D(T(t), t)*exp(T(t))]
|
21 |
+
|
22 |
+
|
23 |
+
def test_pde_separate():
|
24 |
+
x, y, z, t = symbols("x,y,z,t")
|
25 |
+
F, T, X, Y, Z, u = map(Function, 'FTXYZu')
|
26 |
+
|
27 |
+
eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t)))
|
28 |
+
raises(ValueError, lambda: pde_separate(eq, u(x, t), [X(x), T(t)], 'div'))
|
29 |
+
|
30 |
+
|
31 |
+
def test_pde_separate_mul():
|
32 |
+
x, y, z, t = symbols("x,y,z,t")
|
33 |
+
c = Symbol("C", real=True)
|
34 |
+
Phi = Function('Phi')
|
35 |
+
F, R, T, X, Y, Z, u = map(Function, 'FRTXYZu')
|
36 |
+
r, theta, z = symbols('r,theta,z')
|
37 |
+
|
38 |
+
# Something simple :)
|
39 |
+
eq = Eq(D(F(x, y, z), x) + D(F(x, y, z), y) + D(F(x, y, z), z), 0)
|
40 |
+
|
41 |
+
# Duplicate arguments in functions
|
42 |
+
raises(
|
43 |
+
ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), u(z, z)]))
|
44 |
+
# Wrong number of arguments
|
45 |
+
raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), Y(y)]))
|
46 |
+
# Wrong variables: [x, y] -> [x, z]
|
47 |
+
raises(
|
48 |
+
ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(t), Y(x, y)]))
|
49 |
+
|
50 |
+
assert pde_separate_mul(eq, F(x, y, z), [Y(y), u(x, z)]) == \
|
51 |
+
[D(Y(y), y)/Y(y), -D(u(x, z), x)/u(x, z) - D(u(x, z), z)/u(x, z)]
|
52 |
+
assert pde_separate_mul(eq, F(x, y, z), [X(x), Y(y), Z(z)]) == \
|
53 |
+
[D(X(x), x)/X(x), -D(Z(z), z)/Z(z) - D(Y(y), y)/Y(y)]
|
54 |
+
|
55 |
+
# wave equation
|
56 |
+
wave = Eq(D(u(x, t), t, t), c**2*D(u(x, t), x, x))
|
57 |
+
res = pde_separate_mul(wave, u(x, t), [X(x), T(t)])
|
58 |
+
assert res == [D(X(x), x, x)/X(x), D(T(t), t, t)/(c**2*T(t))]
|
59 |
+
|
60 |
+
# Laplace equation in cylindrical coords
|
61 |
+
eq = Eq(1/r * D(Phi(r, theta, z), r) + D(Phi(r, theta, z), r, 2) +
|
62 |
+
1/r**2 * D(Phi(r, theta, z), theta, 2) + D(Phi(r, theta, z), z, 2), 0)
|
63 |
+
# Separate z
|
64 |
+
res = pde_separate_mul(eq, Phi(r, theta, z), [Z(z), u(theta, r)])
|
65 |
+
assert res == [D(Z(z), z, z)/Z(z),
|
66 |
+
-D(u(theta, r), r, r)/u(theta, r) -
|
67 |
+
D(u(theta, r), r)/(r*u(theta, r)) -
|
68 |
+
D(u(theta, r), theta, theta)/(r**2*u(theta, r))]
|
69 |
+
# Lets use the result to create a new equation...
|
70 |
+
eq = Eq(res[1], c)
|
71 |
+
# ...and separate theta...
|
72 |
+
res = pde_separate_mul(eq, u(theta, r), [T(theta), R(r)])
|
73 |
+
assert res == [D(T(theta), theta, theta)/T(theta),
|
74 |
+
-r*D(R(r), r)/R(r) - r**2*D(R(r), r, r)/R(r) - c*r**2]
|
75 |
+
# ...or r...
|
76 |
+
res = pde_separate_mul(eq, u(theta, r), [R(r), T(theta)])
|
77 |
+
assert res == [r*D(R(r), r)/R(r) + r**2*D(R(r), r, r)/R(r) + c*r**2,
|
78 |
+
-D(T(theta), theta, theta)/T(theta)]
|
79 |
+
|
80 |
+
|
81 |
+
def test_issue_11726():
|
82 |
+
x, t = symbols("x t")
|
83 |
+
f = symbols("f", cls=Function)
|
84 |
+
X, T = symbols("X T", cls=Function)
|
85 |
+
|
86 |
+
u = f(x, t)
|
87 |
+
eq = u.diff(x, 2) - u.diff(t, 2)
|
88 |
+
res = pde_separate(eq, u, [T(x), X(t)])
|
89 |
+
assert res == [D(T(x), x, x)/T(x),D(X(t), t, t)/X(t)]
|
90 |
+
|
91 |
+
|
92 |
+
def test_pde_classify():
|
93 |
+
# When more number of hints are added, add tests for classifying here.
|
94 |
+
f = Function('f')
|
95 |
+
eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y)
|
96 |
+
eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y)
|
97 |
+
eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y)
|
98 |
+
eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y)
|
99 |
+
eq5 = x**2*f(x,y) + x*f(x,y).diff(x) + x*y*f(x,y).diff(y)
|
100 |
+
eq6 = y*x**2*f(x,y) + y*f(x,y).diff(x) + f(x,y).diff(y)
|
101 |
+
for eq in [eq1, eq2, eq3]:
|
102 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
103 |
+
for eq in [eq4, eq5, eq6]:
|
104 |
+
assert classify_pde(eq) == ('1st_linear_variable_coeff',)
|
105 |
+
|
106 |
+
|
107 |
+
def test_checkpdesol():
|
108 |
+
f, F = map(Function, ['f', 'F'])
|
109 |
+
eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y)
|
110 |
+
eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y)
|
111 |
+
eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y)
|
112 |
+
for eq in [eq1, eq2, eq3]:
|
113 |
+
assert checkpdesol(eq, pdsolve(eq))[0]
|
114 |
+
eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y)
|
115 |
+
eq5 = 2*f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y)
|
116 |
+
eq6 = f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y)
|
117 |
+
assert checkpdesol(eq4, [pdsolve(eq5), pdsolve(eq6)]) == [
|
118 |
+
(False, (x - 2)*F(3*x - y)*exp(-x/S(5) - 3*y/S(5))),
|
119 |
+
(False, (x - 1)*F(3*x - y)*exp(-x/S(10) - 3*y/S(10)))]
|
120 |
+
for eq in [eq4, eq5, eq6]:
|
121 |
+
assert checkpdesol(eq, pdsolve(eq))[0]
|
122 |
+
sol = pdsolve(eq4)
|
123 |
+
sol4 = Eq(sol.lhs - sol.rhs, 0)
|
124 |
+
raises(NotImplementedError, lambda:
|
125 |
+
checkpdesol(eq4, sol4, solve_for_func=False))
|
126 |
+
|
127 |
+
|
128 |
+
def test_solvefun():
|
129 |
+
f, F, G, H = map(Function, ['f', 'F', 'G', 'H'])
|
130 |
+
eq1 = f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)
|
131 |
+
assert pdsolve(eq1) == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2))
|
132 |
+
assert pdsolve(eq1, solvefun=G) == Eq(f(x, y), G(x - y)*exp(-x/2 - y/2))
|
133 |
+
assert pdsolve(eq1, solvefun=H) == Eq(f(x, y), H(x - y)*exp(-x/2 - y/2))
|
134 |
+
|
135 |
+
|
136 |
+
def test_pde_1st_linear_constant_coeff_homogeneous():
|
137 |
+
f, F = map(Function, ['f', 'F'])
|
138 |
+
u = f(x, y)
|
139 |
+
eq = 2*u + u.diff(x) + u.diff(y)
|
140 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
141 |
+
sol = pdsolve(eq)
|
142 |
+
assert sol == Eq(u, F(x - y)*exp(-x - y))
|
143 |
+
assert checkpdesol(eq, sol)[0]
|
144 |
+
|
145 |
+
eq = 4 + (3*u.diff(x)/u) + (2*u.diff(y)/u)
|
146 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
147 |
+
sol = pdsolve(eq)
|
148 |
+
assert sol == Eq(u, F(2*x - 3*y)*exp(-S(12)*x/13 - S(8)*y/13))
|
149 |
+
assert checkpdesol(eq, sol)[0]
|
150 |
+
|
151 |
+
eq = u + (6*u.diff(x)) + (7*u.diff(y))
|
152 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
153 |
+
sol = pdsolve(eq)
|
154 |
+
assert sol == Eq(u, F(7*x - 6*y)*exp(-6*x/S(85) - 7*y/S(85)))
|
155 |
+
assert checkpdesol(eq, sol)[0]
|
156 |
+
|
157 |
+
eq = a*u + b*u.diff(x) + c*u.diff(y)
|
158 |
+
sol = pdsolve(eq)
|
159 |
+
assert checkpdesol(eq, sol)[0]
|
160 |
+
|
161 |
+
|
162 |
+
def test_pde_1st_linear_constant_coeff():
|
163 |
+
f, F = map(Function, ['f', 'F'])
|
164 |
+
u = f(x,y)
|
165 |
+
eq = -2*u.diff(x) + 4*u.diff(y) + 5*u - exp(x + 3*y)
|
166 |
+
sol = pdsolve(eq)
|
167 |
+
assert sol == Eq(f(x,y),
|
168 |
+
(F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y))
|
169 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
170 |
+
'1st_linear_constant_coeff_Integral')
|
171 |
+
assert checkpdesol(eq, sol)[0]
|
172 |
+
|
173 |
+
eq = (u.diff(x)/u) + (u.diff(y)/u) + 1 - (exp(x + y)/u)
|
174 |
+
sol = pdsolve(eq)
|
175 |
+
assert sol == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2) + exp(x + y)/3)
|
176 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
177 |
+
'1st_linear_constant_coeff_Integral')
|
178 |
+
assert checkpdesol(eq, sol)[0]
|
179 |
+
|
180 |
+
eq = 2*u + -u.diff(x) + 3*u.diff(y) + sin(x)
|
181 |
+
sol = pdsolve(eq)
|
182 |
+
assert sol == Eq(f(x, y),
|
183 |
+
F(3*x + y)*exp(x/5 - 3*y/5) - 2*sin(x)/5 - cos(x)/5)
|
184 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
185 |
+
'1st_linear_constant_coeff_Integral')
|
186 |
+
assert checkpdesol(eq, sol)[0]
|
187 |
+
|
188 |
+
eq = u + u.diff(x) + u.diff(y) + x*y
|
189 |
+
sol = pdsolve(eq)
|
190 |
+
assert sol.expand() == Eq(f(x, y),
|
191 |
+
x + y + (x - y)**2/4 - (x + y)**2/4 + F(x - y)*exp(-x/2 - y/2) - 2).expand()
|
192 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
193 |
+
'1st_linear_constant_coeff_Integral')
|
194 |
+
assert checkpdesol(eq, sol)[0]
|
195 |
+
eq = u + u.diff(x) + u.diff(y) + log(x)
|
196 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
197 |
+
'1st_linear_constant_coeff_Integral')
|
198 |
+
|
199 |
+
|
200 |
+
def test_pdsolve_all():
|
201 |
+
f, F = map(Function, ['f', 'F'])
|
202 |
+
u = f(x,y)
|
203 |
+
eq = u + u.diff(x) + u.diff(y) + x**2*y
|
204 |
+
sol = pdsolve(eq, hint = 'all')
|
205 |
+
keys = ['1st_linear_constant_coeff',
|
206 |
+
'1st_linear_constant_coeff_Integral', 'default', 'order']
|
207 |
+
assert sorted(sol.keys()) == keys
|
208 |
+
assert sol['order'] == 1
|
209 |
+
assert sol['default'] == '1st_linear_constant_coeff'
|
210 |
+
assert sol['1st_linear_constant_coeff'].expand() == Eq(f(x, y),
|
211 |
+
-x**2*y + x**2 + 2*x*y - 4*x - 2*y + F(x - y)*exp(-x/2 - y/2) + 6).expand()
|
212 |
+
|
213 |
+
|
214 |
+
def test_pdsolve_variable_coeff():
|
215 |
+
f, F = map(Function, ['f', 'F'])
|
216 |
+
u = f(x, y)
|
217 |
+
eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2
|
218 |
+
sol = pdsolve(eq, hint="1st_linear_variable_coeff")
|
219 |
+
assert sol == Eq(u, F(x*y)*exp(y**2/2) + 1)
|
220 |
+
assert checkpdesol(eq, sol)[0]
|
221 |
+
|
222 |
+
eq = x**2*u + x*u.diff(x) + x*y*u.diff(y)
|
223 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
224 |
+
assert sol == Eq(u, F(y*exp(-x))*exp(-x**2/2))
|
225 |
+
assert checkpdesol(eq, sol)[0]
|
226 |
+
|
227 |
+
eq = y*x**2*u + y*u.diff(x) + u.diff(y)
|
228 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
229 |
+
assert sol == Eq(u, F(-2*x + y**2)*exp(-x**3/3))
|
230 |
+
assert checkpdesol(eq, sol)[0]
|
231 |
+
|
232 |
+
eq = exp(x)**2*(u.diff(x)) + y
|
233 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
234 |
+
assert sol == Eq(u, y*exp(-2*x)/2 + F(y))
|
235 |
+
assert checkpdesol(eq, sol)[0]
|
236 |
+
|
237 |
+
eq = exp(2*x)*(u.diff(y)) + y*u - u
|
238 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
239 |
+
assert sol == Eq(u, F(x)*exp(-y*(y - 2)*exp(-2*x)/2))
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_polysys.py
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tests for solvers of systems of polynomial equations. """
|
2 |
+
from sympy.core.numbers import (I, Integer, Rational)
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.core.symbol import symbols
|
5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
6 |
+
from sympy.polys.domains.rationalfield import QQ
|
7 |
+
from sympy.polys.polyerrors import UnsolvableFactorError
|
8 |
+
from sympy.polys.polyoptions import Options
|
9 |
+
from sympy.polys.polytools import Poly
|
10 |
+
from sympy.solvers.solvers import solve
|
11 |
+
from sympy.utilities.iterables import flatten
|
12 |
+
from sympy.abc import x, y, z
|
13 |
+
from sympy.polys import PolynomialError
|
14 |
+
from sympy.solvers.polysys import (solve_poly_system,
|
15 |
+
solve_triangulated,
|
16 |
+
solve_biquadratic, SolveFailed,
|
17 |
+
solve_generic)
|
18 |
+
from sympy.polys.polytools import parallel_poly_from_expr
|
19 |
+
from sympy.testing.pytest import raises
|
20 |
+
|
21 |
+
|
22 |
+
def test_solve_poly_system():
|
23 |
+
assert solve_poly_system([x - 1], x) == [(S.One,)]
|
24 |
+
|
25 |
+
assert solve_poly_system([y - x, y - x - 1], x, y) is None
|
26 |
+
|
27 |
+
assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)]
|
28 |
+
|
29 |
+
assert solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z) == \
|
30 |
+
[(Rational(3, 2), Integer(2), Integer(10))]
|
31 |
+
|
32 |
+
assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \
|
33 |
+
[(0, 0), (2, -sqrt(2)), (2, sqrt(2))]
|
34 |
+
|
35 |
+
assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \
|
36 |
+
[(-I*sqrt(S.Half), Rational(-1, 2)), (I*sqrt(S.Half), Rational(-1, 2))]
|
37 |
+
|
38 |
+
f_1 = x**2 + y + z - 1
|
39 |
+
f_2 = x + y**2 + z - 1
|
40 |
+
f_3 = x + y + z**2 - 1
|
41 |
+
|
42 |
+
a, b = sqrt(2) - 1, -sqrt(2) - 1
|
43 |
+
|
44 |
+
assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \
|
45 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
|
46 |
+
|
47 |
+
solution = [(1, -1), (1, 1)]
|
48 |
+
|
49 |
+
assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution
|
50 |
+
assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution
|
51 |
+
assert solve_poly_system([x**2 - y**2, x - 1]) == solution
|
52 |
+
|
53 |
+
assert solve_poly_system(
|
54 |
+
[x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)]
|
55 |
+
|
56 |
+
raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y))
|
57 |
+
raises(NotImplementedError, lambda: solve_poly_system(
|
58 |
+
[z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2]))
|
59 |
+
raises(PolynomialError, lambda: solve_poly_system([1/x], x))
|
60 |
+
|
61 |
+
raises(NotImplementedError, lambda: solve_poly_system(
|
62 |
+
[x-1,], (x, y)))
|
63 |
+
raises(NotImplementedError, lambda: solve_poly_system(
|
64 |
+
[y-1,], (x, y)))
|
65 |
+
|
66 |
+
# solve_poly_system should ideally construct solutions using
|
67 |
+
# CRootOf for the following four tests
|
68 |
+
assert solve_poly_system([x**5 - x + 1], [x], strict=False) == []
|
69 |
+
raises(UnsolvableFactorError, lambda: solve_poly_system(
|
70 |
+
[x**5 - x + 1], [x], strict=True))
|
71 |
+
|
72 |
+
assert solve_poly_system([(x - 1)*(x**5 - x + 1), y**2 - 1], [x, y],
|
73 |
+
strict=False) == [(1, -1), (1, 1)]
|
74 |
+
raises(UnsolvableFactorError,
|
75 |
+
lambda: solve_poly_system([(x - 1)*(x**5 - x + 1), y**2-1],
|
76 |
+
[x, y], strict=True))
|
77 |
+
|
78 |
+
|
79 |
+
def test_solve_generic():
|
80 |
+
NewOption = Options((x, y), {'domain': 'ZZ'})
|
81 |
+
assert solve_generic([x**2 - 2*y**2, y**2 - y + 1], NewOption) == \
|
82 |
+
[(-sqrt(-1 - sqrt(3)*I), Rational(1, 2) - sqrt(3)*I/2),
|
83 |
+
(sqrt(-1 - sqrt(3)*I), Rational(1, 2) - sqrt(3)*I/2),
|
84 |
+
(-sqrt(-1 + sqrt(3)*I), Rational(1, 2) + sqrt(3)*I/2),
|
85 |
+
(sqrt(-1 + sqrt(3)*I), Rational(1, 2) + sqrt(3)*I/2)]
|
86 |
+
|
87 |
+
# solve_generic should ideally construct solutions using
|
88 |
+
# CRootOf for the following two tests
|
89 |
+
assert solve_generic(
|
90 |
+
[2*x - y, (y - 1)*(y**5 - y + 1)], NewOption, strict=False) == \
|
91 |
+
[(Rational(1, 2), 1)]
|
92 |
+
raises(UnsolvableFactorError, lambda: solve_generic(
|
93 |
+
[2*x - y, (y - 1)*(y**5 - y + 1)], NewOption, strict=True))
|
94 |
+
|
95 |
+
|
96 |
+
def test_solve_biquadratic():
|
97 |
+
x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r')
|
98 |
+
|
99 |
+
f_1 = (x - 1)**2 + (y - 1)**2 - r**2
|
100 |
+
f_2 = (x - 2)**2 + (y - 2)**2 - r**2
|
101 |
+
s = sqrt(2*r**2 - 1)
|
102 |
+
a = (3 - s)/2
|
103 |
+
b = (3 + s)/2
|
104 |
+
assert solve_poly_system([f_1, f_2], x, y) == [(a, b), (b, a)]
|
105 |
+
|
106 |
+
f_1 = (x - 1)**2 + (y - 2)**2 - r**2
|
107 |
+
f_2 = (x - 1)**2 + (y - 1)**2 - r**2
|
108 |
+
|
109 |
+
assert solve_poly_system([f_1, f_2], x, y) == \
|
110 |
+
[(1 - sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2)),
|
111 |
+
(1 + sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2))]
|
112 |
+
|
113 |
+
query = lambda expr: expr.is_Pow and expr.exp is S.Half
|
114 |
+
|
115 |
+
f_1 = (x - 1 )**2 + (y - 2)**2 - r**2
|
116 |
+
f_2 = (x - x1)**2 + (y - 1)**2 - r**2
|
117 |
+
|
118 |
+
result = solve_poly_system([f_1, f_2], x, y)
|
119 |
+
|
120 |
+
assert len(result) == 2 and all(len(r) == 2 for r in result)
|
121 |
+
assert all(r.count(query) == 1 for r in flatten(result))
|
122 |
+
|
123 |
+
f_1 = (x - x0)**2 + (y - y0)**2 - r**2
|
124 |
+
f_2 = (x - x1)**2 + (y - y1)**2 - r**2
|
125 |
+
|
126 |
+
result = solve_poly_system([f_1, f_2], x, y)
|
127 |
+
|
128 |
+
assert len(result) == 2 and all(len(r) == 2 for r in result)
|
129 |
+
assert all(len(r.find(query)) == 1 for r in flatten(result))
|
130 |
+
|
131 |
+
s1 = (x*y - y, x**2 - x)
|
132 |
+
assert solve(s1) == [{x: 1}, {x: 0, y: 0}]
|
133 |
+
s2 = (x*y - x, y**2 - y)
|
134 |
+
assert solve(s2) == [{y: 1}, {x: 0, y: 0}]
|
135 |
+
gens = (x, y)
|
136 |
+
for seq in (s1, s2):
|
137 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
138 |
+
raises(SolveFailed, lambda: solve_biquadratic(f, g, opt))
|
139 |
+
seq = (x**2 + y**2 - 2, y**2 - 1)
|
140 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
141 |
+
assert solve_biquadratic(f, g, opt) == [
|
142 |
+
(-1, -1), (-1, 1), (1, -1), (1, 1)]
|
143 |
+
ans = [(0, -1), (0, 1)]
|
144 |
+
seq = (x**2 + y**2 - 1, y**2 - 1)
|
145 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
146 |
+
assert solve_biquadratic(f, g, opt) == ans
|
147 |
+
seq = (x**2 + y**2 - 1, x**2 - x + y**2 - 1)
|
148 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
149 |
+
assert solve_biquadratic(f, g, opt) == ans
|
150 |
+
|
151 |
+
|
152 |
+
def test_solve_triangulated():
|
153 |
+
f_1 = x**2 + y + z - 1
|
154 |
+
f_2 = x + y**2 + z - 1
|
155 |
+
f_3 = x + y + z**2 - 1
|
156 |
+
|
157 |
+
a, b = sqrt(2) - 1, -sqrt(2) - 1
|
158 |
+
|
159 |
+
assert solve_triangulated([f_1, f_2, f_3], x, y, z) == \
|
160 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0)]
|
161 |
+
|
162 |
+
dom = QQ.algebraic_field(sqrt(2))
|
163 |
+
|
164 |
+
assert solve_triangulated([f_1, f_2, f_3], x, y, z, domain=dom) == \
|
165 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
|
166 |
+
|
167 |
+
|
168 |
+
def test_solve_issue_3686():
|
169 |
+
roots = solve_poly_system([((x - 5)**2/250000 + (y - Rational(5, 10))**2/250000) - 1, x], x, y)
|
170 |
+
assert roots == [(0, S.Half - 15*sqrt(1111)), (0, S.Half + 15*sqrt(1111))]
|
171 |
+
|
172 |
+
roots = solve_poly_system([((x - 5)**2/250000 + (y - 5.0/10)**2/250000) - 1, x], x, y)
|
173 |
+
# TODO: does this really have to be so complicated?!
|
174 |
+
assert len(roots) == 2
|
175 |
+
assert roots[0][0] == 0
|
176 |
+
assert roots[0][1].epsilon_eq(-499.474999374969, 1e12)
|
177 |
+
assert roots[1][0] == 0
|
178 |
+
assert roots[1][1].epsilon_eq(500.474999374969, 1e12)
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_solvers.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/sympy/solvers/tests/test_solveset.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/basisdependent.cpython-310.pyc
ADDED
Binary file (12.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-310.pyc
ADDED
Binary file (31.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/deloperator.cpython-310.pyc
ADDED
Binary file (3.69 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/dyadic.cpython-310.pyc
ADDED
Binary file (8.98 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/functions.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/implicitregion.cpython-310.pyc
ADDED
Binary file (13 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/integrals.cpython-310.pyc
ADDED
Binary file (6.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/operators.cpython-310.pyc
ADDED
Binary file (9.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/orienters.cpython-310.pyc
ADDED
Binary file (12.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/parametricregion.cpython-310.pyc
ADDED
Binary file (6.39 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/point.cpython-310.pyc
ADDED
Binary file (4.12 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/scalar.cpython-310.pyc
ADDED
Binary file (2.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/__pycache__/vector.cpython-310.pyc
ADDED
Binary file (18.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/deloperator.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Basic
|
2 |
+
from sympy.vector.operators import gradient, divergence, curl
|
3 |
+
|
4 |
+
|
5 |
+
class Del(Basic):
|
6 |
+
"""
|
7 |
+
Represents the vector differential operator, usually represented in
|
8 |
+
mathematical expressions as the 'nabla' symbol.
|
9 |
+
"""
|
10 |
+
|
11 |
+
def __new__(cls):
|
12 |
+
obj = super().__new__(cls)
|
13 |
+
obj._name = "delop"
|
14 |
+
return obj
|
15 |
+
|
16 |
+
def gradient(self, scalar_field, doit=False):
|
17 |
+
"""
|
18 |
+
Returns the gradient of the given scalar field, as a
|
19 |
+
Vector instance.
|
20 |
+
|
21 |
+
Parameters
|
22 |
+
==========
|
23 |
+
|
24 |
+
scalar_field : SymPy expression
|
25 |
+
The scalar field to calculate the gradient of.
|
26 |
+
|
27 |
+
doit : bool
|
28 |
+
If True, the result is returned after calling .doit() on
|
29 |
+
each component. Else, the returned expression contains
|
30 |
+
Derivative instances
|
31 |
+
|
32 |
+
Examples
|
33 |
+
========
|
34 |
+
|
35 |
+
>>> from sympy.vector import CoordSys3D, Del
|
36 |
+
>>> C = CoordSys3D('C')
|
37 |
+
>>> delop = Del()
|
38 |
+
>>> delop.gradient(9)
|
39 |
+
0
|
40 |
+
>>> delop(C.x*C.y*C.z).doit()
|
41 |
+
C.y*C.z*C.i + C.x*C.z*C.j + C.x*C.y*C.k
|
42 |
+
|
43 |
+
"""
|
44 |
+
|
45 |
+
return gradient(scalar_field, doit=doit)
|
46 |
+
|
47 |
+
__call__ = gradient
|
48 |
+
__call__.__doc__ = gradient.__doc__
|
49 |
+
|
50 |
+
def dot(self, vect, doit=False):
|
51 |
+
"""
|
52 |
+
Represents the dot product between this operator and a given
|
53 |
+
vector - equal to the divergence of the vector field.
|
54 |
+
|
55 |
+
Parameters
|
56 |
+
==========
|
57 |
+
|
58 |
+
vect : Vector
|
59 |
+
The vector whose divergence is to be calculated.
|
60 |
+
|
61 |
+
doit : bool
|
62 |
+
If True, the result is returned after calling .doit() on
|
63 |
+
each component. Else, the returned expression contains
|
64 |
+
Derivative instances
|
65 |
+
|
66 |
+
Examples
|
67 |
+
========
|
68 |
+
|
69 |
+
>>> from sympy.vector import CoordSys3D, Del
|
70 |
+
>>> delop = Del()
|
71 |
+
>>> C = CoordSys3D('C')
|
72 |
+
>>> delop.dot(C.x*C.i)
|
73 |
+
Derivative(C.x, C.x)
|
74 |
+
>>> v = C.x*C.y*C.z * (C.i + C.j + C.k)
|
75 |
+
>>> (delop & v).doit()
|
76 |
+
C.x*C.y + C.x*C.z + C.y*C.z
|
77 |
+
|
78 |
+
"""
|
79 |
+
return divergence(vect, doit=doit)
|
80 |
+
|
81 |
+
__and__ = dot
|
82 |
+
__and__.__doc__ = dot.__doc__
|
83 |
+
|
84 |
+
def cross(self, vect, doit=False):
|
85 |
+
"""
|
86 |
+
Represents the cross product between this operator and a given
|
87 |
+
vector - equal to the curl of the vector field.
|
88 |
+
|
89 |
+
Parameters
|
90 |
+
==========
|
91 |
+
|
92 |
+
vect : Vector
|
93 |
+
The vector whose curl is to be calculated.
|
94 |
+
|
95 |
+
doit : bool
|
96 |
+
If True, the result is returned after calling .doit() on
|
97 |
+
each component. Else, the returned expression contains
|
98 |
+
Derivative instances
|
99 |
+
|
100 |
+
Examples
|
101 |
+
========
|
102 |
+
|
103 |
+
>>> from sympy.vector import CoordSys3D, Del
|
104 |
+
>>> C = CoordSys3D('C')
|
105 |
+
>>> delop = Del()
|
106 |
+
>>> v = C.x*C.y*C.z * (C.i + C.j + C.k)
|
107 |
+
>>> delop.cross(v, doit = True)
|
108 |
+
(-C.x*C.y + C.x*C.z)*C.i + (C.x*C.y - C.y*C.z)*C.j +
|
109 |
+
(-C.x*C.z + C.y*C.z)*C.k
|
110 |
+
>>> (delop ^ C.i).doit()
|
111 |
+
0
|
112 |
+
|
113 |
+
"""
|
114 |
+
|
115 |
+
return curl(vect, doit=doit)
|
116 |
+
|
117 |
+
__xor__ = cross
|
118 |
+
__xor__.__doc__ = cross.__doc__
|
119 |
+
|
120 |
+
def _sympystr(self, printer):
|
121 |
+
return self._name
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/functions.py
ADDED
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.vector.coordsysrect import CoordSys3D
|
2 |
+
from sympy.vector.deloperator import Del
|
3 |
+
from sympy.vector.scalar import BaseScalar
|
4 |
+
from sympy.vector.vector import Vector, BaseVector
|
5 |
+
from sympy.vector.operators import gradient, curl, divergence
|
6 |
+
from sympy.core.function import diff
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.integrals.integrals import integrate
|
9 |
+
from sympy.simplify.simplify import simplify
|
10 |
+
from sympy.core import sympify
|
11 |
+
from sympy.vector.dyadic import Dyadic
|
12 |
+
|
13 |
+
|
14 |
+
def express(expr, system, system2=None, variables=False):
|
15 |
+
"""
|
16 |
+
Global function for 'express' functionality.
|
17 |
+
|
18 |
+
Re-expresses a Vector, Dyadic or scalar(sympyfiable) in the given
|
19 |
+
coordinate system.
|
20 |
+
|
21 |
+
If 'variables' is True, then the coordinate variables (base scalars)
|
22 |
+
of other coordinate systems present in the vector/scalar field or
|
23 |
+
dyadic are also substituted in terms of the base scalars of the
|
24 |
+
given system.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
==========
|
28 |
+
|
29 |
+
expr : Vector/Dyadic/scalar(sympyfiable)
|
30 |
+
The expression to re-express in CoordSys3D 'system'
|
31 |
+
|
32 |
+
system: CoordSys3D
|
33 |
+
The coordinate system the expr is to be expressed in
|
34 |
+
|
35 |
+
system2: CoordSys3D
|
36 |
+
The other coordinate system required for re-expression
|
37 |
+
(only for a Dyadic Expr)
|
38 |
+
|
39 |
+
variables : boolean
|
40 |
+
Specifies whether to substitute the coordinate variables present
|
41 |
+
in expr, in terms of those of parameter system
|
42 |
+
|
43 |
+
Examples
|
44 |
+
========
|
45 |
+
|
46 |
+
>>> from sympy.vector import CoordSys3D
|
47 |
+
>>> from sympy import Symbol, cos, sin
|
48 |
+
>>> N = CoordSys3D('N')
|
49 |
+
>>> q = Symbol('q')
|
50 |
+
>>> B = N.orient_new_axis('B', q, N.k)
|
51 |
+
>>> from sympy.vector import express
|
52 |
+
>>> express(B.i, N)
|
53 |
+
(cos(q))*N.i + (sin(q))*N.j
|
54 |
+
>>> express(N.x, B, variables=True)
|
55 |
+
B.x*cos(q) - B.y*sin(q)
|
56 |
+
>>> d = N.i.outer(N.i)
|
57 |
+
>>> express(d, B, N) == (cos(q))*(B.i|N.i) + (-sin(q))*(B.j|N.i)
|
58 |
+
True
|
59 |
+
|
60 |
+
"""
|
61 |
+
|
62 |
+
if expr in (0, Vector.zero):
|
63 |
+
return expr
|
64 |
+
|
65 |
+
if not isinstance(system, CoordSys3D):
|
66 |
+
raise TypeError("system should be a CoordSys3D \
|
67 |
+
instance")
|
68 |
+
|
69 |
+
if isinstance(expr, Vector):
|
70 |
+
if system2 is not None:
|
71 |
+
raise ValueError("system2 should not be provided for \
|
72 |
+
Vectors")
|
73 |
+
# Given expr is a Vector
|
74 |
+
if variables:
|
75 |
+
# If variables attribute is True, substitute
|
76 |
+
# the coordinate variables in the Vector
|
77 |
+
system_list = {x.system for x in expr.atoms(BaseScalar, BaseVector)} - {system}
|
78 |
+
subs_dict = {}
|
79 |
+
for f in system_list:
|
80 |
+
subs_dict.update(f.scalar_map(system))
|
81 |
+
expr = expr.subs(subs_dict)
|
82 |
+
# Re-express in this coordinate system
|
83 |
+
outvec = Vector.zero
|
84 |
+
parts = expr.separate()
|
85 |
+
for x in parts:
|
86 |
+
if x != system:
|
87 |
+
temp = system.rotation_matrix(x) * parts[x].to_matrix(x)
|
88 |
+
outvec += matrix_to_vector(temp, system)
|
89 |
+
else:
|
90 |
+
outvec += parts[x]
|
91 |
+
return outvec
|
92 |
+
|
93 |
+
elif isinstance(expr, Dyadic):
|
94 |
+
if system2 is None:
|
95 |
+
system2 = system
|
96 |
+
if not isinstance(system2, CoordSys3D):
|
97 |
+
raise TypeError("system2 should be a CoordSys3D \
|
98 |
+
instance")
|
99 |
+
outdyad = Dyadic.zero
|
100 |
+
var = variables
|
101 |
+
for k, v in expr.components.items():
|
102 |
+
outdyad += (express(v, system, variables=var) *
|
103 |
+
(express(k.args[0], system, variables=var) |
|
104 |
+
express(k.args[1], system2, variables=var)))
|
105 |
+
|
106 |
+
return outdyad
|
107 |
+
|
108 |
+
else:
|
109 |
+
if system2 is not None:
|
110 |
+
raise ValueError("system2 should not be provided for \
|
111 |
+
Vectors")
|
112 |
+
if variables:
|
113 |
+
# Given expr is a scalar field
|
114 |
+
system_set = set()
|
115 |
+
expr = sympify(expr)
|
116 |
+
# Substitute all the coordinate variables
|
117 |
+
for x in expr.atoms(BaseScalar):
|
118 |
+
if x.system != system:
|
119 |
+
system_set.add(x.system)
|
120 |
+
subs_dict = {}
|
121 |
+
for f in system_set:
|
122 |
+
subs_dict.update(f.scalar_map(system))
|
123 |
+
return expr.subs(subs_dict)
|
124 |
+
return expr
|
125 |
+
|
126 |
+
|
127 |
+
def directional_derivative(field, direction_vector):
|
128 |
+
"""
|
129 |
+
Returns the directional derivative of a scalar or vector field computed
|
130 |
+
along a given vector in coordinate system which parameters are expressed.
|
131 |
+
|
132 |
+
Parameters
|
133 |
+
==========
|
134 |
+
|
135 |
+
field : Vector or Scalar
|
136 |
+
The scalar or vector field to compute the directional derivative of
|
137 |
+
|
138 |
+
direction_vector : Vector
|
139 |
+
The vector to calculated directional derivative along them.
|
140 |
+
|
141 |
+
|
142 |
+
Examples
|
143 |
+
========
|
144 |
+
|
145 |
+
>>> from sympy.vector import CoordSys3D, directional_derivative
|
146 |
+
>>> R = CoordSys3D('R')
|
147 |
+
>>> f1 = R.x*R.y*R.z
|
148 |
+
>>> v1 = 3*R.i + 4*R.j + R.k
|
149 |
+
>>> directional_derivative(f1, v1)
|
150 |
+
R.x*R.y + 4*R.x*R.z + 3*R.y*R.z
|
151 |
+
>>> f2 = 5*R.x**2*R.z
|
152 |
+
>>> directional_derivative(f2, v1)
|
153 |
+
5*R.x**2 + 30*R.x*R.z
|
154 |
+
|
155 |
+
"""
|
156 |
+
from sympy.vector.operators import _get_coord_systems
|
157 |
+
coord_sys = _get_coord_systems(field)
|
158 |
+
if len(coord_sys) > 0:
|
159 |
+
# TODO: This gets a random coordinate system in case of multiple ones:
|
160 |
+
coord_sys = next(iter(coord_sys))
|
161 |
+
field = express(field, coord_sys, variables=True)
|
162 |
+
i, j, k = coord_sys.base_vectors()
|
163 |
+
x, y, z = coord_sys.base_scalars()
|
164 |
+
out = Vector.dot(direction_vector, i) * diff(field, x)
|
165 |
+
out += Vector.dot(direction_vector, j) * diff(field, y)
|
166 |
+
out += Vector.dot(direction_vector, k) * diff(field, z)
|
167 |
+
if out == 0 and isinstance(field, Vector):
|
168 |
+
out = Vector.zero
|
169 |
+
return out
|
170 |
+
elif isinstance(field, Vector):
|
171 |
+
return Vector.zero
|
172 |
+
else:
|
173 |
+
return S.Zero
|
174 |
+
|
175 |
+
|
176 |
+
def laplacian(expr):
|
177 |
+
"""
|
178 |
+
Return the laplacian of the given field computed in terms of
|
179 |
+
the base scalars of the given coordinate system.
|
180 |
+
|
181 |
+
Parameters
|
182 |
+
==========
|
183 |
+
|
184 |
+
expr : SymPy Expr or Vector
|
185 |
+
expr denotes a scalar or vector field.
|
186 |
+
|
187 |
+
Examples
|
188 |
+
========
|
189 |
+
|
190 |
+
>>> from sympy.vector import CoordSys3D, laplacian
|
191 |
+
>>> R = CoordSys3D('R')
|
192 |
+
>>> f = R.x**2*R.y**5*R.z
|
193 |
+
>>> laplacian(f)
|
194 |
+
20*R.x**2*R.y**3*R.z + 2*R.y**5*R.z
|
195 |
+
>>> f = R.x**2*R.i + R.y**3*R.j + R.z**4*R.k
|
196 |
+
>>> laplacian(f)
|
197 |
+
2*R.i + 6*R.y*R.j + 12*R.z**2*R.k
|
198 |
+
|
199 |
+
"""
|
200 |
+
|
201 |
+
delop = Del()
|
202 |
+
if expr.is_Vector:
|
203 |
+
return (gradient(divergence(expr)) - curl(curl(expr))).doit()
|
204 |
+
return delop.dot(delop(expr)).doit()
|
205 |
+
|
206 |
+
|
207 |
+
def is_conservative(field):
|
208 |
+
"""
|
209 |
+
Checks if a field is conservative.
|
210 |
+
|
211 |
+
Parameters
|
212 |
+
==========
|
213 |
+
|
214 |
+
field : Vector
|
215 |
+
The field to check for conservative property
|
216 |
+
|
217 |
+
Examples
|
218 |
+
========
|
219 |
+
|
220 |
+
>>> from sympy.vector import CoordSys3D
|
221 |
+
>>> from sympy.vector import is_conservative
|
222 |
+
>>> R = CoordSys3D('R')
|
223 |
+
>>> is_conservative(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k)
|
224 |
+
True
|
225 |
+
>>> is_conservative(R.z*R.j)
|
226 |
+
False
|
227 |
+
|
228 |
+
"""
|
229 |
+
|
230 |
+
# Field is conservative irrespective of system
|
231 |
+
# Take the first coordinate system in the result of the
|
232 |
+
# separate method of Vector
|
233 |
+
if not isinstance(field, Vector):
|
234 |
+
raise TypeError("field should be a Vector")
|
235 |
+
if field == Vector.zero:
|
236 |
+
return True
|
237 |
+
return curl(field).simplify() == Vector.zero
|
238 |
+
|
239 |
+
|
240 |
+
def is_solenoidal(field):
|
241 |
+
"""
|
242 |
+
Checks if a field is solenoidal.
|
243 |
+
|
244 |
+
Parameters
|
245 |
+
==========
|
246 |
+
|
247 |
+
field : Vector
|
248 |
+
The field to check for solenoidal property
|
249 |
+
|
250 |
+
Examples
|
251 |
+
========
|
252 |
+
|
253 |
+
>>> from sympy.vector import CoordSys3D
|
254 |
+
>>> from sympy.vector import is_solenoidal
|
255 |
+
>>> R = CoordSys3D('R')
|
256 |
+
>>> is_solenoidal(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k)
|
257 |
+
True
|
258 |
+
>>> is_solenoidal(R.y * R.j)
|
259 |
+
False
|
260 |
+
|
261 |
+
"""
|
262 |
+
|
263 |
+
# Field is solenoidal irrespective of system
|
264 |
+
# Take the first coordinate system in the result of the
|
265 |
+
# separate method in Vector
|
266 |
+
if not isinstance(field, Vector):
|
267 |
+
raise TypeError("field should be a Vector")
|
268 |
+
if field == Vector.zero:
|
269 |
+
return True
|
270 |
+
return divergence(field).simplify() is S.Zero
|
271 |
+
|
272 |
+
|
273 |
+
def scalar_potential(field, coord_sys):
|
274 |
+
"""
|
275 |
+
Returns the scalar potential function of a field in a given
|
276 |
+
coordinate system (without the added integration constant).
|
277 |
+
|
278 |
+
Parameters
|
279 |
+
==========
|
280 |
+
|
281 |
+
field : Vector
|
282 |
+
The vector field whose scalar potential function is to be
|
283 |
+
calculated
|
284 |
+
|
285 |
+
coord_sys : CoordSys3D
|
286 |
+
The coordinate system to do the calculation in
|
287 |
+
|
288 |
+
Examples
|
289 |
+
========
|
290 |
+
|
291 |
+
>>> from sympy.vector import CoordSys3D
|
292 |
+
>>> from sympy.vector import scalar_potential, gradient
|
293 |
+
>>> R = CoordSys3D('R')
|
294 |
+
>>> scalar_potential(R.k, R) == R.z
|
295 |
+
True
|
296 |
+
>>> scalar_field = 2*R.x**2*R.y*R.z
|
297 |
+
>>> grad_field = gradient(scalar_field)
|
298 |
+
>>> scalar_potential(grad_field, R)
|
299 |
+
2*R.x**2*R.y*R.z
|
300 |
+
|
301 |
+
"""
|
302 |
+
|
303 |
+
# Check whether field is conservative
|
304 |
+
if not is_conservative(field):
|
305 |
+
raise ValueError("Field is not conservative")
|
306 |
+
if field == Vector.zero:
|
307 |
+
return S.Zero
|
308 |
+
# Express the field exntirely in coord_sys
|
309 |
+
# Substitute coordinate variables also
|
310 |
+
if not isinstance(coord_sys, CoordSys3D):
|
311 |
+
raise TypeError("coord_sys must be a CoordSys3D")
|
312 |
+
field = express(field, coord_sys, variables=True)
|
313 |
+
dimensions = coord_sys.base_vectors()
|
314 |
+
scalars = coord_sys.base_scalars()
|
315 |
+
# Calculate scalar potential function
|
316 |
+
temp_function = integrate(field.dot(dimensions[0]), scalars[0])
|
317 |
+
for i, dim in enumerate(dimensions[1:]):
|
318 |
+
partial_diff = diff(temp_function, scalars[i + 1])
|
319 |
+
partial_diff = field.dot(dim) - partial_diff
|
320 |
+
temp_function += integrate(partial_diff, scalars[i + 1])
|
321 |
+
return temp_function
|
322 |
+
|
323 |
+
|
324 |
+
def scalar_potential_difference(field, coord_sys, point1, point2):
|
325 |
+
"""
|
326 |
+
Returns the scalar potential difference between two points in a
|
327 |
+
certain coordinate system, wrt a given field.
|
328 |
+
|
329 |
+
If a scalar field is provided, its values at the two points are
|
330 |
+
considered. If a conservative vector field is provided, the values
|
331 |
+
of its scalar potential function at the two points are used.
|
332 |
+
|
333 |
+
Returns (potential at point2) - (potential at point1)
|
334 |
+
|
335 |
+
The position vectors of the two Points are calculated wrt the
|
336 |
+
origin of the coordinate system provided.
|
337 |
+
|
338 |
+
Parameters
|
339 |
+
==========
|
340 |
+
|
341 |
+
field : Vector/Expr
|
342 |
+
The field to calculate wrt
|
343 |
+
|
344 |
+
coord_sys : CoordSys3D
|
345 |
+
The coordinate system to do the calculations in
|
346 |
+
|
347 |
+
point1 : Point
|
348 |
+
The initial Point in given coordinate system
|
349 |
+
|
350 |
+
position2 : Point
|
351 |
+
The second Point in the given coordinate system
|
352 |
+
|
353 |
+
Examples
|
354 |
+
========
|
355 |
+
|
356 |
+
>>> from sympy.vector import CoordSys3D
|
357 |
+
>>> from sympy.vector import scalar_potential_difference
|
358 |
+
>>> R = CoordSys3D('R')
|
359 |
+
>>> P = R.origin.locate_new('P', R.x*R.i + R.y*R.j + R.z*R.k)
|
360 |
+
>>> vectfield = 4*R.x*R.y*R.i + 2*R.x**2*R.j
|
361 |
+
>>> scalar_potential_difference(vectfield, R, R.origin, P)
|
362 |
+
2*R.x**2*R.y
|
363 |
+
>>> Q = R.origin.locate_new('O', 3*R.i + R.j + 2*R.k)
|
364 |
+
>>> scalar_potential_difference(vectfield, R, P, Q)
|
365 |
+
-2*R.x**2*R.y + 18
|
366 |
+
|
367 |
+
"""
|
368 |
+
|
369 |
+
if not isinstance(coord_sys, CoordSys3D):
|
370 |
+
raise TypeError("coord_sys must be a CoordSys3D")
|
371 |
+
if isinstance(field, Vector):
|
372 |
+
# Get the scalar potential function
|
373 |
+
scalar_fn = scalar_potential(field, coord_sys)
|
374 |
+
else:
|
375 |
+
# Field is a scalar
|
376 |
+
scalar_fn = field
|
377 |
+
# Express positions in required coordinate system
|
378 |
+
origin = coord_sys.origin
|
379 |
+
position1 = express(point1.position_wrt(origin), coord_sys,
|
380 |
+
variables=True)
|
381 |
+
position2 = express(point2.position_wrt(origin), coord_sys,
|
382 |
+
variables=True)
|
383 |
+
# Get the two positions as substitution dicts for coordinate variables
|
384 |
+
subs_dict1 = {}
|
385 |
+
subs_dict2 = {}
|
386 |
+
scalars = coord_sys.base_scalars()
|
387 |
+
for i, x in enumerate(coord_sys.base_vectors()):
|
388 |
+
subs_dict1[scalars[i]] = x.dot(position1)
|
389 |
+
subs_dict2[scalars[i]] = x.dot(position2)
|
390 |
+
return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1)
|
391 |
+
|
392 |
+
|
393 |
+
def matrix_to_vector(matrix, system):
|
394 |
+
"""
|
395 |
+
Converts a vector in matrix form to a Vector instance.
|
396 |
+
|
397 |
+
It is assumed that the elements of the Matrix represent the
|
398 |
+
measure numbers of the components of the vector along basis
|
399 |
+
vectors of 'system'.
|
400 |
+
|
401 |
+
Parameters
|
402 |
+
==========
|
403 |
+
|
404 |
+
matrix : SymPy Matrix, Dimensions: (3, 1)
|
405 |
+
The matrix to be converted to a vector
|
406 |
+
|
407 |
+
system : CoordSys3D
|
408 |
+
The coordinate system the vector is to be defined in
|
409 |
+
|
410 |
+
Examples
|
411 |
+
========
|
412 |
+
|
413 |
+
>>> from sympy import ImmutableMatrix as Matrix
|
414 |
+
>>> m = Matrix([1, 2, 3])
|
415 |
+
>>> from sympy.vector import CoordSys3D, matrix_to_vector
|
416 |
+
>>> C = CoordSys3D('C')
|
417 |
+
>>> v = matrix_to_vector(m, C)
|
418 |
+
>>> v
|
419 |
+
C.i + 2*C.j + 3*C.k
|
420 |
+
>>> v.to_matrix(C) == m
|
421 |
+
True
|
422 |
+
|
423 |
+
"""
|
424 |
+
|
425 |
+
outvec = Vector.zero
|
426 |
+
vects = system.base_vectors()
|
427 |
+
for i, x in enumerate(matrix):
|
428 |
+
outvec += x * vects[i]
|
429 |
+
return outvec
|
430 |
+
|
431 |
+
|
432 |
+
def _path(from_object, to_object):
|
433 |
+
"""
|
434 |
+
Calculates the 'path' of objects starting from 'from_object'
|
435 |
+
to 'to_object', along with the index of the first common
|
436 |
+
ancestor in the tree.
|
437 |
+
|
438 |
+
Returns (index, list) tuple.
|
439 |
+
"""
|
440 |
+
|
441 |
+
if from_object._root != to_object._root:
|
442 |
+
raise ValueError("No connecting path found between " +
|
443 |
+
str(from_object) + " and " + str(to_object))
|
444 |
+
|
445 |
+
other_path = []
|
446 |
+
obj = to_object
|
447 |
+
while obj._parent is not None:
|
448 |
+
other_path.append(obj)
|
449 |
+
obj = obj._parent
|
450 |
+
other_path.append(obj)
|
451 |
+
object_set = set(other_path)
|
452 |
+
from_path = []
|
453 |
+
obj = from_object
|
454 |
+
while obj not in object_set:
|
455 |
+
from_path.append(obj)
|
456 |
+
obj = obj._parent
|
457 |
+
index = len(from_path)
|
458 |
+
i = other_path.index(obj)
|
459 |
+
while i >= 0:
|
460 |
+
from_path.append(other_path[i])
|
461 |
+
i -= 1
|
462 |
+
return index, from_path
|
463 |
+
|
464 |
+
|
465 |
+
def orthogonalize(*vlist, orthonormal=False):
|
466 |
+
"""
|
467 |
+
Takes a sequence of independent vectors and orthogonalizes them
|
468 |
+
using the Gram - Schmidt process. Returns a list of
|
469 |
+
orthogonal or orthonormal vectors.
|
470 |
+
|
471 |
+
Parameters
|
472 |
+
==========
|
473 |
+
|
474 |
+
vlist : sequence of independent vectors to be made orthogonal.
|
475 |
+
|
476 |
+
orthonormal : Optional parameter
|
477 |
+
Set to True if the vectors returned should be
|
478 |
+
orthonormal.
|
479 |
+
Default: False
|
480 |
+
|
481 |
+
Examples
|
482 |
+
========
|
483 |
+
|
484 |
+
>>> from sympy.vector.coordsysrect import CoordSys3D
|
485 |
+
>>> from sympy.vector.functions import orthogonalize
|
486 |
+
>>> C = CoordSys3D('C')
|
487 |
+
>>> i, j, k = C.base_vectors()
|
488 |
+
>>> v1 = i + 2*j
|
489 |
+
>>> v2 = 2*i + 3*j
|
490 |
+
>>> orthogonalize(v1, v2)
|
491 |
+
[C.i + 2*C.j, 2/5*C.i + (-1/5)*C.j]
|
492 |
+
|
493 |
+
References
|
494 |
+
==========
|
495 |
+
|
496 |
+
.. [1] https://en.wikipedia.org/wiki/Gram-Schmidt_process
|
497 |
+
|
498 |
+
"""
|
499 |
+
|
500 |
+
if not all(isinstance(vec, Vector) for vec in vlist):
|
501 |
+
raise TypeError('Each element must be of Type Vector')
|
502 |
+
|
503 |
+
ortho_vlist = []
|
504 |
+
for i, term in enumerate(vlist):
|
505 |
+
for j in range(i):
|
506 |
+
term -= ortho_vlist[j].projection(vlist[i])
|
507 |
+
# TODO : The following line introduces a performance issue
|
508 |
+
# and needs to be changed once a good solution for issue #10279 is
|
509 |
+
# found.
|
510 |
+
if simplify(term).equals(Vector.zero):
|
511 |
+
raise ValueError("Vector set not linearly independent")
|
512 |
+
ortho_vlist.append(term)
|
513 |
+
|
514 |
+
if orthonormal:
|
515 |
+
ortho_vlist = [vec.normalize() for vec in ortho_vlist]
|
516 |
+
|
517 |
+
return ortho_vlist
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/implicitregion.py
ADDED
@@ -0,0 +1,506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import Rational
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.functions.elementary.complexes import sign
|
5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
6 |
+
from sympy.polys.polytools import gcd
|
7 |
+
from sympy.sets.sets import Complement
|
8 |
+
from sympy.core import Basic, Tuple, diff, expand, Eq, Integer
|
9 |
+
from sympy.core.sorting import ordered
|
10 |
+
from sympy.core.symbol import _symbol
|
11 |
+
from sympy.solvers import solveset, nonlinsolve, diophantine
|
12 |
+
from sympy.polys import total_degree
|
13 |
+
from sympy.geometry import Point
|
14 |
+
from sympy.ntheory.factor_ import core
|
15 |
+
|
16 |
+
|
17 |
+
class ImplicitRegion(Basic):
|
18 |
+
"""
|
19 |
+
Represents an implicit region in space.
|
20 |
+
|
21 |
+
Examples
|
22 |
+
========
|
23 |
+
|
24 |
+
>>> from sympy import Eq
|
25 |
+
>>> from sympy.abc import x, y, z, t
|
26 |
+
>>> from sympy.vector import ImplicitRegion
|
27 |
+
|
28 |
+
>>> ImplicitRegion((x, y), x**2 + y**2 - 4)
|
29 |
+
ImplicitRegion((x, y), x**2 + y**2 - 4)
|
30 |
+
>>> ImplicitRegion((x, y), Eq(y*x, 1))
|
31 |
+
ImplicitRegion((x, y), x*y - 1)
|
32 |
+
|
33 |
+
>>> parabola = ImplicitRegion((x, y), y**2 - 4*x)
|
34 |
+
>>> parabola.degree
|
35 |
+
2
|
36 |
+
>>> parabola.equation
|
37 |
+
-4*x + y**2
|
38 |
+
>>> parabola.rational_parametrization(t)
|
39 |
+
(4/t**2, 4/t)
|
40 |
+
|
41 |
+
>>> r = ImplicitRegion((x, y, z), Eq(z, x**2 + y**2))
|
42 |
+
>>> r.variables
|
43 |
+
(x, y, z)
|
44 |
+
>>> r.singular_points()
|
45 |
+
EmptySet
|
46 |
+
>>> r.regular_point()
|
47 |
+
(-10, -10, 200)
|
48 |
+
|
49 |
+
Parameters
|
50 |
+
==========
|
51 |
+
|
52 |
+
variables : tuple to map variables in implicit equation to base scalars.
|
53 |
+
|
54 |
+
equation : An expression or Eq denoting the implicit equation of the region.
|
55 |
+
|
56 |
+
"""
|
57 |
+
def __new__(cls, variables, equation):
|
58 |
+
if not isinstance(variables, Tuple):
|
59 |
+
variables = Tuple(*variables)
|
60 |
+
|
61 |
+
if isinstance(equation, Eq):
|
62 |
+
equation = equation.lhs - equation.rhs
|
63 |
+
|
64 |
+
return super().__new__(cls, variables, equation)
|
65 |
+
|
66 |
+
@property
|
67 |
+
def variables(self):
|
68 |
+
return self.args[0]
|
69 |
+
|
70 |
+
@property
|
71 |
+
def equation(self):
|
72 |
+
return self.args[1]
|
73 |
+
|
74 |
+
@property
|
75 |
+
def degree(self):
|
76 |
+
return total_degree(self.equation)
|
77 |
+
|
78 |
+
def regular_point(self):
|
79 |
+
"""
|
80 |
+
Returns a point on the implicit region.
|
81 |
+
|
82 |
+
Examples
|
83 |
+
========
|
84 |
+
|
85 |
+
>>> from sympy.abc import x, y, z
|
86 |
+
>>> from sympy.vector import ImplicitRegion
|
87 |
+
>>> circle = ImplicitRegion((x, y), (x + 2)**2 + (y - 3)**2 - 16)
|
88 |
+
>>> circle.regular_point()
|
89 |
+
(-2, -1)
|
90 |
+
>>> parabola = ImplicitRegion((x, y), x**2 - 4*y)
|
91 |
+
>>> parabola.regular_point()
|
92 |
+
(0, 0)
|
93 |
+
>>> r = ImplicitRegion((x, y, z), (x + y + z)**4)
|
94 |
+
>>> r.regular_point()
|
95 |
+
(-10, -10, 20)
|
96 |
+
|
97 |
+
References
|
98 |
+
==========
|
99 |
+
|
100 |
+
- Erik Hillgarter, "Rational Points on Conics", Diploma Thesis, RISC-Linz,
|
101 |
+
J. Kepler Universitat Linz, 1996. Available:
|
102 |
+
https://www3.risc.jku.at/publications/download/risc_1355/Rational%20Points%20on%20Conics.pdf
|
103 |
+
|
104 |
+
"""
|
105 |
+
equation = self.equation
|
106 |
+
|
107 |
+
if len(self.variables) == 1:
|
108 |
+
return (list(solveset(equation, self.variables[0], domain=S.Reals))[0],)
|
109 |
+
elif len(self.variables) == 2:
|
110 |
+
|
111 |
+
if self.degree == 2:
|
112 |
+
coeffs = a, b, c, d, e, f = conic_coeff(self.variables, equation)
|
113 |
+
|
114 |
+
if b**2 == 4*a*c:
|
115 |
+
x_reg, y_reg = self._regular_point_parabola(*coeffs)
|
116 |
+
else:
|
117 |
+
x_reg, y_reg = self._regular_point_ellipse(*coeffs)
|
118 |
+
return x_reg, y_reg
|
119 |
+
|
120 |
+
if len(self.variables) == 3:
|
121 |
+
x, y, z = self.variables
|
122 |
+
|
123 |
+
for x_reg in range(-10, 10):
|
124 |
+
for y_reg in range(-10, 10):
|
125 |
+
if not solveset(equation.subs({x: x_reg, y: y_reg}), self.variables[2], domain=S.Reals).is_empty:
|
126 |
+
return (x_reg, y_reg, list(solveset(equation.subs({x: x_reg, y: y_reg})))[0])
|
127 |
+
|
128 |
+
if len(self.singular_points()) != 0:
|
129 |
+
return list[self.singular_points()][0]
|
130 |
+
|
131 |
+
raise NotImplementedError()
|
132 |
+
|
133 |
+
def _regular_point_parabola(self, a, b, c, d, e, f):
|
134 |
+
ok = (a, d) != (0, 0) and (c, e) != (0, 0) and b**2 == 4*a*c and (a, c) != (0, 0)
|
135 |
+
|
136 |
+
if not ok:
|
137 |
+
raise ValueError("Rational Point on the conic does not exist")
|
138 |
+
|
139 |
+
if a != 0:
|
140 |
+
d_dash, f_dash = (4*a*e - 2*b*d, 4*a*f - d**2)
|
141 |
+
if d_dash != 0:
|
142 |
+
y_reg = -f_dash/d_dash
|
143 |
+
x_reg = -(d + b*y_reg)/(2*a)
|
144 |
+
else:
|
145 |
+
ok = False
|
146 |
+
elif c != 0:
|
147 |
+
d_dash, f_dash = (4*c*d - 2*b*e, 4*c*f - e**2)
|
148 |
+
if d_dash != 0:
|
149 |
+
x_reg = -f_dash/d_dash
|
150 |
+
y_reg = -(e + b*x_reg)/(2*c)
|
151 |
+
else:
|
152 |
+
ok = False
|
153 |
+
|
154 |
+
if ok:
|
155 |
+
return x_reg, y_reg
|
156 |
+
else:
|
157 |
+
raise ValueError("Rational Point on the conic does not exist")
|
158 |
+
|
159 |
+
def _regular_point_ellipse(self, a, b, c, d, e, f):
|
160 |
+
D = 4*a*c - b**2
|
161 |
+
ok = D
|
162 |
+
|
163 |
+
if not ok:
|
164 |
+
raise ValueError("Rational Point on the conic does not exist")
|
165 |
+
|
166 |
+
if a == 0 and c == 0:
|
167 |
+
K = -1
|
168 |
+
L = 4*(d*e - b*f)
|
169 |
+
elif c != 0:
|
170 |
+
K = D
|
171 |
+
L = 4*c**2*d**2 - 4*b*c*d*e + 4*a*c*e**2 + 4*b**2*c*f - 16*a*c**2*f
|
172 |
+
else:
|
173 |
+
K = D
|
174 |
+
L = 4*a**2*e**2 - 4*b*a*d*e + 4*b**2*a*f
|
175 |
+
|
176 |
+
ok = L != 0 and not(K > 0 and L < 0)
|
177 |
+
if not ok:
|
178 |
+
raise ValueError("Rational Point on the conic does not exist")
|
179 |
+
|
180 |
+
K = Rational(K).limit_denominator(10**12)
|
181 |
+
L = Rational(L).limit_denominator(10**12)
|
182 |
+
|
183 |
+
k1, k2 = K.p, K.q
|
184 |
+
l1, l2 = L.p, L.q
|
185 |
+
g = gcd(k2, l2)
|
186 |
+
|
187 |
+
a1 = (l2*k2)/g
|
188 |
+
b1 = (k1*l2)/g
|
189 |
+
c1 = -(l1*k2)/g
|
190 |
+
a2 = sign(a1)*core(abs(a1), 2)
|
191 |
+
r1 = sqrt(a1/a2)
|
192 |
+
b2 = sign(b1)*core(abs(b1), 2)
|
193 |
+
r2 = sqrt(b1/b2)
|
194 |
+
c2 = sign(c1)*core(abs(c1), 2)
|
195 |
+
r3 = sqrt(c1/c2)
|
196 |
+
|
197 |
+
g = gcd(gcd(a2, b2), c2)
|
198 |
+
a2 = a2/g
|
199 |
+
b2 = b2/g
|
200 |
+
c2 = c2/g
|
201 |
+
|
202 |
+
g1 = gcd(a2, b2)
|
203 |
+
a2 = a2/g1
|
204 |
+
b2 = b2/g1
|
205 |
+
c2 = c2*g1
|
206 |
+
|
207 |
+
g2 = gcd(a2,c2)
|
208 |
+
a2 = a2/g2
|
209 |
+
b2 = b2*g2
|
210 |
+
c2 = c2/g2
|
211 |
+
|
212 |
+
g3 = gcd(b2, c2)
|
213 |
+
a2 = a2*g3
|
214 |
+
b2 = b2/g3
|
215 |
+
c2 = c2/g3
|
216 |
+
|
217 |
+
x, y, z = symbols("x y z")
|
218 |
+
eq = a2*x**2 + b2*y**2 + c2*z**2
|
219 |
+
|
220 |
+
solutions = diophantine(eq)
|
221 |
+
|
222 |
+
if len(solutions) == 0:
|
223 |
+
raise ValueError("Rational Point on the conic does not exist")
|
224 |
+
|
225 |
+
flag = False
|
226 |
+
for sol in solutions:
|
227 |
+
syms = Tuple(*sol).free_symbols
|
228 |
+
rep = {s: 3 for s in syms}
|
229 |
+
sol_z = sol[2]
|
230 |
+
|
231 |
+
if sol_z == 0:
|
232 |
+
flag = True
|
233 |
+
continue
|
234 |
+
|
235 |
+
if not isinstance(sol_z, (int, Integer)):
|
236 |
+
syms_z = sol_z.free_symbols
|
237 |
+
|
238 |
+
if len(syms_z) == 1:
|
239 |
+
p = next(iter(syms_z))
|
240 |
+
p_values = Complement(S.Integers, solveset(Eq(sol_z, 0), p, S.Integers))
|
241 |
+
rep[p] = next(iter(p_values))
|
242 |
+
|
243 |
+
if len(syms_z) == 2:
|
244 |
+
p, q = list(ordered(syms_z))
|
245 |
+
|
246 |
+
for i in S.Integers:
|
247 |
+
subs_sol_z = sol_z.subs(p, i)
|
248 |
+
q_values = Complement(S.Integers, solveset(Eq(subs_sol_z, 0), q, S.Integers))
|
249 |
+
|
250 |
+
if not q_values.is_empty:
|
251 |
+
rep[p] = i
|
252 |
+
rep[q] = next(iter(q_values))
|
253 |
+
break
|
254 |
+
|
255 |
+
if len(syms) != 0:
|
256 |
+
x, y, z = tuple(s.subs(rep) for s in sol)
|
257 |
+
else:
|
258 |
+
x, y, z = sol
|
259 |
+
flag = False
|
260 |
+
break
|
261 |
+
|
262 |
+
if flag:
|
263 |
+
raise ValueError("Rational Point on the conic does not exist")
|
264 |
+
|
265 |
+
x = (x*g3)/r1
|
266 |
+
y = (y*g2)/r2
|
267 |
+
z = (z*g1)/r3
|
268 |
+
x = x/z
|
269 |
+
y = y/z
|
270 |
+
|
271 |
+
if a == 0 and c == 0:
|
272 |
+
x_reg = (x + y - 2*e)/(2*b)
|
273 |
+
y_reg = (x - y - 2*d)/(2*b)
|
274 |
+
elif c != 0:
|
275 |
+
x_reg = (x - 2*d*c + b*e)/K
|
276 |
+
y_reg = (y - b*x_reg - e)/(2*c)
|
277 |
+
else:
|
278 |
+
y_reg = (x - 2*e*a + b*d)/K
|
279 |
+
x_reg = (y - b*y_reg - d)/(2*a)
|
280 |
+
|
281 |
+
return x_reg, y_reg
|
282 |
+
|
283 |
+
def singular_points(self):
|
284 |
+
"""
|
285 |
+
Returns a set of singular points of the region.
|
286 |
+
|
287 |
+
The singular points are those points on the region
|
288 |
+
where all partial derivatives vanish.
|
289 |
+
|
290 |
+
Examples
|
291 |
+
========
|
292 |
+
|
293 |
+
>>> from sympy.abc import x, y
|
294 |
+
>>> from sympy.vector import ImplicitRegion
|
295 |
+
>>> I = ImplicitRegion((x, y), (y-1)**2 -x**3 + 2*x**2 -x)
|
296 |
+
>>> I.singular_points()
|
297 |
+
{(1, 1)}
|
298 |
+
|
299 |
+
"""
|
300 |
+
eq_list = [self.equation]
|
301 |
+
for var in self.variables:
|
302 |
+
eq_list += [diff(self.equation, var)]
|
303 |
+
|
304 |
+
return nonlinsolve(eq_list, list(self.variables))
|
305 |
+
|
306 |
+
def multiplicity(self, point):
|
307 |
+
"""
|
308 |
+
Returns the multiplicity of a singular point on the region.
|
309 |
+
|
310 |
+
A singular point (x,y) of region is said to be of multiplicity m
|
311 |
+
if all the partial derivatives off to order m - 1 vanish there.
|
312 |
+
|
313 |
+
Examples
|
314 |
+
========
|
315 |
+
|
316 |
+
>>> from sympy.abc import x, y, z
|
317 |
+
>>> from sympy.vector import ImplicitRegion
|
318 |
+
>>> I = ImplicitRegion((x, y, z), x**2 + y**3 - z**4)
|
319 |
+
>>> I.singular_points()
|
320 |
+
{(0, 0, 0)}
|
321 |
+
>>> I.multiplicity((0, 0, 0))
|
322 |
+
2
|
323 |
+
|
324 |
+
"""
|
325 |
+
if isinstance(point, Point):
|
326 |
+
point = point.args
|
327 |
+
|
328 |
+
modified_eq = self.equation
|
329 |
+
|
330 |
+
for i, var in enumerate(self.variables):
|
331 |
+
modified_eq = modified_eq.subs(var, var + point[i])
|
332 |
+
modified_eq = expand(modified_eq)
|
333 |
+
|
334 |
+
if len(modified_eq.args) != 0:
|
335 |
+
terms = modified_eq.args
|
336 |
+
m = min([total_degree(term) for term in terms])
|
337 |
+
else:
|
338 |
+
terms = modified_eq
|
339 |
+
m = total_degree(terms)
|
340 |
+
|
341 |
+
return m
|
342 |
+
|
343 |
+
def rational_parametrization(self, parameters=('t', 's'), reg_point=None):
|
344 |
+
"""
|
345 |
+
Returns the rational parametrization of implicit region.
|
346 |
+
|
347 |
+
Examples
|
348 |
+
========
|
349 |
+
|
350 |
+
>>> from sympy import Eq
|
351 |
+
>>> from sympy.abc import x, y, z, s, t
|
352 |
+
>>> from sympy.vector import ImplicitRegion
|
353 |
+
|
354 |
+
>>> parabola = ImplicitRegion((x, y), y**2 - 4*x)
|
355 |
+
>>> parabola.rational_parametrization()
|
356 |
+
(4/t**2, 4/t)
|
357 |
+
|
358 |
+
>>> circle = ImplicitRegion((x, y), Eq(x**2 + y**2, 4))
|
359 |
+
>>> circle.rational_parametrization()
|
360 |
+
(4*t/(t**2 + 1), 4*t**2/(t**2 + 1) - 2)
|
361 |
+
|
362 |
+
>>> I = ImplicitRegion((x, y), x**3 + x**2 - y**2)
|
363 |
+
>>> I.rational_parametrization()
|
364 |
+
(t**2 - 1, t*(t**2 - 1))
|
365 |
+
|
366 |
+
>>> cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2)
|
367 |
+
>>> cubic_curve.rational_parametrization(parameters=(t))
|
368 |
+
(t**2 - 1, t*(t**2 - 1))
|
369 |
+
|
370 |
+
>>> sphere = ImplicitRegion((x, y, z), x**2 + y**2 + z**2 - 4)
|
371 |
+
>>> sphere.rational_parametrization(parameters=(t, s))
|
372 |
+
(-2 + 4/(s**2 + t**2 + 1), 4*s/(s**2 + t**2 + 1), 4*t/(s**2 + t**2 + 1))
|
373 |
+
|
374 |
+
For some conics, regular_points() is unable to find a point on curve.
|
375 |
+
To calulcate the parametric representation in such cases, user need
|
376 |
+
to determine a point on the region and pass it using reg_point.
|
377 |
+
|
378 |
+
>>> c = ImplicitRegion((x, y), (x - 1/2)**2 + (y)**2 - (1/4)**2)
|
379 |
+
>>> c.rational_parametrization(reg_point=(3/4, 0))
|
380 |
+
(0.75 - 0.5/(t**2 + 1), -0.5*t/(t**2 + 1))
|
381 |
+
|
382 |
+
References
|
383 |
+
==========
|
384 |
+
|
385 |
+
- Christoph M. Hoffmann, "Conversion Methods between Parametric and
|
386 |
+
Implicit Curves and Surfaces", Purdue e-Pubs, 1990. Available:
|
387 |
+
https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1827&context=cstech
|
388 |
+
|
389 |
+
"""
|
390 |
+
equation = self.equation
|
391 |
+
degree = self.degree
|
392 |
+
|
393 |
+
if degree == 1:
|
394 |
+
if len(self.variables) == 1:
|
395 |
+
return (equation,)
|
396 |
+
elif len(self.variables) == 2:
|
397 |
+
x, y = self.variables
|
398 |
+
y_par = list(solveset(equation, y))[0]
|
399 |
+
return x, y_par
|
400 |
+
else:
|
401 |
+
raise NotImplementedError()
|
402 |
+
|
403 |
+
point = ()
|
404 |
+
|
405 |
+
# Finding the (n - 1) fold point of the monoid of degree
|
406 |
+
if degree == 2:
|
407 |
+
# For degree 2 curves, either a regular point or a singular point can be used.
|
408 |
+
if reg_point is not None:
|
409 |
+
# Using point provided by the user as regular point
|
410 |
+
point = reg_point
|
411 |
+
else:
|
412 |
+
if len(self.singular_points()) != 0:
|
413 |
+
point = list(self.singular_points())[0]
|
414 |
+
else:
|
415 |
+
point = self.regular_point()
|
416 |
+
|
417 |
+
if len(self.singular_points()) != 0:
|
418 |
+
singular_points = self.singular_points()
|
419 |
+
for spoint in singular_points:
|
420 |
+
syms = Tuple(*spoint).free_symbols
|
421 |
+
rep = {s: 2 for s in syms}
|
422 |
+
|
423 |
+
if len(syms) != 0:
|
424 |
+
spoint = tuple(s.subs(rep) for s in spoint)
|
425 |
+
|
426 |
+
if self.multiplicity(spoint) == degree - 1:
|
427 |
+
point = spoint
|
428 |
+
break
|
429 |
+
|
430 |
+
if len(point) == 0:
|
431 |
+
# The region in not a monoid
|
432 |
+
raise NotImplementedError()
|
433 |
+
|
434 |
+
modified_eq = equation
|
435 |
+
|
436 |
+
# Shifting the region such that fold point moves to origin
|
437 |
+
for i, var in enumerate(self.variables):
|
438 |
+
modified_eq = modified_eq.subs(var, var + point[i])
|
439 |
+
modified_eq = expand(modified_eq)
|
440 |
+
|
441 |
+
hn = hn_1 = 0
|
442 |
+
for term in modified_eq.args:
|
443 |
+
if total_degree(term) == degree:
|
444 |
+
hn += term
|
445 |
+
else:
|
446 |
+
hn_1 += term
|
447 |
+
|
448 |
+
hn_1 = -1*hn_1
|
449 |
+
|
450 |
+
if not isinstance(parameters, tuple):
|
451 |
+
parameters = (parameters,)
|
452 |
+
|
453 |
+
if len(self.variables) == 2:
|
454 |
+
|
455 |
+
parameter1 = parameters[0]
|
456 |
+
if parameter1 == 's':
|
457 |
+
# To avoid name conflict between parameters
|
458 |
+
s = _symbol('s_', real=True)
|
459 |
+
else:
|
460 |
+
s = _symbol('s', real=True)
|
461 |
+
t = _symbol(parameter1, real=True)
|
462 |
+
|
463 |
+
hn = hn.subs({self.variables[0]: s, self.variables[1]: t})
|
464 |
+
hn_1 = hn_1.subs({self.variables[0]: s, self.variables[1]: t})
|
465 |
+
|
466 |
+
x_par = (s*(hn_1/hn)).subs(s, 1) + point[0]
|
467 |
+
y_par = (t*(hn_1/hn)).subs(s, 1) + point[1]
|
468 |
+
|
469 |
+
return x_par, y_par
|
470 |
+
|
471 |
+
elif len(self.variables) == 3:
|
472 |
+
|
473 |
+
parameter1, parameter2 = parameters
|
474 |
+
if 'r' in parameters:
|
475 |
+
# To avoid name conflict between parameters
|
476 |
+
r = _symbol('r_', real=True)
|
477 |
+
else:
|
478 |
+
r = _symbol('r', real=True)
|
479 |
+
s = _symbol(parameter2, real=True)
|
480 |
+
t = _symbol(parameter1, real=True)
|
481 |
+
|
482 |
+
hn = hn.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t})
|
483 |
+
hn_1 = hn_1.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t})
|
484 |
+
|
485 |
+
x_par = (r*(hn_1/hn)).subs(r, 1) + point[0]
|
486 |
+
y_par = (s*(hn_1/hn)).subs(r, 1) + point[1]
|
487 |
+
z_par = (t*(hn_1/hn)).subs(r, 1) + point[2]
|
488 |
+
|
489 |
+
return x_par, y_par, z_par
|
490 |
+
|
491 |
+
raise NotImplementedError()
|
492 |
+
|
493 |
+
def conic_coeff(variables, equation):
|
494 |
+
if total_degree(equation) != 2:
|
495 |
+
raise ValueError()
|
496 |
+
x = variables[0]
|
497 |
+
y = variables[1]
|
498 |
+
|
499 |
+
equation = expand(equation)
|
500 |
+
a = equation.coeff(x**2)
|
501 |
+
b = equation.coeff(x*y)
|
502 |
+
c = equation.coeff(y**2)
|
503 |
+
d = equation.coeff(x, 1).coeff(y, 0)
|
504 |
+
e = equation.coeff(y, 1).coeff(x, 0)
|
505 |
+
f = equation.coeff(x, 0).coeff(y, 0)
|
506 |
+
return a, b, c, d, e, f
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/integrals.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Basic, diff
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.sorting import default_sort_key
|
4 |
+
from sympy.matrices import Matrix
|
5 |
+
from sympy.integrals import Integral, integrate
|
6 |
+
from sympy.geometry.entity import GeometryEntity
|
7 |
+
from sympy.simplify.simplify import simplify
|
8 |
+
from sympy.utilities.iterables import topological_sort
|
9 |
+
from sympy.vector import (CoordSys3D, Vector, ParametricRegion,
|
10 |
+
parametric_region_list, ImplicitRegion)
|
11 |
+
from sympy.vector.operators import _get_coord_systems
|
12 |
+
|
13 |
+
|
14 |
+
class ParametricIntegral(Basic):
|
15 |
+
"""
|
16 |
+
Represents integral of a scalar or vector field
|
17 |
+
over a Parametric Region
|
18 |
+
|
19 |
+
Examples
|
20 |
+
========
|
21 |
+
|
22 |
+
>>> from sympy import cos, sin, pi
|
23 |
+
>>> from sympy.vector import CoordSys3D, ParametricRegion, ParametricIntegral
|
24 |
+
>>> from sympy.abc import r, t, theta, phi
|
25 |
+
|
26 |
+
>>> C = CoordSys3D('C')
|
27 |
+
>>> curve = ParametricRegion((3*t - 2, t + 1), (t, 1, 2))
|
28 |
+
>>> ParametricIntegral(C.x, curve)
|
29 |
+
5*sqrt(10)/2
|
30 |
+
>>> length = ParametricIntegral(1, curve)
|
31 |
+
>>> length
|
32 |
+
sqrt(10)
|
33 |
+
>>> semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\
|
34 |
+
(theta, 0, 2*pi), (phi, 0, pi/2))
|
35 |
+
>>> ParametricIntegral(C.z, semisphere)
|
36 |
+
8*pi
|
37 |
+
|
38 |
+
>>> ParametricIntegral(C.j + C.k, ParametricRegion((r*cos(theta), r*sin(theta)), r, theta))
|
39 |
+
0
|
40 |
+
|
41 |
+
"""
|
42 |
+
|
43 |
+
def __new__(cls, field, parametricregion):
|
44 |
+
|
45 |
+
coord_set = _get_coord_systems(field)
|
46 |
+
|
47 |
+
if len(coord_set) == 0:
|
48 |
+
coord_sys = CoordSys3D('C')
|
49 |
+
elif len(coord_set) > 1:
|
50 |
+
raise ValueError
|
51 |
+
else:
|
52 |
+
coord_sys = next(iter(coord_set))
|
53 |
+
|
54 |
+
if parametricregion.dimensions == 0:
|
55 |
+
return S.Zero
|
56 |
+
|
57 |
+
base_vectors = coord_sys.base_vectors()
|
58 |
+
base_scalars = coord_sys.base_scalars()
|
59 |
+
|
60 |
+
parametricfield = field
|
61 |
+
|
62 |
+
r = Vector.zero
|
63 |
+
for i in range(len(parametricregion.definition)):
|
64 |
+
r += base_vectors[i]*parametricregion.definition[i]
|
65 |
+
|
66 |
+
if len(coord_set) != 0:
|
67 |
+
for i in range(len(parametricregion.definition)):
|
68 |
+
parametricfield = parametricfield.subs(base_scalars[i], parametricregion.definition[i])
|
69 |
+
|
70 |
+
if parametricregion.dimensions == 1:
|
71 |
+
parameter = parametricregion.parameters[0]
|
72 |
+
|
73 |
+
r_diff = diff(r, parameter)
|
74 |
+
lower, upper = parametricregion.limits[parameter][0], parametricregion.limits[parameter][1]
|
75 |
+
|
76 |
+
if isinstance(parametricfield, Vector):
|
77 |
+
integrand = simplify(r_diff.dot(parametricfield))
|
78 |
+
else:
|
79 |
+
integrand = simplify(r_diff.magnitude()*parametricfield)
|
80 |
+
|
81 |
+
result = integrate(integrand, (parameter, lower, upper))
|
82 |
+
|
83 |
+
elif parametricregion.dimensions == 2:
|
84 |
+
u, v = cls._bounds_case(parametricregion.parameters, parametricregion.limits)
|
85 |
+
|
86 |
+
r_u = diff(r, u)
|
87 |
+
r_v = diff(r, v)
|
88 |
+
normal_vector = simplify(r_u.cross(r_v))
|
89 |
+
|
90 |
+
if isinstance(parametricfield, Vector):
|
91 |
+
integrand = parametricfield.dot(normal_vector)
|
92 |
+
else:
|
93 |
+
integrand = parametricfield*normal_vector.magnitude()
|
94 |
+
|
95 |
+
integrand = simplify(integrand)
|
96 |
+
|
97 |
+
lower_u, upper_u = parametricregion.limits[u][0], parametricregion.limits[u][1]
|
98 |
+
lower_v, upper_v = parametricregion.limits[v][0], parametricregion.limits[v][1]
|
99 |
+
|
100 |
+
result = integrate(integrand, (u, lower_u, upper_u), (v, lower_v, upper_v))
|
101 |
+
|
102 |
+
else:
|
103 |
+
variables = cls._bounds_case(parametricregion.parameters, parametricregion.limits)
|
104 |
+
coeff = Matrix(parametricregion.definition).jacobian(variables).det()
|
105 |
+
integrand = simplify(parametricfield*coeff)
|
106 |
+
|
107 |
+
l = [(var, parametricregion.limits[var][0], parametricregion.limits[var][1]) for var in variables]
|
108 |
+
result = integrate(integrand, *l)
|
109 |
+
|
110 |
+
if not isinstance(result, Integral):
|
111 |
+
return result
|
112 |
+
else:
|
113 |
+
return super().__new__(cls, field, parametricregion)
|
114 |
+
|
115 |
+
@classmethod
|
116 |
+
def _bounds_case(cls, parameters, limits):
|
117 |
+
|
118 |
+
V = list(limits.keys())
|
119 |
+
E = []
|
120 |
+
|
121 |
+
for p in V:
|
122 |
+
lower_p = limits[p][0]
|
123 |
+
upper_p = limits[p][1]
|
124 |
+
|
125 |
+
lower_p = lower_p.atoms()
|
126 |
+
upper_p = upper_p.atoms()
|
127 |
+
E.extend((p, q) for q in V if p != q and
|
128 |
+
(lower_p.issuperset({q}) or upper_p.issuperset({q})))
|
129 |
+
|
130 |
+
if not E:
|
131 |
+
return parameters
|
132 |
+
else:
|
133 |
+
return topological_sort((V, E), key=default_sort_key)
|
134 |
+
|
135 |
+
@property
|
136 |
+
def field(self):
|
137 |
+
return self.args[0]
|
138 |
+
|
139 |
+
@property
|
140 |
+
def parametricregion(self):
|
141 |
+
return self.args[1]
|
142 |
+
|
143 |
+
|
144 |
+
def vector_integrate(field, *region):
|
145 |
+
"""
|
146 |
+
Compute the integral of a vector/scalar field
|
147 |
+
over a a region or a set of parameters.
|
148 |
+
|
149 |
+
Examples
|
150 |
+
========
|
151 |
+
>>> from sympy.vector import CoordSys3D, ParametricRegion, vector_integrate
|
152 |
+
>>> from sympy.abc import x, y, t
|
153 |
+
>>> C = CoordSys3D('C')
|
154 |
+
|
155 |
+
>>> region = ParametricRegion((t, t**2), (t, 1, 5))
|
156 |
+
>>> vector_integrate(C.x*C.i, region)
|
157 |
+
12
|
158 |
+
|
159 |
+
Integrals over some objects of geometry module can also be calculated.
|
160 |
+
|
161 |
+
>>> from sympy.geometry import Point, Circle, Triangle
|
162 |
+
>>> c = Circle(Point(0, 2), 5)
|
163 |
+
>>> vector_integrate(C.x**2 + C.y**2, c)
|
164 |
+
290*pi
|
165 |
+
>>> triangle = Triangle(Point(-2, 3), Point(2, 3), Point(0, 5))
|
166 |
+
>>> vector_integrate(3*C.x**2*C.y*C.i + C.j, triangle)
|
167 |
+
-8
|
168 |
+
|
169 |
+
Integrals over some simple implicit regions can be computed. But in most cases,
|
170 |
+
it takes too long to compute over them. This is due to the expressions of parametric
|
171 |
+
representation becoming large.
|
172 |
+
|
173 |
+
>>> from sympy.vector import ImplicitRegion
|
174 |
+
>>> c2 = ImplicitRegion((x, y), (x - 2)**2 + (y - 1)**2 - 9)
|
175 |
+
>>> vector_integrate(1, c2)
|
176 |
+
6*pi
|
177 |
+
|
178 |
+
Integral of fields with respect to base scalars:
|
179 |
+
|
180 |
+
>>> vector_integrate(12*C.y**3, (C.y, 1, 3))
|
181 |
+
240
|
182 |
+
>>> vector_integrate(C.x**2*C.z, C.x)
|
183 |
+
C.x**3*C.z/3
|
184 |
+
>>> vector_integrate(C.x*C.i - C.y*C.k, C.x)
|
185 |
+
(Integral(C.x, C.x))*C.i + (Integral(-C.y, C.x))*C.k
|
186 |
+
>>> _.doit()
|
187 |
+
C.x**2/2*C.i + (-C.x*C.y)*C.k
|
188 |
+
|
189 |
+
"""
|
190 |
+
if len(region) == 1:
|
191 |
+
if isinstance(region[0], ParametricRegion):
|
192 |
+
return ParametricIntegral(field, region[0])
|
193 |
+
|
194 |
+
if isinstance(region[0], ImplicitRegion):
|
195 |
+
region = parametric_region_list(region[0])[0]
|
196 |
+
return vector_integrate(field, region)
|
197 |
+
|
198 |
+
if isinstance(region[0], GeometryEntity):
|
199 |
+
regions_list = parametric_region_list(region[0])
|
200 |
+
|
201 |
+
result = 0
|
202 |
+
for reg in regions_list:
|
203 |
+
result += vector_integrate(field, reg)
|
204 |
+
return result
|
205 |
+
|
206 |
+
return integrate(field, *region)
|
env-llmeval/lib/python3.10/site-packages/sympy/vector/orienters.py
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.core.sympify import sympify
|
3 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
4 |
+
from sympy.matrices.dense import (eye, rot_axis1, rot_axis2, rot_axis3)
|
5 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix
|
6 |
+
from sympy.core.cache import cacheit
|
7 |
+
from sympy.core.symbol import Str
|
8 |
+
import sympy.vector
|
9 |
+
|
10 |
+
|
11 |
+
class Orienter(Basic):
|
12 |
+
"""
|
13 |
+
Super-class for all orienter classes.
|
14 |
+
"""
|
15 |
+
|
16 |
+
def rotation_matrix(self):
|
17 |
+
"""
|
18 |
+
The rotation matrix corresponding to this orienter
|
19 |
+
instance.
|
20 |
+
"""
|
21 |
+
return self._parent_orient
|
22 |
+
|
23 |
+
|
24 |
+
class AxisOrienter(Orienter):
|
25 |
+
"""
|
26 |
+
Class to denote an axis orienter.
|
27 |
+
"""
|
28 |
+
|
29 |
+
def __new__(cls, angle, axis):
|
30 |
+
if not isinstance(axis, sympy.vector.Vector):
|
31 |
+
raise TypeError("axis should be a Vector")
|
32 |
+
angle = sympify(angle)
|
33 |
+
|
34 |
+
obj = super().__new__(cls, angle, axis)
|
35 |
+
obj._angle = angle
|
36 |
+
obj._axis = axis
|
37 |
+
|
38 |
+
return obj
|
39 |
+
|
40 |
+
def __init__(self, angle, axis):
|
41 |
+
"""
|
42 |
+
Axis rotation is a rotation about an arbitrary axis by
|
43 |
+
some angle. The angle is supplied as a SymPy expr scalar, and
|
44 |
+
the axis is supplied as a Vector.
|
45 |
+
|
46 |
+
Parameters
|
47 |
+
==========
|
48 |
+
|
49 |
+
angle : Expr
|
50 |
+
The angle by which the new system is to be rotated
|
51 |
+
|
52 |
+
axis : Vector
|
53 |
+
The axis around which the rotation has to be performed
|
54 |
+
|
55 |
+
Examples
|
56 |
+
========
|
57 |
+
|
58 |
+
>>> from sympy.vector import CoordSys3D
|
59 |
+
>>> from sympy import symbols
|
60 |
+
>>> q1 = symbols('q1')
|
61 |
+
>>> N = CoordSys3D('N')
|
62 |
+
>>> from sympy.vector import AxisOrienter
|
63 |
+
>>> orienter = AxisOrienter(q1, N.i + 2 * N.j)
|
64 |
+
>>> B = N.orient_new('B', (orienter, ))
|
65 |
+
|
66 |
+
"""
|
67 |
+
# Dummy initializer for docstrings
|
68 |
+
pass
|
69 |
+
|
70 |
+
@cacheit
|
71 |
+
def rotation_matrix(self, system):
|
72 |
+
"""
|
73 |
+
The rotation matrix corresponding to this orienter
|
74 |
+
instance.
|
75 |
+
|
76 |
+
Parameters
|
77 |
+
==========
|
78 |
+
|
79 |
+
system : CoordSys3D
|
80 |
+
The coordinate system wrt which the rotation matrix
|
81 |
+
is to be computed
|
82 |
+
"""
|
83 |
+
|
84 |
+
axis = sympy.vector.express(self.axis, system).normalize()
|
85 |
+
axis = axis.to_matrix(system)
|
86 |
+
theta = self.angle
|
87 |
+
parent_orient = ((eye(3) - axis * axis.T) * cos(theta) +
|
88 |
+
Matrix([[0, -axis[2], axis[1]],
|
89 |
+
[axis[2], 0, -axis[0]],
|
90 |
+
[-axis[1], axis[0], 0]]) * sin(theta) +
|
91 |
+
axis * axis.T)
|
92 |
+
parent_orient = parent_orient.T
|
93 |
+
return parent_orient
|
94 |
+
|
95 |
+
@property
|
96 |
+
def angle(self):
|
97 |
+
return self._angle
|
98 |
+
|
99 |
+
@property
|
100 |
+
def axis(self):
|
101 |
+
return self._axis
|
102 |
+
|
103 |
+
|
104 |
+
class ThreeAngleOrienter(Orienter):
|
105 |
+
"""
|
106 |
+
Super-class for Body and Space orienters.
|
107 |
+
"""
|
108 |
+
|
109 |
+
def __new__(cls, angle1, angle2, angle3, rot_order):
|
110 |
+
if isinstance(rot_order, Str):
|
111 |
+
rot_order = rot_order.name
|
112 |
+
|
113 |
+
approved_orders = ('123', '231', '312', '132', '213',
|
114 |
+
'321', '121', '131', '212', '232',
|
115 |
+
'313', '323', '')
|
116 |
+
original_rot_order = rot_order
|
117 |
+
rot_order = str(rot_order).upper()
|
118 |
+
if not (len(rot_order) == 3):
|
119 |
+
raise TypeError('rot_order should be a str of length 3')
|
120 |
+
rot_order = [i.replace('X', '1') for i in rot_order]
|
121 |
+
rot_order = [i.replace('Y', '2') for i in rot_order]
|
122 |
+
rot_order = [i.replace('Z', '3') for i in rot_order]
|
123 |
+
rot_order = ''.join(rot_order)
|
124 |
+
if rot_order not in approved_orders:
|
125 |
+
raise TypeError('Invalid rot_type parameter')
|
126 |
+
a1 = int(rot_order[0])
|
127 |
+
a2 = int(rot_order[1])
|
128 |
+
a3 = int(rot_order[2])
|
129 |
+
angle1 = sympify(angle1)
|
130 |
+
angle2 = sympify(angle2)
|
131 |
+
angle3 = sympify(angle3)
|
132 |
+
if cls._in_order:
|
133 |
+
parent_orient = (_rot(a1, angle1) *
|
134 |
+
_rot(a2, angle2) *
|
135 |
+
_rot(a3, angle3))
|
136 |
+
else:
|
137 |
+
parent_orient = (_rot(a3, angle3) *
|
138 |
+
_rot(a2, angle2) *
|
139 |
+
_rot(a1, angle1))
|
140 |
+
parent_orient = parent_orient.T
|
141 |
+
|
142 |
+
obj = super().__new__(
|
143 |
+
cls, angle1, angle2, angle3, Str(rot_order))
|
144 |
+
obj._angle1 = angle1
|
145 |
+
obj._angle2 = angle2
|
146 |
+
obj._angle3 = angle3
|
147 |
+
obj._rot_order = original_rot_order
|
148 |
+
obj._parent_orient = parent_orient
|
149 |
+
|
150 |
+
return obj
|
151 |
+
|
152 |
+
@property
|
153 |
+
def angle1(self):
|
154 |
+
return self._angle1
|
155 |
+
|
156 |
+
@property
|
157 |
+
def angle2(self):
|
158 |
+
return self._angle2
|
159 |
+
|
160 |
+
@property
|
161 |
+
def angle3(self):
|
162 |
+
return self._angle3
|
163 |
+
|
164 |
+
@property
|
165 |
+
def rot_order(self):
|
166 |
+
return self._rot_order
|
167 |
+
|
168 |
+
|
169 |
+
class BodyOrienter(ThreeAngleOrienter):
|
170 |
+
"""
|
171 |
+
Class to denote a body-orienter.
|
172 |
+
"""
|
173 |
+
|
174 |
+
_in_order = True
|
175 |
+
|
176 |
+
def __new__(cls, angle1, angle2, angle3, rot_order):
|
177 |
+
obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3,
|
178 |
+
rot_order)
|
179 |
+
return obj
|
180 |
+
|
181 |
+
def __init__(self, angle1, angle2, angle3, rot_order):
|
182 |
+
"""
|
183 |
+
Body orientation takes this coordinate system through three
|
184 |
+
successive simple rotations.
|
185 |
+
|
186 |
+
Body fixed rotations include both Euler Angles and
|
187 |
+
Tait-Bryan Angles, see https://en.wikipedia.org/wiki/Euler_angles.
|
188 |
+
|
189 |
+
Parameters
|
190 |
+
==========
|
191 |
+
|
192 |
+
angle1, angle2, angle3 : Expr
|
193 |
+
Three successive angles to rotate the coordinate system by
|
194 |
+
|
195 |
+
rotation_order : string
|
196 |
+
String defining the order of axes for rotation
|
197 |
+
|
198 |
+
Examples
|
199 |
+
========
|
200 |
+
|
201 |
+
>>> from sympy.vector import CoordSys3D, BodyOrienter
|
202 |
+
>>> from sympy import symbols
|
203 |
+
>>> q1, q2, q3 = symbols('q1 q2 q3')
|
204 |
+
>>> N = CoordSys3D('N')
|
205 |
+
|
206 |
+
A 'Body' fixed rotation is described by three angles and
|
207 |
+
three body-fixed rotation axes. To orient a coordinate system D
|
208 |
+
with respect to N, each sequential rotation is always about
|
209 |
+
the orthogonal unit vectors fixed to D. For example, a '123'
|
210 |
+
rotation will specify rotations about N.i, then D.j, then
|
211 |
+
D.k. (Initially, D.i is same as N.i)
|
212 |
+
Therefore,
|
213 |
+
|
214 |
+
>>> body_orienter = BodyOrienter(q1, q2, q3, '123')
|
215 |
+
>>> D = N.orient_new('D', (body_orienter, ))
|
216 |
+
|
217 |
+
is same as
|
218 |
+
|
219 |
+
>>> from sympy.vector import AxisOrienter
|
220 |
+
>>> axis_orienter1 = AxisOrienter(q1, N.i)
|
221 |
+
>>> D = N.orient_new('D', (axis_orienter1, ))
|
222 |
+
>>> axis_orienter2 = AxisOrienter(q2, D.j)
|
223 |
+
>>> D = D.orient_new('D', (axis_orienter2, ))
|
224 |
+
>>> axis_orienter3 = AxisOrienter(q3, D.k)
|
225 |
+
>>> D = D.orient_new('D', (axis_orienter3, ))
|
226 |
+
|
227 |
+
Acceptable rotation orders are of length 3, expressed in XYZ or
|
228 |
+
123, and cannot have a rotation about about an axis twice in a row.
|
229 |
+
|
230 |
+
>>> body_orienter1 = BodyOrienter(q1, q2, q3, '123')
|
231 |
+
>>> body_orienter2 = BodyOrienter(q1, q2, 0, 'ZXZ')
|
232 |
+
>>> body_orienter3 = BodyOrienter(0, 0, 0, 'XYX')
|
233 |
+
|
234 |
+
"""
|
235 |
+
# Dummy initializer for docstrings
|
236 |
+
pass
|
237 |
+
|
238 |
+
|
239 |
+
class SpaceOrienter(ThreeAngleOrienter):
|
240 |
+
"""
|
241 |
+
Class to denote a space-orienter.
|
242 |
+
"""
|
243 |
+
|
244 |
+
_in_order = False
|
245 |
+
|
246 |
+
def __new__(cls, angle1, angle2, angle3, rot_order):
|
247 |
+
obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3,
|
248 |
+
rot_order)
|
249 |
+
return obj
|
250 |
+
|
251 |
+
def __init__(self, angle1, angle2, angle3, rot_order):
|
252 |
+
"""
|
253 |
+
Space rotation is similar to Body rotation, but the rotations
|
254 |
+
are applied in the opposite order.
|
255 |
+
|
256 |
+
Parameters
|
257 |
+
==========
|
258 |
+
|
259 |
+
angle1, angle2, angle3 : Expr
|
260 |
+
Three successive angles to rotate the coordinate system by
|
261 |
+
|
262 |
+
rotation_order : string
|
263 |
+
String defining the order of axes for rotation
|
264 |
+
|
265 |
+
See Also
|
266 |
+
========
|
267 |
+
|
268 |
+
BodyOrienter : Orienter to orient systems wrt Euler angles.
|
269 |
+
|
270 |
+
Examples
|
271 |
+
========
|
272 |
+
|
273 |
+
>>> from sympy.vector import CoordSys3D, SpaceOrienter
|
274 |
+
>>> from sympy import symbols
|
275 |
+
>>> q1, q2, q3 = symbols('q1 q2 q3')
|
276 |
+
>>> N = CoordSys3D('N')
|
277 |
+
|
278 |
+
To orient a coordinate system D with respect to N, each
|
279 |
+
sequential rotation is always about N's orthogonal unit vectors.
|
280 |
+
For example, a '123' rotation will specify rotations about
|
281 |
+
N.i, then N.j, then N.k.
|
282 |
+
Therefore,
|
283 |
+
|
284 |
+
>>> space_orienter = SpaceOrienter(q1, q2, q3, '312')
|
285 |
+
>>> D = N.orient_new('D', (space_orienter, ))
|
286 |
+
|
287 |
+
is same as
|
288 |
+
|
289 |
+
>>> from sympy.vector import AxisOrienter
|
290 |
+
>>> axis_orienter1 = AxisOrienter(q1, N.i)
|
291 |
+
>>> B = N.orient_new('B', (axis_orienter1, ))
|
292 |
+
>>> axis_orienter2 = AxisOrienter(q2, N.j)
|
293 |
+
>>> C = B.orient_new('C', (axis_orienter2, ))
|
294 |
+
>>> axis_orienter3 = AxisOrienter(q3, N.k)
|
295 |
+
>>> D = C.orient_new('C', (axis_orienter3, ))
|
296 |
+
|
297 |
+
"""
|
298 |
+
# Dummy initializer for docstrings
|
299 |
+
pass
|
300 |
+
|
301 |
+
|
302 |
+
class QuaternionOrienter(Orienter):
|
303 |
+
"""
|
304 |
+
Class to denote a quaternion-orienter.
|
305 |
+
"""
|
306 |
+
|
307 |
+
def __new__(cls, q0, q1, q2, q3):
|
308 |
+
q0 = sympify(q0)
|
309 |
+
q1 = sympify(q1)
|
310 |
+
q2 = sympify(q2)
|
311 |
+
q3 = sympify(q3)
|
312 |
+
parent_orient = (Matrix([[q0 ** 2 + q1 ** 2 - q2 ** 2 -
|
313 |
+
q3 ** 2,
|
314 |
+
2 * (q1 * q2 - q0 * q3),
|
315 |
+
2 * (q0 * q2 + q1 * q3)],
|
316 |
+
[2 * (q1 * q2 + q0 * q3),
|
317 |
+
q0 ** 2 - q1 ** 2 +
|
318 |
+
q2 ** 2 - q3 ** 2,
|
319 |
+
2 * (q2 * q3 - q0 * q1)],
|
320 |
+
[2 * (q1 * q3 - q0 * q2),
|
321 |
+
2 * (q0 * q1 + q2 * q3),
|
322 |
+
q0 ** 2 - q1 ** 2 -
|
323 |
+
q2 ** 2 + q3 ** 2]]))
|
324 |
+
parent_orient = parent_orient.T
|
325 |
+
|
326 |
+
obj = super().__new__(cls, q0, q1, q2, q3)
|
327 |
+
obj._q0 = q0
|
328 |
+
obj._q1 = q1
|
329 |
+
obj._q2 = q2
|
330 |
+
obj._q3 = q3
|
331 |
+
obj._parent_orient = parent_orient
|
332 |
+
|
333 |
+
return obj
|
334 |
+
|
335 |
+
def __init__(self, angle1, angle2, angle3, rot_order):
|
336 |
+
"""
|
337 |
+
Quaternion orientation orients the new CoordSys3D with
|
338 |
+
Quaternions, defined as a finite rotation about lambda, a unit
|
339 |
+
vector, by some amount theta.
|
340 |
+
|
341 |
+
This orientation is described by four parameters:
|
342 |
+
|
343 |
+
q0 = cos(theta/2)
|
344 |
+
|
345 |
+
q1 = lambda_x sin(theta/2)
|
346 |
+
|
347 |
+
q2 = lambda_y sin(theta/2)
|
348 |
+
|
349 |
+
q3 = lambda_z sin(theta/2)
|
350 |
+
|
351 |
+
Quaternion does not take in a rotation order.
|
352 |
+
|
353 |
+
Parameters
|
354 |
+
==========
|
355 |
+
|
356 |
+
q0, q1, q2, q3 : Expr
|
357 |
+
The quaternions to rotate the coordinate system by
|
358 |
+
|
359 |
+
Examples
|
360 |
+
========
|
361 |
+
|
362 |
+
>>> from sympy.vector import CoordSys3D
|
363 |
+
>>> from sympy import symbols
|
364 |
+
>>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
|
365 |
+
>>> N = CoordSys3D('N')
|
366 |
+
>>> from sympy.vector import QuaternionOrienter
|
367 |
+
>>> q_orienter = QuaternionOrienter(q0, q1, q2, q3)
|
368 |
+
>>> B = N.orient_new('B', (q_orienter, ))
|
369 |
+
|
370 |
+
"""
|
371 |
+
# Dummy initializer for docstrings
|
372 |
+
pass
|
373 |
+
|
374 |
+
@property
|
375 |
+
def q0(self):
|
376 |
+
return self._q0
|
377 |
+
|
378 |
+
@property
|
379 |
+
def q1(self):
|
380 |
+
return self._q1
|
381 |
+
|
382 |
+
@property
|
383 |
+
def q2(self):
|
384 |
+
return self._q2
|
385 |
+
|
386 |
+
@property
|
387 |
+
def q3(self):
|
388 |
+
return self._q3
|
389 |
+
|
390 |
+
|
391 |
+
def _rot(axis, angle):
|
392 |
+
"""DCM for simple axis 1, 2 or 3 rotations. """
|
393 |
+
if axis == 1:
|
394 |
+
return Matrix(rot_axis1(angle).T)
|
395 |
+
elif axis == 2:
|
396 |
+
return Matrix(rot_axis2(angle).T)
|
397 |
+
elif axis == 3:
|
398 |
+
return Matrix(rot_axis3(angle).T)
|