applied-ai-018 commited on
Commit
6deb680
·
verified ·
1 Parent(s): 1e07062

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/_print_helpers.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/assumptions_generated.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/containers.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/core.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/coreerrors.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/decorators.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/logic.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/mul.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/multidimensional.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/parameters.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/power.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/relational.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/sympify.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/trace.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/traversal.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/core/benchmarks/bench_assumptions.py +12 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/series/__init__.py +23 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/acceleration.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/approximants.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/aseries.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/fourier.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/gruntz.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/kauers.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/limits.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/limitseq.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/sequences.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/series/acceleration.py +101 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/series/approximants.py +103 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/series/aseries.py +10 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__init__.py +0 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__pycache__/bench_limit.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__pycache__/bench_order.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/bench_limit.py +9 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/bench_order.py +10 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/series/formal.py +1869 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/series/fourier.py +808 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/series/gruntz.py +738 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/series/kauers.py +51 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/series/limits.py +385 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/series/limitseq.py +257 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/series/order.py +517 -0
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/_print_helpers.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/assumptions_generated.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/containers.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/core.cpython-310.pyc ADDED
Binary file (1.67 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/coreerrors.cpython-310.pyc ADDED
Binary file (663 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/decorators.cpython-310.pyc ADDED
Binary file (7.87 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc ADDED
Binary file (101 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/logic.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/mul.cpython-310.pyc ADDED
Binary file (54.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/multidimensional.cpython-310.pyc ADDED
Binary file (3.91 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/parameters.cpython-310.pyc ADDED
Binary file (4.09 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/power.cpython-310.pyc ADDED
Binary file (50.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/relational.cpython-310.pyc ADDED
Binary file (44.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/sympify.cpython-310.pyc ADDED
Binary file (16.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/trace.cpython-310.pyc ADDED
Binary file (505 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/__pycache__/traversal.cpython-310.pyc ADDED
Binary file (9.21 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/core/benchmarks/bench_assumptions.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Symbol, Integer
2
+
3
+ x = Symbol('x')
4
+ i3 = Integer(3)
5
+
6
+
7
+ def timeit_x_is_integer():
8
+ x.is_integer
9
+
10
+
11
+ def timeit_Integer_is_irrational():
12
+ i3.is_irrational
env-llmeval/lib/python3.10/site-packages/sympy/series/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module that handles series: find a limit, order the series etc.
2
+ """
3
+ from .order import Order
4
+ from .limits import limit, Limit
5
+ from .gruntz import gruntz
6
+ from .series import series
7
+ from .approximants import approximants
8
+ from .residues import residue
9
+ from .sequences import SeqPer, SeqFormula, sequence, SeqAdd, SeqMul
10
+ from .fourier import fourier_series
11
+ from .formal import fps
12
+ from .limitseq import difference_delta, limit_seq
13
+
14
+ from sympy.core.singleton import S
15
+ EmptySequence = S.EmptySequence
16
+
17
+ O = Order
18
+
19
+ __all__ = ['Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
20
+ 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence',
21
+ 'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta',
22
+ 'limit_seq'
23
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (937 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/acceleration.cpython-310.pyc ADDED
Binary file (3.83 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/approximants.cpython-310.pyc ADDED
Binary file (3.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/aseries.cpython-310.pyc ADDED
Binary file (485 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc ADDED
Binary file (51.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/fourier.cpython-310.pyc ADDED
Binary file (24.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/gruntz.cpython-310.pyc ADDED
Binary file (21.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/kauers.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/limits.cpython-310.pyc ADDED
Binary file (9.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/limitseq.cpython-310.pyc ADDED
Binary file (7.25 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/sequences.cpython-310.pyc ADDED
Binary file (35.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc ADDED
Binary file (2.11 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc ADDED
Binary file (3.72 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/acceleration.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convergence acceleration / extrapolation methods for series and
3
+ sequences.
4
+
5
+ References:
6
+ Carl M. Bender & Steven A. Orszag, "Advanced Mathematical Methods for
7
+ Scientists and Engineers: Asymptotic Methods and Perturbation Theory",
8
+ Springer 1999. (Shanks transformation: pp. 368-375, Richardson
9
+ extrapolation: pp. 375-377.)
10
+ """
11
+
12
+ from sympy.core.numbers import Integer
13
+ from sympy.core.singleton import S
14
+ from sympy.functions.combinatorial.factorials import factorial
15
+
16
+
17
+ def richardson(A, k, n, N):
18
+ """
19
+ Calculate an approximation for lim k->oo A(k) using Richardson
20
+ extrapolation with the terms A(n), A(n+1), ..., A(n+N+1).
21
+ Choosing N ~= 2*n often gives good results.
22
+
23
+ Examples
24
+ ========
25
+
26
+ A simple example is to calculate exp(1) using the limit definition.
27
+ This limit converges slowly; n = 100 only produces two accurate
28
+ digits:
29
+
30
+ >>> from sympy.abc import n
31
+ >>> e = (1 + 1/n)**n
32
+ >>> print(round(e.subs(n, 100).evalf(), 10))
33
+ 2.7048138294
34
+
35
+ Richardson extrapolation with 11 appropriately chosen terms gives
36
+ a value that is accurate to the indicated precision:
37
+
38
+ >>> from sympy import E
39
+ >>> from sympy.series.acceleration import richardson
40
+ >>> print(round(richardson(e, n, 10, 20).evalf(), 10))
41
+ 2.7182818285
42
+ >>> print(round(E.evalf(), 10))
43
+ 2.7182818285
44
+
45
+ Another useful application is to speed up convergence of series.
46
+ Computing 100 terms of the zeta(2) series 1/k**2 yields only
47
+ two accurate digits:
48
+
49
+ >>> from sympy.abc import k, n
50
+ >>> from sympy import Sum
51
+ >>> A = Sum(k**-2, (k, 1, n))
52
+ >>> print(round(A.subs(n, 100).evalf(), 10))
53
+ 1.6349839002
54
+
55
+ Richardson extrapolation performs much better:
56
+
57
+ >>> from sympy import pi
58
+ >>> print(round(richardson(A, n, 10, 20).evalf(), 10))
59
+ 1.6449340668
60
+ >>> print(round(((pi**2)/6).evalf(), 10)) # Exact value
61
+ 1.6449340668
62
+
63
+ """
64
+ s = S.Zero
65
+ for j in range(0, N + 1):
66
+ s += (A.subs(k, Integer(n + j)).doit() * (n + j)**N *
67
+ S.NegativeOne**(j + N) / (factorial(j) * factorial(N - j)))
68
+ return s
69
+
70
+
71
+ def shanks(A, k, n, m=1):
72
+ """
73
+ Calculate an approximation for lim k->oo A(k) using the n-term Shanks
74
+ transformation S(A)(n). With m > 1, calculate the m-fold recursive
75
+ Shanks transformation S(S(...S(A)...))(n).
76
+
77
+ The Shanks transformation is useful for summing Taylor series that
78
+ converge slowly near a pole or singularity, e.g. for log(2):
79
+
80
+ >>> from sympy.abc import k, n
81
+ >>> from sympy import Sum, Integer
82
+ >>> from sympy.series.acceleration import shanks
83
+ >>> A = Sum(Integer(-1)**(k+1) / k, (k, 1, n))
84
+ >>> print(round(A.subs(n, 100).doit().evalf(), 10))
85
+ 0.6881721793
86
+ >>> print(round(shanks(A, n, 25).evalf(), 10))
87
+ 0.6931396564
88
+ >>> print(round(shanks(A, n, 25, 5).evalf(), 10))
89
+ 0.6931471806
90
+
91
+ The correct value is 0.6931471805599453094172321215.
92
+ """
93
+ table = [A.subs(k, Integer(j)).doit() for j in range(n + m + 2)]
94
+ table2 = table[:]
95
+
96
+ for i in range(1, m + 1):
97
+ for j in range(i, n + m + 1):
98
+ x, y, z = table[j - 1], table[j], table[j + 1]
99
+ table2[j] = (z*x - y**2) / (z + x - 2*y)
100
+ table = table2[:]
101
+ return table[n]
env-llmeval/lib/python3.10/site-packages/sympy/series/approximants.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.polys.polytools import lcm
4
+ from sympy.utilities import public
5
+
6
+ @public
7
+ def approximants(l, X=Symbol('x'), simplify=False):
8
+ """
9
+ Return a generator for consecutive Pade approximants for a series.
10
+ It can also be used for computing the rational generating function of a
11
+ series when possible, since the last approximant returned by the generator
12
+ will be the generating function (if any).
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ The input list can contain more complex expressions than integer or rational
18
+ numbers; symbols may also be involved in the computation. An example below
19
+ show how to compute the generating function of the whole Pascal triangle.
20
+
21
+ The generator can be asked to apply the sympy.simplify function on each
22
+ generated term, which will make the computation slower; however it may be
23
+ useful when symbols are involved in the expressions.
24
+
25
+ Examples
26
+ ========
27
+
28
+ >>> from sympy.series import approximants
29
+ >>> from sympy import lucas, fibonacci, symbols, binomial
30
+ >>> g = [lucas(k) for k in range(16)]
31
+ >>> [e for e in approximants(g)]
32
+ [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)]
33
+
34
+ >>> h = [fibonacci(k) for k in range(16)]
35
+ >>> [e for e in approximants(h)]
36
+ [x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)]
37
+
38
+ >>> x, t = symbols("x,t")
39
+ >>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
40
+ >>> y = approximants(p, t)
41
+ >>> for k in range(3): print(next(y))
42
+ 1
43
+ (x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1)))
44
+ nan
45
+
46
+ >>> y = approximants(p, t, simplify=True)
47
+ >>> for k in range(3): print(next(y))
48
+ 1
49
+ -1/(t*(x + 1) - 1)
50
+ nan
51
+
52
+ See Also
53
+ ========
54
+
55
+ sympy.concrete.guess.guess_generating_function_rational
56
+ mpmath.pade
57
+ """
58
+ from sympy.simplify import simplify as simp
59
+ from sympy.simplify.radsimp import denom
60
+ p1, q1 = [S.One], [S.Zero]
61
+ p2, q2 = [S.Zero], [S.One]
62
+ while len(l):
63
+ b = 0
64
+ while l[b]==0:
65
+ b += 1
66
+ if b == len(l):
67
+ return
68
+ m = [S.One/l[b]]
69
+ for k in range(b+1, len(l)):
70
+ s = 0
71
+ for j in range(b, k):
72
+ s -= l[j+1] * m[b-j-1]
73
+ m.append(s/l[b])
74
+ l = m
75
+ a, l[0] = l[0], 0
76
+ p = [0] * max(len(p2), b+len(p1))
77
+ q = [0] * max(len(q2), b+len(q1))
78
+ for k in range(len(p2)):
79
+ p[k] = a*p2[k]
80
+ for k in range(b, b+len(p1)):
81
+ p[k] += p1[k-b]
82
+ for k in range(len(q2)):
83
+ q[k] = a*q2[k]
84
+ for k in range(b, b+len(q1)):
85
+ q[k] += q1[k-b]
86
+ while p[-1]==0: p.pop()
87
+ while q[-1]==0: q.pop()
88
+ p1, p2 = p2, p
89
+ q1, q2 = q2, q
90
+
91
+ # yield result
92
+ c = 1
93
+ for x in p:
94
+ c = lcm(c, denom(x))
95
+ for x in q:
96
+ c = lcm(c, denom(x))
97
+ out = ( sum(c*e*X**k for k, e in enumerate(p))
98
+ / sum(c*e*X**k for k, e in enumerate(q)) )
99
+ if simplify:
100
+ yield(simp(out))
101
+ else:
102
+ yield out
103
+ return
env-llmeval/lib/python3.10/site-packages/sympy/series/aseries.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.sympify import sympify
2
+
3
+
4
+ def aseries(expr, x=None, n=6, bound=0, hir=False):
5
+ """
6
+ See the docstring of Expr.aseries() for complete details of this wrapper.
7
+
8
+ """
9
+ expr = sympify(expr)
10
+ return expr.aseries(x, n, bound, hir)
env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__pycache__/bench_limit.cpython-310.pyc ADDED
Binary file (494 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/__pycache__/bench_order.cpython-310.pyc ADDED
Binary file (650 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/bench_limit.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import oo
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.series.limits import limit
4
+
5
+ x = Symbol('x')
6
+
7
+
8
+ def timeit_limit_1x():
9
+ limit(1/x, x, oo)
env-llmeval/lib/python3.10/site-packages/sympy/series/benchmarks/bench_order.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.series.order import O
4
+
5
+ x = Symbol('x')
6
+ l = [x**i for i in range(1000)]
7
+ l.append(O(x**1001))
8
+
9
+ def timeit_order_1x():
10
+ Add(*l)
env-llmeval/lib/python3.10/site-packages/sympy/series/formal.py ADDED
@@ -0,0 +1,1869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Formal Power Series"""
2
+
3
+ from collections import defaultdict
4
+
5
+ from sympy.core.numbers import (nan, oo, zoo)
6
+ from sympy.core.add import Add
7
+ from sympy.core.expr import Expr
8
+ from sympy.core.function import Derivative, Function, expand
9
+ from sympy.core.mul import Mul
10
+ from sympy.core.numbers import Rational
11
+ from sympy.core.relational import Eq
12
+ from sympy.sets.sets import Interval
13
+ from sympy.core.singleton import S
14
+ from sympy.core.symbol import Wild, Dummy, symbols, Symbol
15
+ from sympy.core.sympify import sympify
16
+ from sympy.discrete.convolutions import convolution
17
+ from sympy.functions.combinatorial.factorials import binomial, factorial, rf
18
+ from sympy.functions.combinatorial.numbers import bell
19
+ from sympy.functions.elementary.integers import floor, frac, ceiling
20
+ from sympy.functions.elementary.miscellaneous import Min, Max
21
+ from sympy.functions.elementary.piecewise import Piecewise
22
+ from sympy.series.limits import Limit
23
+ from sympy.series.order import Order
24
+ from sympy.series.sequences import sequence
25
+ from sympy.series.series_class import SeriesBase
26
+ from sympy.utilities.iterables import iterable
27
+
28
+
29
+
30
+ def rational_algorithm(f, x, k, order=4, full=False):
31
+ """
32
+ Rational algorithm for computing
33
+ formula of coefficients of Formal Power Series
34
+ of a function.
35
+
36
+ Explanation
37
+ ===========
38
+
39
+ Applicable when f(x) or some derivative of f(x)
40
+ is a rational function in x.
41
+
42
+ :func:`rational_algorithm` uses :func:`~.apart` function for partial fraction
43
+ decomposition. :func:`~.apart` by default uses 'undetermined coefficients
44
+ method'. By setting ``full=True``, 'Bronstein's algorithm' can be used
45
+ instead.
46
+
47
+ Looks for derivative of a function up to 4'th order (by default).
48
+ This can be overridden using order option.
49
+
50
+ Parameters
51
+ ==========
52
+
53
+ x : Symbol
54
+ order : int, optional
55
+ Order of the derivative of ``f``, Default is 4.
56
+ full : bool
57
+
58
+ Returns
59
+ =======
60
+
61
+ formula : Expr
62
+ ind : Expr
63
+ Independent terms.
64
+ order : int
65
+ full : bool
66
+
67
+ Examples
68
+ ========
69
+
70
+ >>> from sympy import log, atan
71
+ >>> from sympy.series.formal import rational_algorithm as ra
72
+ >>> from sympy.abc import x, k
73
+
74
+ >>> ra(1 / (1 - x), x, k)
75
+ (1, 0, 0)
76
+ >>> ra(log(1 + x), x, k)
77
+ (-1/((-1)**k*k), 0, 1)
78
+
79
+ >>> ra(atan(x), x, k, full=True)
80
+ ((-I/(2*(-I)**k) + I/(2*I**k))/k, 0, 1)
81
+
82
+ Notes
83
+ =====
84
+
85
+ By setting ``full=True``, range of admissible functions to be solved using
86
+ ``rational_algorithm`` can be increased. This option should be used
87
+ carefully as it can significantly slow down the computation as ``doit`` is
88
+ performed on the :class:`~.RootSum` object returned by the :func:`~.apart`
89
+ function. Use ``full=False`` whenever possible.
90
+
91
+ See Also
92
+ ========
93
+
94
+ sympy.polys.partfrac.apart
95
+
96
+ References
97
+ ==========
98
+
99
+ .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
100
+ .. [2] Power Series in Computer Algebra - Wolfram Koepf
101
+
102
+ """
103
+ from sympy.polys import RootSum, apart
104
+ from sympy.integrals import integrate
105
+
106
+ diff = f
107
+ ds = [] # list of diff
108
+
109
+ for i in range(order + 1):
110
+ if i:
111
+ diff = diff.diff(x)
112
+
113
+ if diff.is_rational_function(x):
114
+ coeff, sep = S.Zero, S.Zero
115
+
116
+ terms = apart(diff, x, full=full)
117
+ if terms.has(RootSum):
118
+ terms = terms.doit()
119
+
120
+ for t in Add.make_args(terms):
121
+ num, den = t.as_numer_denom()
122
+ if not den.has(x):
123
+ sep += t
124
+ else:
125
+ if isinstance(den, Mul):
126
+ # m*(n*x - a)**j -> (n*x - a)**j
127
+ ind = den.as_independent(x)
128
+ den = ind[1]
129
+ num /= ind[0]
130
+
131
+ # (n*x - a)**j -> (x - b)
132
+ den, j = den.as_base_exp()
133
+ a, xterm = den.as_coeff_add(x)
134
+
135
+ # term -> m/x**n
136
+ if not a:
137
+ sep += t
138
+ continue
139
+
140
+ xc = xterm[0].coeff(x)
141
+ a /= -xc
142
+ num /= xc**j
143
+
144
+ ak = ((-1)**j * num *
145
+ binomial(j + k - 1, k).rewrite(factorial) /
146
+ a**(j + k))
147
+ coeff += ak
148
+
149
+ # Hacky, better way?
150
+ if coeff.is_zero:
151
+ return None
152
+ if (coeff.has(x) or coeff.has(zoo) or coeff.has(oo) or
153
+ coeff.has(nan)):
154
+ return None
155
+
156
+ for j in range(i):
157
+ coeff = (coeff / (k + j + 1))
158
+ sep = integrate(sep, x)
159
+ sep += (ds.pop() - sep).limit(x, 0) # constant of integration
160
+ return (coeff.subs(k, k - i), sep, i)
161
+
162
+ else:
163
+ ds.append(diff)
164
+
165
+ return None
166
+
167
+
168
+ def rational_independent(terms, x):
169
+ """
170
+ Returns a list of all the rationally independent terms.
171
+
172
+ Examples
173
+ ========
174
+
175
+ >>> from sympy import sin, cos
176
+ >>> from sympy.series.formal import rational_independent
177
+ >>> from sympy.abc import x
178
+
179
+ >>> rational_independent([cos(x), sin(x)], x)
180
+ [cos(x), sin(x)]
181
+ >>> rational_independent([x**2, sin(x), x*sin(x), x**3], x)
182
+ [x**3 + x**2, x*sin(x) + sin(x)]
183
+ """
184
+ if not terms:
185
+ return []
186
+
187
+ ind = terms[0:1]
188
+
189
+ for t in terms[1:]:
190
+ n = t.as_independent(x)[1]
191
+ for i, term in enumerate(ind):
192
+ d = term.as_independent(x)[1]
193
+ q = (n / d).cancel()
194
+ if q.is_rational_function(x):
195
+ ind[i] += t
196
+ break
197
+ else:
198
+ ind.append(t)
199
+ return ind
200
+
201
+
202
+ def simpleDE(f, x, g, order=4):
203
+ r"""
204
+ Generates simple DE.
205
+
206
+ Explanation
207
+ ===========
208
+
209
+ DE is of the form
210
+
211
+ .. math::
212
+ f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0
213
+
214
+ where :math:`A_j` should be rational function in x.
215
+
216
+ Generates DE's upto order 4 (default). DE's can also have free parameters.
217
+
218
+ By increasing order, higher order DE's can be found.
219
+
220
+ Yields a tuple of (DE, order).
221
+ """
222
+ from sympy.solvers.solveset import linsolve
223
+
224
+ a = symbols('a:%d' % (order))
225
+
226
+ def _makeDE(k):
227
+ eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)])
228
+ DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)])
229
+ return eq, DE
230
+
231
+ found = False
232
+ for k in range(1, order + 1):
233
+ eq, DE = _makeDE(k)
234
+ eq = eq.expand()
235
+ terms = eq.as_ordered_terms()
236
+ ind = rational_independent(terms, x)
237
+ if found or len(ind) == k:
238
+ sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s)))
239
+ if sol:
240
+ found = True
241
+ DE = DE.subs(sol)
242
+ DE = DE.as_numer_denom()[0]
243
+ DE = DE.factor().as_coeff_mul(Derivative)[1][0]
244
+ yield DE.collect(Derivative(g(x))), k
245
+
246
+
247
+ def exp_re(DE, r, k):
248
+ """Converts a DE with constant coefficients (explike) into a RE.
249
+
250
+ Explanation
251
+ ===========
252
+
253
+ Performs the substitution:
254
+
255
+ .. math::
256
+ f^j(x) \\to r(k + j)
257
+
258
+ Normalises the terms so that lowest order of a term is always r(k).
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy import Function, Derivative
264
+ >>> from sympy.series.formal import exp_re
265
+ >>> from sympy.abc import x, k
266
+ >>> f, r = Function('f'), Function('r')
267
+
268
+ >>> exp_re(-f(x) + Derivative(f(x)), r, k)
269
+ -r(k) + r(k + 1)
270
+ >>> exp_re(Derivative(f(x), x) + Derivative(f(x), (x, 2)), r, k)
271
+ r(k) + r(k + 1)
272
+
273
+ See Also
274
+ ========
275
+
276
+ sympy.series.formal.hyper_re
277
+ """
278
+ RE = S.Zero
279
+
280
+ g = DE.atoms(Function).pop()
281
+
282
+ mini = None
283
+ for t in Add.make_args(DE):
284
+ coeff, d = t.as_independent(g)
285
+ if isinstance(d, Derivative):
286
+ j = d.derivative_count
287
+ else:
288
+ j = 0
289
+ if mini is None or j < mini:
290
+ mini = j
291
+ RE += coeff * r(k + j)
292
+ if mini:
293
+ RE = RE.subs(k, k - mini)
294
+ return RE
295
+
296
+
297
+ def hyper_re(DE, r, k):
298
+ """
299
+ Converts a DE into a RE.
300
+
301
+ Explanation
302
+ ===========
303
+
304
+ Performs the substitution:
305
+
306
+ .. math::
307
+ x^l f^j(x) \\to (k + 1 - l)_j . a_{k + j - l}
308
+
309
+ Normalises the terms so that lowest order of a term is always r(k).
310
+
311
+ Examples
312
+ ========
313
+
314
+ >>> from sympy import Function, Derivative
315
+ >>> from sympy.series.formal import hyper_re
316
+ >>> from sympy.abc import x, k
317
+ >>> f, r = Function('f'), Function('r')
318
+
319
+ >>> hyper_re(-f(x) + Derivative(f(x)), r, k)
320
+ (k + 1)*r(k + 1) - r(k)
321
+ >>> hyper_re(-x*f(x) + Derivative(f(x), (x, 2)), r, k)
322
+ (k + 2)*(k + 3)*r(k + 3) - r(k)
323
+
324
+ See Also
325
+ ========
326
+
327
+ sympy.series.formal.exp_re
328
+ """
329
+ RE = S.Zero
330
+
331
+ g = DE.atoms(Function).pop()
332
+ x = g.atoms(Symbol).pop()
333
+
334
+ mini = None
335
+ for t in Add.make_args(DE.expand()):
336
+ coeff, d = t.as_independent(g)
337
+ c, v = coeff.as_independent(x)
338
+ l = v.as_coeff_exponent(x)[1]
339
+ if isinstance(d, Derivative):
340
+ j = d.derivative_count
341
+ else:
342
+ j = 0
343
+ RE += c * rf(k + 1 - l, j) * r(k + j - l)
344
+ if mini is None or j - l < mini:
345
+ mini = j - l
346
+
347
+ RE = RE.subs(k, k - mini)
348
+
349
+ m = Wild('m')
350
+ return RE.collect(r(k + m))
351
+
352
+
353
+ def _transformation_a(f, x, P, Q, k, m, shift):
354
+ f *= x**(-shift)
355
+ P = P.subs(k, k + shift)
356
+ Q = Q.subs(k, k + shift)
357
+ return f, P, Q, m
358
+
359
+
360
+ def _transformation_c(f, x, P, Q, k, m, scale):
361
+ f = f.subs(x, x**scale)
362
+ P = P.subs(k, k / scale)
363
+ Q = Q.subs(k, k / scale)
364
+ m *= scale
365
+ return f, P, Q, m
366
+
367
+
368
+ def _transformation_e(f, x, P, Q, k, m):
369
+ f = f.diff(x)
370
+ P = P.subs(k, k + 1) * (k + m + 1)
371
+ Q = Q.subs(k, k + 1) * (k + 1)
372
+ return f, P, Q, m
373
+
374
+
375
+ def _apply_shift(sol, shift):
376
+ return [(res, cond + shift) for res, cond in sol]
377
+
378
+
379
+ def _apply_scale(sol, scale):
380
+ return [(res, cond / scale) for res, cond in sol]
381
+
382
+
383
+ def _apply_integrate(sol, x, k):
384
+ return [(res / ((cond + 1)*(cond.as_coeff_Add()[1].coeff(k))), cond + 1)
385
+ for res, cond in sol]
386
+
387
+
388
+ def _compute_formula(f, x, P, Q, k, m, k_max):
389
+ """Computes the formula for f."""
390
+ from sympy.polys import roots
391
+
392
+ sol = []
393
+ for i in range(k_max + 1, k_max + m + 1):
394
+ if (i < 0) == True:
395
+ continue
396
+ r = f.diff(x, i).limit(x, 0) / factorial(i)
397
+ if r.is_zero:
398
+ continue
399
+
400
+ kterm = m*k + i
401
+ res = r
402
+
403
+ p = P.subs(k, kterm)
404
+ q = Q.subs(k, kterm)
405
+ c1 = p.subs(k, 1/k).leadterm(k)[0]
406
+ c2 = q.subs(k, 1/k).leadterm(k)[0]
407
+ res *= (-c1 / c2)**k
408
+
409
+ res *= Mul(*[rf(-r, k)**mul for r, mul in roots(p, k).items()])
410
+ res /= Mul(*[rf(-r, k)**mul for r, mul in roots(q, k).items()])
411
+
412
+ sol.append((res, kterm))
413
+
414
+ return sol
415
+
416
+
417
+ def _rsolve_hypergeometric(f, x, P, Q, k, m):
418
+ """
419
+ Recursive wrapper to rsolve_hypergeometric.
420
+
421
+ Explanation
422
+ ===========
423
+
424
+ Returns a Tuple of (formula, series independent terms,
425
+ maximum power of x in independent terms) if successful
426
+ otherwise ``None``.
427
+
428
+ See :func:`rsolve_hypergeometric` for details.
429
+ """
430
+ from sympy.polys import lcm, roots
431
+ from sympy.integrals import integrate
432
+
433
+ # transformation - c
434
+ proots, qroots = roots(P, k), roots(Q, k)
435
+ all_roots = dict(proots)
436
+ all_roots.update(qroots)
437
+ scale = lcm([r.as_numer_denom()[1] for r, t in all_roots.items()
438
+ if r.is_rational])
439
+ f, P, Q, m = _transformation_c(f, x, P, Q, k, m, scale)
440
+
441
+ # transformation - a
442
+ qroots = roots(Q, k)
443
+ if qroots:
444
+ k_min = Min(*qroots.keys())
445
+ else:
446
+ k_min = S.Zero
447
+ shift = k_min + m
448
+ f, P, Q, m = _transformation_a(f, x, P, Q, k, m, shift)
449
+
450
+ l = (x*f).limit(x, 0)
451
+ if not isinstance(l, Limit) and l != 0: # Ideally should only be l != 0
452
+ return None
453
+
454
+ qroots = roots(Q, k)
455
+ if qroots:
456
+ k_max = Max(*qroots.keys())
457
+ else:
458
+ k_max = S.Zero
459
+
460
+ ind, mp = S.Zero, -oo
461
+ for i in range(k_max + m + 1):
462
+ r = f.diff(x, i).limit(x, 0) / factorial(i)
463
+ if r.is_finite is False:
464
+ old_f = f
465
+ f, P, Q, m = _transformation_a(f, x, P, Q, k, m, i)
466
+ f, P, Q, m = _transformation_e(f, x, P, Q, k, m)
467
+ sol, ind, mp = _rsolve_hypergeometric(f, x, P, Q, k, m)
468
+ sol = _apply_integrate(sol, x, k)
469
+ sol = _apply_shift(sol, i)
470
+ ind = integrate(ind, x)
471
+ ind += (old_f - ind).limit(x, 0) # constant of integration
472
+ mp += 1
473
+ return sol, ind, mp
474
+ elif r:
475
+ ind += r*x**(i + shift)
476
+ pow_x = Rational((i + shift), scale)
477
+ if pow_x > mp:
478
+ mp = pow_x # maximum power of x
479
+ ind = ind.subs(x, x**(1/scale))
480
+
481
+ sol = _compute_formula(f, x, P, Q, k, m, k_max)
482
+ sol = _apply_shift(sol, shift)
483
+ sol = _apply_scale(sol, scale)
484
+
485
+ return sol, ind, mp
486
+
487
+
488
+ def rsolve_hypergeometric(f, x, P, Q, k, m):
489
+ """
490
+ Solves RE of hypergeometric type.
491
+
492
+ Explanation
493
+ ===========
494
+
495
+ Attempts to solve RE of the form
496
+
497
+ Q(k)*a(k + m) - P(k)*a(k)
498
+
499
+ Transformations that preserve Hypergeometric type:
500
+
501
+ a. x**n*f(x): b(k + m) = R(k - n)*b(k)
502
+ b. f(A*x): b(k + m) = A**m*R(k)*b(k)
503
+ c. f(x**n): b(k + n*m) = R(k/n)*b(k)
504
+ d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k)
505
+ e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k)
506
+
507
+ Some of these transformations have been used to solve the RE.
508
+
509
+ Returns
510
+ =======
511
+
512
+ formula : Expr
513
+ ind : Expr
514
+ Independent terms.
515
+ order : int
516
+
517
+ Examples
518
+ ========
519
+
520
+ >>> from sympy import exp, ln, S
521
+ >>> from sympy.series.formal import rsolve_hypergeometric as rh
522
+ >>> from sympy.abc import x, k
523
+
524
+ >>> rh(exp(x), x, -S.One, (k + 1), k, 1)
525
+ (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
526
+
527
+ >>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1)
528
+ (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
529
+ Eq(Mod(k, 1), 0)), (0, True)), x, 2)
530
+
531
+ References
532
+ ==========
533
+
534
+ .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
535
+ .. [2] Power Series in Computer Algebra - Wolfram Koepf
536
+ """
537
+ result = _rsolve_hypergeometric(f, x, P, Q, k, m)
538
+
539
+ if result is None:
540
+ return None
541
+
542
+ sol_list, ind, mp = result
543
+
544
+ sol_dict = defaultdict(lambda: S.Zero)
545
+ for res, cond in sol_list:
546
+ j, mk = cond.as_coeff_Add()
547
+ c = mk.coeff(k)
548
+
549
+ if j.is_integer is False:
550
+ res *= x**frac(j)
551
+ j = floor(j)
552
+
553
+ res = res.subs(k, (k - j) / c)
554
+ cond = Eq(k % c, j % c)
555
+ sol_dict[cond] += res # Group together formula for same conditions
556
+
557
+ sol = []
558
+ for cond, res in sol_dict.items():
559
+ sol.append((res, cond))
560
+ sol.append((S.Zero, True))
561
+ sol = Piecewise(*sol)
562
+
563
+ if mp is -oo:
564
+ s = S.Zero
565
+ elif mp.is_integer is False:
566
+ s = ceiling(mp)
567
+ else:
568
+ s = mp + 1
569
+
570
+ # save all the terms of
571
+ # form 1/x**k in ind
572
+ if s < 0:
573
+ ind += sum(sequence(sol * x**k, (k, s, -1)))
574
+ s = S.Zero
575
+
576
+ return (sol, ind, s)
577
+
578
+
579
+ def _solve_hyper_RE(f, x, RE, g, k):
580
+ """See docstring of :func:`rsolve_hypergeometric` for details."""
581
+ terms = Add.make_args(RE)
582
+
583
+ if len(terms) == 2:
584
+ gs = list(RE.atoms(Function))
585
+ P, Q = map(RE.coeff, gs)
586
+ m = gs[1].args[0] - gs[0].args[0]
587
+ if m < 0:
588
+ P, Q = Q, P
589
+ m = abs(m)
590
+ return rsolve_hypergeometric(f, x, P, Q, k, m)
591
+
592
+
593
+ def _solve_explike_DE(f, x, DE, g, k):
594
+ """Solves DE with constant coefficients."""
595
+ from sympy.solvers import rsolve
596
+
597
+ for t in Add.make_args(DE):
598
+ coeff, d = t.as_independent(g)
599
+ if coeff.free_symbols:
600
+ return
601
+
602
+ RE = exp_re(DE, g, k)
603
+
604
+ init = {}
605
+ for i in range(len(Add.make_args(RE))):
606
+ if i:
607
+ f = f.diff(x)
608
+ init[g(k).subs(k, i)] = f.limit(x, 0)
609
+
610
+ sol = rsolve(RE, g(k), init)
611
+
612
+ if sol:
613
+ return (sol / factorial(k), S.Zero, S.Zero)
614
+
615
+
616
+ def _solve_simple(f, x, DE, g, k):
617
+ """Converts DE into RE and solves using :func:`rsolve`."""
618
+ from sympy.solvers import rsolve
619
+
620
+ RE = hyper_re(DE, g, k)
621
+
622
+ init = {}
623
+ for i in range(len(Add.make_args(RE))):
624
+ if i:
625
+ f = f.diff(x)
626
+ init[g(k).subs(k, i)] = f.limit(x, 0) / factorial(i)
627
+
628
+ sol = rsolve(RE, g(k), init)
629
+
630
+ if sol:
631
+ return (sol, S.Zero, S.Zero)
632
+
633
+
634
+ def _transform_explike_DE(DE, g, x, order, syms):
635
+ """Converts DE with free parameters into DE with constant coefficients."""
636
+ from sympy.solvers.solveset import linsolve
637
+
638
+ eq = []
639
+ highest_coeff = DE.coeff(Derivative(g(x), x, order))
640
+ for i in range(order):
641
+ coeff = DE.coeff(Derivative(g(x), x, i))
642
+ coeff = (coeff / highest_coeff).expand().collect(x)
643
+ for t in Add.make_args(coeff):
644
+ eq.append(t)
645
+ temp = []
646
+ for e in eq:
647
+ if e.has(x):
648
+ break
649
+ elif e.has(Symbol):
650
+ temp.append(e)
651
+ else:
652
+ eq = temp
653
+ if eq:
654
+ sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
655
+ if sol:
656
+ DE = DE.subs(sol)
657
+ DE = DE.factor().as_coeff_mul(Derivative)[1][0]
658
+ DE = DE.collect(Derivative(g(x)))
659
+ return DE
660
+
661
+
662
+ def _transform_DE_RE(DE, g, k, order, syms):
663
+ """Converts DE with free parameters into RE of hypergeometric type."""
664
+ from sympy.solvers.solveset import linsolve
665
+
666
+ RE = hyper_re(DE, g, k)
667
+
668
+ eq = []
669
+ for i in range(1, order):
670
+ coeff = RE.coeff(g(k + i))
671
+ eq.append(coeff)
672
+ sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
673
+ if sol:
674
+ m = Wild('m')
675
+ RE = RE.subs(sol)
676
+ RE = RE.factor().as_numer_denom()[0].collect(g(k + m))
677
+ RE = RE.as_coeff_mul(g)[1][0]
678
+ for i in range(order): # smallest order should be g(k)
679
+ if RE.coeff(g(k + i)) and i:
680
+ RE = RE.subs(k, k - i)
681
+ break
682
+ return RE
683
+
684
+
685
+ def solve_de(f, x, DE, order, g, k):
686
+ """
687
+ Solves the DE.
688
+
689
+ Explanation
690
+ ===========
691
+
692
+ Tries to solve DE by either converting into a RE containing two terms or
693
+ converting into a DE having constant coefficients.
694
+
695
+ Returns
696
+ =======
697
+
698
+ formula : Expr
699
+ ind : Expr
700
+ Independent terms.
701
+ order : int
702
+
703
+ Examples
704
+ ========
705
+
706
+ >>> from sympy import Derivative as D, Function
707
+ >>> from sympy import exp, ln
708
+ >>> from sympy.series.formal import solve_de
709
+ >>> from sympy.abc import x, k
710
+ >>> f = Function('f')
711
+
712
+ >>> solve_de(exp(x), x, D(f(x), x) - f(x), 1, f, k)
713
+ (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
714
+
715
+ >>> solve_de(ln(1 + x), x, (x + 1)*D(f(x), x, 2) + D(f(x)), 2, f, k)
716
+ (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
717
+ Eq(Mod(k, 1), 0)), (0, True)), x, 2)
718
+ """
719
+ sol = None
720
+ syms = DE.free_symbols.difference({g, x})
721
+
722
+ if syms:
723
+ RE = _transform_DE_RE(DE, g, k, order, syms)
724
+ else:
725
+ RE = hyper_re(DE, g, k)
726
+ if not RE.free_symbols.difference({k}):
727
+ sol = _solve_hyper_RE(f, x, RE, g, k)
728
+
729
+ if sol:
730
+ return sol
731
+
732
+ if syms:
733
+ DE = _transform_explike_DE(DE, g, x, order, syms)
734
+ if not DE.free_symbols.difference({x}):
735
+ sol = _solve_explike_DE(f, x, DE, g, k)
736
+
737
+ if sol:
738
+ return sol
739
+
740
+
741
+ def hyper_algorithm(f, x, k, order=4):
742
+ """
743
+ Hypergeometric algorithm for computing Formal Power Series.
744
+
745
+ Explanation
746
+ ===========
747
+
748
+ Steps:
749
+ * Generates DE
750
+ * Convert the DE into RE
751
+ * Solves the RE
752
+
753
+ Examples
754
+ ========
755
+
756
+ >>> from sympy import exp, ln
757
+ >>> from sympy.series.formal import hyper_algorithm
758
+
759
+ >>> from sympy.abc import x, k
760
+
761
+ >>> hyper_algorithm(exp(x), x, k)
762
+ (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
763
+
764
+ >>> hyper_algorithm(ln(1 + x), x, k)
765
+ (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
766
+ Eq(Mod(k, 1), 0)), (0, True)), x, 2)
767
+
768
+ See Also
769
+ ========
770
+
771
+ sympy.series.formal.simpleDE
772
+ sympy.series.formal.solve_de
773
+ """
774
+ g = Function('g')
775
+
776
+ des = [] # list of DE's
777
+ sol = None
778
+ for DE, i in simpleDE(f, x, g, order):
779
+ if DE is not None:
780
+ sol = solve_de(f, x, DE, i, g, k)
781
+ if sol:
782
+ return sol
783
+ if not DE.free_symbols.difference({x}):
784
+ des.append(DE)
785
+
786
+ # If nothing works
787
+ # Try plain rsolve
788
+ for DE in des:
789
+ sol = _solve_simple(f, x, DE, g, k)
790
+ if sol:
791
+ return sol
792
+
793
+
794
+ def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
795
+ """Recursive wrapper to compute fps.
796
+
797
+ See :func:`compute_fps` for details.
798
+ """
799
+ if x0 in [S.Infinity, S.NegativeInfinity]:
800
+ dir = S.One if x0 is S.Infinity else -S.One
801
+ temp = f.subs(x, 1/x)
802
+ result = _compute_fps(temp, x, 0, dir, hyper, order, rational, full)
803
+ if result is None:
804
+ return None
805
+ return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x))
806
+ elif x0 or dir == -S.One:
807
+ if dir == -S.One:
808
+ rep = -x + x0
809
+ rep2 = -x
810
+ rep2b = x0
811
+ else:
812
+ rep = x + x0
813
+ rep2 = x
814
+ rep2b = -x0
815
+ temp = f.subs(x, rep)
816
+ result = _compute_fps(temp, x, 0, S.One, hyper, order, rational, full)
817
+ if result is None:
818
+ return None
819
+ return (result[0], result[1].subs(x, rep2 + rep2b),
820
+ result[2].subs(x, rep2 + rep2b))
821
+
822
+ if f.is_polynomial(x):
823
+ k = Dummy('k')
824
+ ak = sequence(Coeff(f, x, k), (k, 1, oo))
825
+ xk = sequence(x**k, (k, 0, oo))
826
+ ind = f.coeff(x, 0)
827
+ return ak, xk, ind
828
+
829
+ # Break instances of Add
830
+ # this allows application of different
831
+ # algorithms on different terms increasing the
832
+ # range of admissible functions.
833
+ if isinstance(f, Add):
834
+ result = False
835
+ ak = sequence(S.Zero, (0, oo))
836
+ ind, xk = S.Zero, None
837
+ for t in Add.make_args(f):
838
+ res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full)
839
+ if res:
840
+ if not result:
841
+ result = True
842
+ xk = res[1]
843
+ if res[0].start > ak.start:
844
+ seq = ak
845
+ s, f = ak.start, res[0].start
846
+ else:
847
+ seq = res[0]
848
+ s, f = res[0].start, ak.start
849
+ save = Add(*[z[0]*z[1] for z in zip(seq[0:(f - s)], xk[s:f])])
850
+ ak += res[0]
851
+ ind += res[2] + save
852
+ else:
853
+ ind += t
854
+ if result:
855
+ return ak, xk, ind
856
+ return None
857
+
858
+ # The symbolic term - symb, if present, is being separated from the function
859
+ # Otherwise symb is being set to S.One
860
+ syms = f.free_symbols.difference({x})
861
+ (f, symb) = expand(f).as_independent(*syms)
862
+
863
+ result = None
864
+
865
+ # from here on it's x0=0 and dir=1 handling
866
+ k = Dummy('k')
867
+ if rational:
868
+ result = rational_algorithm(f, x, k, order, full)
869
+
870
+ if result is None and hyper:
871
+ result = hyper_algorithm(f, x, k, order)
872
+
873
+ if result is None:
874
+ return None
875
+
876
+ from sympy.simplify.powsimp import powsimp
877
+ if symb.is_zero:
878
+ symb = S.One
879
+ else:
880
+ symb = powsimp(symb)
881
+ ak = sequence(result[0], (k, result[2], oo))
882
+ xk_formula = powsimp(x**k * symb)
883
+ xk = sequence(xk_formula, (k, 0, oo))
884
+ ind = powsimp(result[1] * symb)
885
+
886
+ return ak, xk, ind
887
+
888
+
889
+ def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True,
890
+ full=False):
891
+ """
892
+ Computes the formula for Formal Power Series of a function.
893
+
894
+ Explanation
895
+ ===========
896
+
897
+ Tries to compute the formula by applying the following techniques
898
+ (in order):
899
+
900
+ * rational_algorithm
901
+ * Hypergeometric algorithm
902
+
903
+ Parameters
904
+ ==========
905
+
906
+ x : Symbol
907
+ x0 : number, optional
908
+ Point to perform series expansion about. Default is 0.
909
+ dir : {1, -1, '+', '-'}, optional
910
+ If dir is 1 or '+' the series is calculated from the right and
911
+ for -1 or '-' the series is calculated from the left. For smooth
912
+ functions this flag will not alter the results. Default is 1.
913
+ hyper : {True, False}, optional
914
+ Set hyper to False to skip the hypergeometric algorithm.
915
+ By default it is set to False.
916
+ order : int, optional
917
+ Order of the derivative of ``f``, Default is 4.
918
+ rational : {True, False}, optional
919
+ Set rational to False to skip rational algorithm. By default it is set
920
+ to True.
921
+ full : {True, False}, optional
922
+ Set full to True to increase the range of rational algorithm.
923
+ See :func:`rational_algorithm` for details. By default it is set to
924
+ False.
925
+
926
+ Returns
927
+ =======
928
+
929
+ ak : sequence
930
+ Sequence of coefficients.
931
+ xk : sequence
932
+ Sequence of powers of x.
933
+ ind : Expr
934
+ Independent terms.
935
+ mul : Pow
936
+ Common terms.
937
+
938
+ See Also
939
+ ========
940
+
941
+ sympy.series.formal.rational_algorithm
942
+ sympy.series.formal.hyper_algorithm
943
+ """
944
+ f = sympify(f)
945
+ x = sympify(x)
946
+
947
+ if not f.has(x):
948
+ return None
949
+
950
+ x0 = sympify(x0)
951
+
952
+ if dir == '+':
953
+ dir = S.One
954
+ elif dir == '-':
955
+ dir = -S.One
956
+ elif dir not in [S.One, -S.One]:
957
+ raise ValueError("Dir must be '+' or '-'")
958
+ else:
959
+ dir = sympify(dir)
960
+
961
+ return _compute_fps(f, x, x0, dir, hyper, order, rational, full)
962
+
963
+
964
+ class Coeff(Function):
965
+ """
966
+ Coeff(p, x, n) represents the nth coefficient of the polynomial p in x
967
+ """
968
+ @classmethod
969
+ def eval(cls, p, x, n):
970
+ if p.is_polynomial(x) and n.is_integer:
971
+ return p.coeff(x, n)
972
+
973
+
974
+ class FormalPowerSeries(SeriesBase):
975
+ """
976
+ Represents Formal Power Series of a function.
977
+
978
+ Explanation
979
+ ===========
980
+
981
+ No computation is performed. This class should only to be used to represent
982
+ a series. No checks are performed.
983
+
984
+ For computing a series use :func:`fps`.
985
+
986
+ See Also
987
+ ========
988
+
989
+ sympy.series.formal.fps
990
+ """
991
+ def __new__(cls, *args):
992
+ args = map(sympify, args)
993
+ return Expr.__new__(cls, *args)
994
+
995
+ def __init__(self, *args):
996
+ ak = args[4][0]
997
+ k = ak.variables[0]
998
+ self.ak_seq = sequence(ak.formula, (k, 1, oo))
999
+ self.fact_seq = sequence(factorial(k), (k, 1, oo))
1000
+ self.bell_coeff_seq = self.ak_seq * self.fact_seq
1001
+ self.sign_seq = sequence((-1, 1), (k, 1, oo))
1002
+
1003
+ @property
1004
+ def function(self):
1005
+ return self.args[0]
1006
+
1007
+ @property
1008
+ def x(self):
1009
+ return self.args[1]
1010
+
1011
+ @property
1012
+ def x0(self):
1013
+ return self.args[2]
1014
+
1015
+ @property
1016
+ def dir(self):
1017
+ return self.args[3]
1018
+
1019
+ @property
1020
+ def ak(self):
1021
+ return self.args[4][0]
1022
+
1023
+ @property
1024
+ def xk(self):
1025
+ return self.args[4][1]
1026
+
1027
+ @property
1028
+ def ind(self):
1029
+ return self.args[4][2]
1030
+
1031
+ @property
1032
+ def interval(self):
1033
+ return Interval(0, oo)
1034
+
1035
+ @property
1036
+ def start(self):
1037
+ return self.interval.inf
1038
+
1039
+ @property
1040
+ def stop(self):
1041
+ return self.interval.sup
1042
+
1043
+ @property
1044
+ def length(self):
1045
+ return oo
1046
+
1047
+ @property
1048
+ def infinite(self):
1049
+ """Returns an infinite representation of the series"""
1050
+ from sympy.concrete import Sum
1051
+ ak, xk = self.ak, self.xk
1052
+ k = ak.variables[0]
1053
+ inf_sum = Sum(ak.formula * xk.formula, (k, ak.start, ak.stop))
1054
+
1055
+ return self.ind + inf_sum
1056
+
1057
+ def _get_pow_x(self, term):
1058
+ """Returns the power of x in a term."""
1059
+ xterm, pow_x = term.as_independent(self.x)[1].as_base_exp()
1060
+ if not xterm.has(self.x):
1061
+ return S.Zero
1062
+ return pow_x
1063
+
1064
+ def polynomial(self, n=6):
1065
+ """
1066
+ Truncated series as polynomial.
1067
+
1068
+ Explanation
1069
+ ===========
1070
+
1071
+ Returns series expansion of ``f`` upto order ``O(x**n)``
1072
+ as a polynomial(without ``O`` term).
1073
+ """
1074
+ terms = []
1075
+ sym = self.free_symbols
1076
+ for i, t in enumerate(self):
1077
+ xp = self._get_pow_x(t)
1078
+ if xp.has(*sym):
1079
+ xp = xp.as_coeff_add(*sym)[0]
1080
+ if xp >= n:
1081
+ break
1082
+ elif xp.is_integer is True and i == n + 1:
1083
+ break
1084
+ elif t is not S.Zero:
1085
+ terms.append(t)
1086
+
1087
+ return Add(*terms)
1088
+
1089
+ def truncate(self, n=6):
1090
+ """
1091
+ Truncated series.
1092
+
1093
+ Explanation
1094
+ ===========
1095
+
1096
+ Returns truncated series expansion of f upto
1097
+ order ``O(x**n)``.
1098
+
1099
+ If n is ``None``, returns an infinite iterator.
1100
+ """
1101
+ if n is None:
1102
+ return iter(self)
1103
+
1104
+ x, x0 = self.x, self.x0
1105
+ pt_xk = self.xk.coeff(n)
1106
+ if x0 is S.NegativeInfinity:
1107
+ x0 = S.Infinity
1108
+
1109
+ return self.polynomial(n) + Order(pt_xk, (x, x0))
1110
+
1111
+ def zero_coeff(self):
1112
+ return self._eval_term(0)
1113
+
1114
+ def _eval_term(self, pt):
1115
+ try:
1116
+ pt_xk = self.xk.coeff(pt)
1117
+ pt_ak = self.ak.coeff(pt).simplify() # Simplify the coefficients
1118
+ except IndexError:
1119
+ term = S.Zero
1120
+ else:
1121
+ term = (pt_ak * pt_xk)
1122
+
1123
+ if self.ind:
1124
+ ind = S.Zero
1125
+ sym = self.free_symbols
1126
+ for t in Add.make_args(self.ind):
1127
+ pow_x = self._get_pow_x(t)
1128
+ if pow_x.has(*sym):
1129
+ pow_x = pow_x.as_coeff_add(*sym)[0]
1130
+ if pt == 0 and pow_x < 1:
1131
+ ind += t
1132
+ elif pow_x >= pt and pow_x < pt + 1:
1133
+ ind += t
1134
+ term += ind
1135
+
1136
+ return term.collect(self.x)
1137
+
1138
+ def _eval_subs(self, old, new):
1139
+ x = self.x
1140
+ if old.has(x):
1141
+ return self
1142
+
1143
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1144
+ for t in self:
1145
+ if t is not S.Zero:
1146
+ return t
1147
+
1148
+ def _eval_derivative(self, x):
1149
+ f = self.function.diff(x)
1150
+ ind = self.ind.diff(x)
1151
+
1152
+ pow_xk = self._get_pow_x(self.xk.formula)
1153
+ ak = self.ak
1154
+ k = ak.variables[0]
1155
+ if ak.formula.has(x):
1156
+ form = []
1157
+ for e, c in ak.formula.args:
1158
+ temp = S.Zero
1159
+ for t in Add.make_args(e):
1160
+ pow_x = self._get_pow_x(t)
1161
+ temp += t * (pow_xk + pow_x)
1162
+ form.append((temp, c))
1163
+ form = Piecewise(*form)
1164
+ ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop))
1165
+ else:
1166
+ ak = sequence((ak.formula * pow_xk).subs(k, k + 1),
1167
+ (k, ak.start - 1, ak.stop))
1168
+
1169
+ return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
1170
+
1171
+ def integrate(self, x=None, **kwargs):
1172
+ """
1173
+ Integrate Formal Power Series.
1174
+
1175
+ Examples
1176
+ ========
1177
+
1178
+ >>> from sympy import fps, sin, integrate
1179
+ >>> from sympy.abc import x
1180
+ >>> f = fps(sin(x))
1181
+ >>> f.integrate(x).truncate()
1182
+ -1 + x**2/2 - x**4/24 + O(x**6)
1183
+ >>> integrate(f, (x, 0, 1))
1184
+ 1 - cos(1)
1185
+ """
1186
+ from sympy.integrals import integrate
1187
+
1188
+ if x is None:
1189
+ x = self.x
1190
+ elif iterable(x):
1191
+ return integrate(self.function, x)
1192
+
1193
+ f = integrate(self.function, x)
1194
+ ind = integrate(self.ind, x)
1195
+ ind += (f - ind).limit(x, 0) # constant of integration
1196
+
1197
+ pow_xk = self._get_pow_x(self.xk.formula)
1198
+ ak = self.ak
1199
+ k = ak.variables[0]
1200
+ if ak.formula.has(x):
1201
+ form = []
1202
+ for e, c in ak.formula.args:
1203
+ temp = S.Zero
1204
+ for t in Add.make_args(e):
1205
+ pow_x = self._get_pow_x(t)
1206
+ temp += t / (pow_xk + pow_x + 1)
1207
+ form.append((temp, c))
1208
+ form = Piecewise(*form)
1209
+ ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop))
1210
+ else:
1211
+ ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1),
1212
+ (k, ak.start + 1, ak.stop))
1213
+
1214
+ return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
1215
+
1216
+ def product(self, other, x=None, n=6):
1217
+ """
1218
+ Multiplies two Formal Power Series, using discrete convolution and
1219
+ return the truncated terms upto specified order.
1220
+
1221
+ Parameters
1222
+ ==========
1223
+
1224
+ n : Number, optional
1225
+ Specifies the order of the term up to which the polynomial should
1226
+ be truncated.
1227
+
1228
+ Examples
1229
+ ========
1230
+
1231
+ >>> from sympy import fps, sin, exp
1232
+ >>> from sympy.abc import x
1233
+ >>> f1 = fps(sin(x))
1234
+ >>> f2 = fps(exp(x))
1235
+
1236
+ >>> f1.product(f2, x).truncate(4)
1237
+ x + x**2 + x**3/3 + O(x**4)
1238
+
1239
+ See Also
1240
+ ========
1241
+
1242
+ sympy.discrete.convolutions
1243
+ sympy.series.formal.FormalPowerSeriesProduct
1244
+
1245
+ """
1246
+
1247
+ if n is None:
1248
+ return iter(self)
1249
+
1250
+ other = sympify(other)
1251
+
1252
+ if not isinstance(other, FormalPowerSeries):
1253
+ raise ValueError("Both series should be an instance of FormalPowerSeries"
1254
+ " class.")
1255
+
1256
+ if self.dir != other.dir:
1257
+ raise ValueError("Both series should be calculated from the"
1258
+ " same direction.")
1259
+ elif self.x0 != other.x0:
1260
+ raise ValueError("Both series should be calculated about the"
1261
+ " same point.")
1262
+
1263
+ elif self.x != other.x:
1264
+ raise ValueError("Both series should have the same symbol.")
1265
+
1266
+ return FormalPowerSeriesProduct(self, other)
1267
+
1268
+ def coeff_bell(self, n):
1269
+ r"""
1270
+ self.coeff_bell(n) returns a sequence of Bell polynomials of the second kind.
1271
+ Note that ``n`` should be a integer.
1272
+
1273
+ The second kind of Bell polynomials (are sometimes called "partial" Bell
1274
+ polynomials or incomplete Bell polynomials) are defined as
1275
+
1276
+ .. math::
1277
+ B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
1278
+ \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
1279
+ \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
1280
+ \left(\frac{x_1}{1!} \right)^{j_1}
1281
+ \left(\frac{x_2}{2!} \right)^{j_2} \dotsb
1282
+ \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
1283
+
1284
+ * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
1285
+ `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
1286
+
1287
+ See Also
1288
+ ========
1289
+
1290
+ sympy.functions.combinatorial.numbers.bell
1291
+
1292
+ """
1293
+
1294
+ inner_coeffs = [bell(n, j, tuple(self.bell_coeff_seq[:n-j+1])) for j in range(1, n+1)]
1295
+
1296
+ k = Dummy('k')
1297
+ return sequence(tuple(inner_coeffs), (k, 1, oo))
1298
+
1299
+ def compose(self, other, x=None, n=6):
1300
+ r"""
1301
+ Returns the truncated terms of the formal power series of the composed function,
1302
+ up to specified ``n``.
1303
+
1304
+ Explanation
1305
+ ===========
1306
+
1307
+ If ``f`` and ``g`` are two formal power series of two different functions,
1308
+ then the coefficient sequence ``ak`` of the composed formal power series `fp`
1309
+ will be as follows.
1310
+
1311
+ .. math::
1312
+ \sum\limits_{k=0}^{n} b_k B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
1313
+
1314
+ Parameters
1315
+ ==========
1316
+
1317
+ n : Number, optional
1318
+ Specifies the order of the term up to which the polynomial should
1319
+ be truncated.
1320
+
1321
+ Examples
1322
+ ========
1323
+
1324
+ >>> from sympy import fps, sin, exp
1325
+ >>> from sympy.abc import x
1326
+ >>> f1 = fps(exp(x))
1327
+ >>> f2 = fps(sin(x))
1328
+
1329
+ >>> f1.compose(f2, x).truncate()
1330
+ 1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
1331
+
1332
+ >>> f1.compose(f2, x).truncate(8)
1333
+ 1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8)
1334
+
1335
+ See Also
1336
+ ========
1337
+
1338
+ sympy.functions.combinatorial.numbers.bell
1339
+ sympy.series.formal.FormalPowerSeriesCompose
1340
+
1341
+ References
1342
+ ==========
1343
+
1344
+ .. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
1345
+
1346
+ """
1347
+
1348
+ if n is None:
1349
+ return iter(self)
1350
+
1351
+ other = sympify(other)
1352
+
1353
+ if not isinstance(other, FormalPowerSeries):
1354
+ raise ValueError("Both series should be an instance of FormalPowerSeries"
1355
+ " class.")
1356
+
1357
+ if self.dir != other.dir:
1358
+ raise ValueError("Both series should be calculated from the"
1359
+ " same direction.")
1360
+ elif self.x0 != other.x0:
1361
+ raise ValueError("Both series should be calculated about the"
1362
+ " same point.")
1363
+
1364
+ elif self.x != other.x:
1365
+ raise ValueError("Both series should have the same symbol.")
1366
+
1367
+ if other._eval_term(0).as_coeff_mul(other.x)[0] is not S.Zero:
1368
+ raise ValueError("The formal power series of the inner function should not have any "
1369
+ "constant coefficient term.")
1370
+
1371
+ return FormalPowerSeriesCompose(self, other)
1372
+
1373
+ def inverse(self, x=None, n=6):
1374
+ r"""
1375
+ Returns the truncated terms of the inverse of the formal power series,
1376
+ up to specified ``n``.
1377
+
1378
+ Explanation
1379
+ ===========
1380
+
1381
+ If ``f`` and ``g`` are two formal power series of two different functions,
1382
+ then the coefficient sequence ``ak`` of the composed formal power series ``fp``
1383
+ will be as follows.
1384
+
1385
+ .. math::
1386
+ \sum\limits_{k=0}^{n} (-1)^{k} x_0^{-k-1} B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
1387
+
1388
+ Parameters
1389
+ ==========
1390
+
1391
+ n : Number, optional
1392
+ Specifies the order of the term up to which the polynomial should
1393
+ be truncated.
1394
+
1395
+ Examples
1396
+ ========
1397
+
1398
+ >>> from sympy import fps, exp, cos
1399
+ >>> from sympy.abc import x
1400
+ >>> f1 = fps(exp(x))
1401
+ >>> f2 = fps(cos(x))
1402
+
1403
+ >>> f1.inverse(x).truncate()
1404
+ 1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6)
1405
+
1406
+ >>> f2.inverse(x).truncate(8)
1407
+ 1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
1408
+
1409
+ See Also
1410
+ ========
1411
+
1412
+ sympy.functions.combinatorial.numbers.bell
1413
+ sympy.series.formal.FormalPowerSeriesInverse
1414
+
1415
+ References
1416
+ ==========
1417
+
1418
+ .. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
1419
+
1420
+ """
1421
+
1422
+ if n is None:
1423
+ return iter(self)
1424
+
1425
+ if self._eval_term(0).is_zero:
1426
+ raise ValueError("Constant coefficient should exist for an inverse of a formal"
1427
+ " power series to exist.")
1428
+
1429
+ return FormalPowerSeriesInverse(self)
1430
+
1431
+ def __add__(self, other):
1432
+ other = sympify(other)
1433
+
1434
+ if isinstance(other, FormalPowerSeries):
1435
+ if self.dir != other.dir:
1436
+ raise ValueError("Both series should be calculated from the"
1437
+ " same direction.")
1438
+ elif self.x0 != other.x0:
1439
+ raise ValueError("Both series should be calculated about the"
1440
+ " same point.")
1441
+
1442
+ x, y = self.x, other.x
1443
+ f = self.function + other.function.subs(y, x)
1444
+
1445
+ if self.x not in f.free_symbols:
1446
+ return f
1447
+
1448
+ ak = self.ak + other.ak
1449
+ if self.ak.start > other.ak.start:
1450
+ seq = other.ak
1451
+ s, e = other.ak.start, self.ak.start
1452
+ else:
1453
+ seq = self.ak
1454
+ s, e = self.ak.start, other.ak.start
1455
+ save = Add(*[z[0]*z[1] for z in zip(seq[0:(e - s)], self.xk[s:e])])
1456
+ ind = self.ind + other.ind + save
1457
+
1458
+ return self.func(f, x, self.x0, self.dir, (ak, self.xk, ind))
1459
+
1460
+ elif not other.has(self.x):
1461
+ f = self.function + other
1462
+ ind = self.ind + other
1463
+
1464
+ return self.func(f, self.x, self.x0, self.dir,
1465
+ (self.ak, self.xk, ind))
1466
+
1467
+ return Add(self, other)
1468
+
1469
+ def __radd__(self, other):
1470
+ return self.__add__(other)
1471
+
1472
+ def __neg__(self):
1473
+ return self.func(-self.function, self.x, self.x0, self.dir,
1474
+ (-self.ak, self.xk, -self.ind))
1475
+
1476
+ def __sub__(self, other):
1477
+ return self.__add__(-other)
1478
+
1479
+ def __rsub__(self, other):
1480
+ return (-self).__add__(other)
1481
+
1482
+ def __mul__(self, other):
1483
+ other = sympify(other)
1484
+
1485
+ if other.has(self.x):
1486
+ return Mul(self, other)
1487
+
1488
+ f = self.function * other
1489
+ ak = self.ak.coeff_mul(other)
1490
+ ind = self.ind * other
1491
+
1492
+ return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
1493
+
1494
+ def __rmul__(self, other):
1495
+ return self.__mul__(other)
1496
+
1497
+
1498
+ class FiniteFormalPowerSeries(FormalPowerSeries):
1499
+ """Base Class for Product, Compose and Inverse classes"""
1500
+
1501
+ def __init__(self, *args):
1502
+ pass
1503
+
1504
+ @property
1505
+ def ffps(self):
1506
+ return self.args[0]
1507
+
1508
+ @property
1509
+ def gfps(self):
1510
+ return self.args[1]
1511
+
1512
+ @property
1513
+ def f(self):
1514
+ return self.ffps.function
1515
+
1516
+ @property
1517
+ def g(self):
1518
+ return self.gfps.function
1519
+
1520
+ @property
1521
+ def infinite(self):
1522
+ raise NotImplementedError("No infinite version for an object of"
1523
+ " FiniteFormalPowerSeries class.")
1524
+
1525
+ def _eval_terms(self, n):
1526
+ raise NotImplementedError("(%s)._eval_terms()" % self)
1527
+
1528
+ def _eval_term(self, pt):
1529
+ raise NotImplementedError("By the current logic, one can get terms"
1530
+ "upto a certain order, instead of getting term by term.")
1531
+
1532
+ def polynomial(self, n):
1533
+ return self._eval_terms(n)
1534
+
1535
+ def truncate(self, n=6):
1536
+ ffps = self.ffps
1537
+ pt_xk = ffps.xk.coeff(n)
1538
+ x, x0 = ffps.x, ffps.x0
1539
+
1540
+ return self.polynomial(n) + Order(pt_xk, (x, x0))
1541
+
1542
+ def _eval_derivative(self, x):
1543
+ raise NotImplementedError
1544
+
1545
+ def integrate(self, x):
1546
+ raise NotImplementedError
1547
+
1548
+
1549
+ class FormalPowerSeriesProduct(FiniteFormalPowerSeries):
1550
+ """Represents the product of two formal power series of two functions.
1551
+
1552
+ Explanation
1553
+ ===========
1554
+
1555
+ No computation is performed. Terms are calculated using a term by term logic,
1556
+ instead of a point by point logic.
1557
+
1558
+ There are two differences between a :obj:`FormalPowerSeries` object and a
1559
+ :obj:`FormalPowerSeriesProduct` object. The first argument contains the two
1560
+ functions involved in the product. Also, the coefficient sequence contains
1561
+ both the coefficient sequence of the formal power series of the involved functions.
1562
+
1563
+ See Also
1564
+ ========
1565
+
1566
+ sympy.series.formal.FormalPowerSeries
1567
+ sympy.series.formal.FiniteFormalPowerSeries
1568
+
1569
+ """
1570
+
1571
+ def __init__(self, *args):
1572
+ ffps, gfps = self.ffps, self.gfps
1573
+
1574
+ k = ffps.ak.variables[0]
1575
+ self.coeff1 = sequence(ffps.ak.formula, (k, 0, oo))
1576
+
1577
+ k = gfps.ak.variables[0]
1578
+ self.coeff2 = sequence(gfps.ak.formula, (k, 0, oo))
1579
+
1580
+ @property
1581
+ def function(self):
1582
+ """Function of the product of two formal power series."""
1583
+ return self.f * self.g
1584
+
1585
+ def _eval_terms(self, n):
1586
+ """
1587
+ Returns the first ``n`` terms of the product formal power series.
1588
+ Term by term logic is implemented here.
1589
+
1590
+ Examples
1591
+ ========
1592
+
1593
+ >>> from sympy import fps, sin, exp
1594
+ >>> from sympy.abc import x
1595
+ >>> f1 = fps(sin(x))
1596
+ >>> f2 = fps(exp(x))
1597
+ >>> fprod = f1.product(f2, x)
1598
+
1599
+ >>> fprod._eval_terms(4)
1600
+ x**3/3 + x**2 + x
1601
+
1602
+ See Also
1603
+ ========
1604
+
1605
+ sympy.series.formal.FormalPowerSeries.product
1606
+
1607
+ """
1608
+ coeff1, coeff2 = self.coeff1, self.coeff2
1609
+
1610
+ aks = convolution(coeff1[:n], coeff2[:n])
1611
+
1612
+ terms = []
1613
+ for i in range(0, n):
1614
+ terms.append(aks[i] * self.ffps.xk.coeff(i))
1615
+
1616
+ return Add(*terms)
1617
+
1618
+
1619
+ class FormalPowerSeriesCompose(FiniteFormalPowerSeries):
1620
+ """
1621
+ Represents the composed formal power series of two functions.
1622
+
1623
+ Explanation
1624
+ ===========
1625
+
1626
+ No computation is performed. Terms are calculated using a term by term logic,
1627
+ instead of a point by point logic.
1628
+
1629
+ There are two differences between a :obj:`FormalPowerSeries` object and a
1630
+ :obj:`FormalPowerSeriesCompose` object. The first argument contains the outer
1631
+ function and the inner function involved in the omposition. Also, the
1632
+ coefficient sequence contains the generic sequence which is to be multiplied
1633
+ by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to
1634
+ get the final terms.
1635
+
1636
+ See Also
1637
+ ========
1638
+
1639
+ sympy.series.formal.FormalPowerSeries
1640
+ sympy.series.formal.FiniteFormalPowerSeries
1641
+
1642
+ """
1643
+
1644
+ @property
1645
+ def function(self):
1646
+ """Function for the composed formal power series."""
1647
+ f, g, x = self.f, self.g, self.ffps.x
1648
+ return f.subs(x, g)
1649
+
1650
+ def _eval_terms(self, n):
1651
+ """
1652
+ Returns the first `n` terms of the composed formal power series.
1653
+ Term by term logic is implemented here.
1654
+
1655
+ Explanation
1656
+ ===========
1657
+
1658
+ The coefficient sequence of the :obj:`FormalPowerSeriesCompose` object is the generic sequence.
1659
+ It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
1660
+ the final terms for the polynomial.
1661
+
1662
+ Examples
1663
+ ========
1664
+
1665
+ >>> from sympy import fps, sin, exp
1666
+ >>> from sympy.abc import x
1667
+ >>> f1 = fps(exp(x))
1668
+ >>> f2 = fps(sin(x))
1669
+ >>> fcomp = f1.compose(f2, x)
1670
+
1671
+ >>> fcomp._eval_terms(6)
1672
+ -x**5/15 - x**4/8 + x**2/2 + x + 1
1673
+
1674
+ >>> fcomp._eval_terms(8)
1675
+ x**7/90 - x**6/240 - x**5/15 - x**4/8 + x**2/2 + x + 1
1676
+
1677
+ See Also
1678
+ ========
1679
+
1680
+ sympy.series.formal.FormalPowerSeries.compose
1681
+ sympy.series.formal.FormalPowerSeries.coeff_bell
1682
+
1683
+ """
1684
+
1685
+ ffps, gfps = self.ffps, self.gfps
1686
+ terms = [ffps.zero_coeff()]
1687
+
1688
+ for i in range(1, n):
1689
+ bell_seq = gfps.coeff_bell(i)
1690
+ seq = (ffps.bell_coeff_seq * bell_seq)
1691
+ terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
1692
+
1693
+ return Add(*terms)
1694
+
1695
+
1696
+ class FormalPowerSeriesInverse(FiniteFormalPowerSeries):
1697
+ """
1698
+ Represents the Inverse of a formal power series.
1699
+
1700
+ Explanation
1701
+ ===========
1702
+
1703
+ No computation is performed. Terms are calculated using a term by term logic,
1704
+ instead of a point by point logic.
1705
+
1706
+ There is a single difference between a :obj:`FormalPowerSeries` object and a
1707
+ :obj:`FormalPowerSeriesInverse` object. The coefficient sequence contains the
1708
+ generic sequence which is to be multiplied by a custom ``bell_seq`` finite sequence.
1709
+ The finite terms will then be added up to get the final terms.
1710
+
1711
+ See Also
1712
+ ========
1713
+
1714
+ sympy.series.formal.FormalPowerSeries
1715
+ sympy.series.formal.FiniteFormalPowerSeries
1716
+
1717
+ """
1718
+ def __init__(self, *args):
1719
+ ffps = self.ffps
1720
+ k = ffps.xk.variables[0]
1721
+
1722
+ inv = ffps.zero_coeff()
1723
+ inv_seq = sequence(inv ** (-(k + 1)), (k, 1, oo))
1724
+ self.aux_seq = ffps.sign_seq * ffps.fact_seq * inv_seq
1725
+
1726
+ @property
1727
+ def function(self):
1728
+ """Function for the inverse of a formal power series."""
1729
+ f = self.f
1730
+ return 1 / f
1731
+
1732
+ @property
1733
+ def g(self):
1734
+ raise ValueError("Only one function is considered while performing"
1735
+ "inverse of a formal power series.")
1736
+
1737
+ @property
1738
+ def gfps(self):
1739
+ raise ValueError("Only one function is considered while performing"
1740
+ "inverse of a formal power series.")
1741
+
1742
+ def _eval_terms(self, n):
1743
+ """
1744
+ Returns the first ``n`` terms of the composed formal power series.
1745
+ Term by term logic is implemented here.
1746
+
1747
+ Explanation
1748
+ ===========
1749
+
1750
+ The coefficient sequence of the `FormalPowerSeriesInverse` object is the generic sequence.
1751
+ It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
1752
+ the final terms for the polynomial.
1753
+
1754
+ Examples
1755
+ ========
1756
+
1757
+ >>> from sympy import fps, exp, cos
1758
+ >>> from sympy.abc import x
1759
+ >>> f1 = fps(exp(x))
1760
+ >>> f2 = fps(cos(x))
1761
+ >>> finv1, finv2 = f1.inverse(), f2.inverse()
1762
+
1763
+ >>> finv1._eval_terms(6)
1764
+ -x**5/120 + x**4/24 - x**3/6 + x**2/2 - x + 1
1765
+
1766
+ >>> finv2._eval_terms(8)
1767
+ 61*x**6/720 + 5*x**4/24 + x**2/2 + 1
1768
+
1769
+ See Also
1770
+ ========
1771
+
1772
+ sympy.series.formal.FormalPowerSeries.inverse
1773
+ sympy.series.formal.FormalPowerSeries.coeff_bell
1774
+
1775
+ """
1776
+ ffps = self.ffps
1777
+ terms = [ffps.zero_coeff()]
1778
+
1779
+ for i in range(1, n):
1780
+ bell_seq = ffps.coeff_bell(i)
1781
+ seq = (self.aux_seq * bell_seq)
1782
+ terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
1783
+
1784
+ return Add(*terms)
1785
+
1786
+
1787
+ def fps(f, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False):
1788
+ """
1789
+ Generates Formal Power Series of ``f``.
1790
+
1791
+ Explanation
1792
+ ===========
1793
+
1794
+ Returns the formal series expansion of ``f`` around ``x = x0``
1795
+ with respect to ``x`` in the form of a ``FormalPowerSeries`` object.
1796
+
1797
+ Formal Power Series is represented using an explicit formula
1798
+ computed using different algorithms.
1799
+
1800
+ See :func:`compute_fps` for the more details regarding the computation
1801
+ of formula.
1802
+
1803
+ Parameters
1804
+ ==========
1805
+
1806
+ x : Symbol, optional
1807
+ If x is None and ``f`` is univariate, the univariate symbols will be
1808
+ supplied, otherwise an error will be raised.
1809
+ x0 : number, optional
1810
+ Point to perform series expansion about. Default is 0.
1811
+ dir : {1, -1, '+', '-'}, optional
1812
+ If dir is 1 or '+' the series is calculated from the right and
1813
+ for -1 or '-' the series is calculated from the left. For smooth
1814
+ functions this flag will not alter the results. Default is 1.
1815
+ hyper : {True, False}, optional
1816
+ Set hyper to False to skip the hypergeometric algorithm.
1817
+ By default it is set to False.
1818
+ order : int, optional
1819
+ Order of the derivative of ``f``, Default is 4.
1820
+ rational : {True, False}, optional
1821
+ Set rational to False to skip rational algorithm. By default it is set
1822
+ to True.
1823
+ full : {True, False}, optional
1824
+ Set full to True to increase the range of rational algorithm.
1825
+ See :func:`rational_algorithm` for details. By default it is set to
1826
+ False.
1827
+
1828
+ Examples
1829
+ ========
1830
+
1831
+ >>> from sympy import fps, ln, atan, sin
1832
+ >>> from sympy.abc import x, n
1833
+
1834
+ Rational Functions
1835
+
1836
+ >>> fps(ln(1 + x)).truncate()
1837
+ x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
1838
+
1839
+ >>> fps(atan(x), full=True).truncate()
1840
+ x - x**3/3 + x**5/5 + O(x**6)
1841
+
1842
+ Symbolic Functions
1843
+
1844
+ >>> fps(x**n*sin(x**2), x).truncate(8)
1845
+ -x**(n + 6)/6 + x**(n + 2) + O(x**(n + 8))
1846
+
1847
+ See Also
1848
+ ========
1849
+
1850
+ sympy.series.formal.FormalPowerSeries
1851
+ sympy.series.formal.compute_fps
1852
+ """
1853
+ f = sympify(f)
1854
+
1855
+ if x is None:
1856
+ free = f.free_symbols
1857
+ if len(free) == 1:
1858
+ x = free.pop()
1859
+ elif not free:
1860
+ return f
1861
+ else:
1862
+ raise NotImplementedError("multivariate formal power series")
1863
+
1864
+ result = compute_fps(f, x, x0, dir, hyper, order, rational, full)
1865
+
1866
+ if result is None:
1867
+ return f
1868
+
1869
+ return FormalPowerSeries(f, x, x0, dir, result)
env-llmeval/lib/python3.10/site-packages/sympy/series/fourier.py ADDED
@@ -0,0 +1,808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fourier Series"""
2
+
3
+ from sympy.core.numbers import (oo, pi)
4
+ from sympy.core.symbol import Wild
5
+ from sympy.core.expr import Expr
6
+ from sympy.core.add import Add
7
+ from sympy.core.containers import Tuple
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import Dummy, Symbol
10
+ from sympy.core.sympify import sympify
11
+ from sympy.functions.elementary.trigonometric import sin, cos, sinc
12
+ from sympy.series.series_class import SeriesBase
13
+ from sympy.series.sequences import SeqFormula
14
+ from sympy.sets.sets import Interval
15
+ from sympy.utilities.iterables import is_sequence
16
+
17
+
18
+ def fourier_cos_seq(func, limits, n):
19
+ """Returns the cos sequence in a Fourier series"""
20
+ from sympy.integrals import integrate
21
+ x, L = limits[0], limits[2] - limits[1]
22
+ cos_term = cos(2*n*pi*x / L)
23
+ formula = 2 * cos_term * integrate(func * cos_term, limits) / L
24
+ a0 = formula.subs(n, S.Zero) / 2
25
+ return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits)
26
+ / L, (n, 1, oo))
27
+
28
+
29
+ def fourier_sin_seq(func, limits, n):
30
+ """Returns the sin sequence in a Fourier series"""
31
+ from sympy.integrals import integrate
32
+ x, L = limits[0], limits[2] - limits[1]
33
+ sin_term = sin(2*n*pi*x / L)
34
+ return SeqFormula(2 * sin_term * integrate(func * sin_term, limits)
35
+ / L, (n, 1, oo))
36
+
37
+
38
+ def _process_limits(func, limits):
39
+ """
40
+ Limits should be of the form (x, start, stop).
41
+ x should be a symbol. Both start and stop should be bounded.
42
+
43
+ Explanation
44
+ ===========
45
+
46
+ * If x is not given, x is determined from func.
47
+ * If limits is None. Limit of the form (x, -pi, pi) is returned.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy.series.fourier import _process_limits as pari
53
+ >>> from sympy.abc import x
54
+ >>> pari(x**2, (x, -2, 2))
55
+ (x, -2, 2)
56
+ >>> pari(x**2, (-2, 2))
57
+ (x, -2, 2)
58
+ >>> pari(x**2, None)
59
+ (x, -pi, pi)
60
+ """
61
+ def _find_x(func):
62
+ free = func.free_symbols
63
+ if len(free) == 1:
64
+ return free.pop()
65
+ elif not free:
66
+ return Dummy('k')
67
+ else:
68
+ raise ValueError(
69
+ " specify dummy variables for %s. If the function contains"
70
+ " more than one free symbol, a dummy variable should be"
71
+ " supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))"
72
+ % func)
73
+
74
+ x, start, stop = None, None, None
75
+ if limits is None:
76
+ x, start, stop = _find_x(func), -pi, pi
77
+ if is_sequence(limits, Tuple):
78
+ if len(limits) == 3:
79
+ x, start, stop = limits
80
+ elif len(limits) == 2:
81
+ x = _find_x(func)
82
+ start, stop = limits
83
+
84
+ if not isinstance(x, Symbol) or start is None or stop is None:
85
+ raise ValueError('Invalid limits given: %s' % str(limits))
86
+
87
+ unbounded = [S.NegativeInfinity, S.Infinity]
88
+ if start in unbounded or stop in unbounded:
89
+ raise ValueError("Both the start and end value should be bounded")
90
+
91
+ return sympify((x, start, stop))
92
+
93
+
94
+ def finite_check(f, x, L):
95
+
96
+ def check_fx(exprs, x):
97
+ return x not in exprs.free_symbols
98
+
99
+ def check_sincos(_expr, x, L):
100
+ if isinstance(_expr, (sin, cos)):
101
+ sincos_args = _expr.args[0]
102
+
103
+ if sincos_args.match(a*(pi/L)*x + b) is not None:
104
+ return True
105
+ else:
106
+ return False
107
+
108
+ from sympy.simplify.fu import TR2, TR1, sincos_to_sum
109
+ _expr = sincos_to_sum(TR2(TR1(f)))
110
+ add_coeff = _expr.as_coeff_add()
111
+
112
+ a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ])
113
+ b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
114
+
115
+ for s in add_coeff[1]:
116
+ mul_coeffs = s.as_coeff_mul()[1]
117
+ for t in mul_coeffs:
118
+ if not (check_fx(t, x) or check_sincos(t, x, L)):
119
+ return False, f
120
+
121
+ return True, _expr
122
+
123
+
124
+ class FourierSeries(SeriesBase):
125
+ r"""Represents Fourier sine/cosine series.
126
+
127
+ Explanation
128
+ ===========
129
+
130
+ This class only represents a fourier series.
131
+ No computation is performed.
132
+
133
+ For how to compute Fourier series, see the :func:`fourier_series`
134
+ docstring.
135
+
136
+ See Also
137
+ ========
138
+
139
+ sympy.series.fourier.fourier_series
140
+ """
141
+ def __new__(cls, *args):
142
+ args = map(sympify, args)
143
+ return Expr.__new__(cls, *args)
144
+
145
+ @property
146
+ def function(self):
147
+ return self.args[0]
148
+
149
+ @property
150
+ def x(self):
151
+ return self.args[1][0]
152
+
153
+ @property
154
+ def period(self):
155
+ return (self.args[1][1], self.args[1][2])
156
+
157
+ @property
158
+ def a0(self):
159
+ return self.args[2][0]
160
+
161
+ @property
162
+ def an(self):
163
+ return self.args[2][1]
164
+
165
+ @property
166
+ def bn(self):
167
+ return self.args[2][2]
168
+
169
+ @property
170
+ def interval(self):
171
+ return Interval(0, oo)
172
+
173
+ @property
174
+ def start(self):
175
+ return self.interval.inf
176
+
177
+ @property
178
+ def stop(self):
179
+ return self.interval.sup
180
+
181
+ @property
182
+ def length(self):
183
+ return oo
184
+
185
+ @property
186
+ def L(self):
187
+ return abs(self.period[1] - self.period[0]) / 2
188
+
189
+ def _eval_subs(self, old, new):
190
+ x = self.x
191
+ if old.has(x):
192
+ return self
193
+
194
+ def truncate(self, n=3):
195
+ """
196
+ Return the first n nonzero terms of the series.
197
+
198
+ If ``n`` is None return an iterator.
199
+
200
+ Parameters
201
+ ==========
202
+
203
+ n : int or None
204
+ Amount of non-zero terms in approximation or None.
205
+
206
+ Returns
207
+ =======
208
+
209
+ Expr or iterator :
210
+ Approximation of function expanded into Fourier series.
211
+
212
+ Examples
213
+ ========
214
+
215
+ >>> from sympy import fourier_series, pi
216
+ >>> from sympy.abc import x
217
+ >>> s = fourier_series(x, (x, -pi, pi))
218
+ >>> s.truncate(4)
219
+ 2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2
220
+
221
+ See Also
222
+ ========
223
+
224
+ sympy.series.fourier.FourierSeries.sigma_approximation
225
+ """
226
+ if n is None:
227
+ return iter(self)
228
+
229
+ terms = []
230
+ for t in self:
231
+ if len(terms) == n:
232
+ break
233
+ if t is not S.Zero:
234
+ terms.append(t)
235
+
236
+ return Add(*terms)
237
+
238
+ def sigma_approximation(self, n=3):
239
+ r"""
240
+ Return :math:`\sigma`-approximation of Fourier series with respect
241
+ to order n.
242
+
243
+ Explanation
244
+ ===========
245
+
246
+ Sigma approximation adjusts a Fourier summation to eliminate the Gibbs
247
+ phenomenon which would otherwise occur at discontinuities.
248
+ A sigma-approximated summation for a Fourier series of a T-periodical
249
+ function can be written as
250
+
251
+ .. math::
252
+ s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1}
253
+ \operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot
254
+ \left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr)
255
+ + b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right],
256
+
257
+ where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier
258
+ series coefficients and
259
+ :math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos
260
+ :math:`\sigma` factor (expressed in terms of normalized
261
+ :math:`\operatorname{sinc}` function).
262
+
263
+ Parameters
264
+ ==========
265
+
266
+ n : int
267
+ Highest order of the terms taken into account in approximation.
268
+
269
+ Returns
270
+ =======
271
+
272
+ Expr :
273
+ Sigma approximation of function expanded into Fourier series.
274
+
275
+ Examples
276
+ ========
277
+
278
+ >>> from sympy import fourier_series, pi
279
+ >>> from sympy.abc import x
280
+ >>> s = fourier_series(x, (x, -pi, pi))
281
+ >>> s.sigma_approximation(4)
282
+ 2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3
283
+
284
+ See Also
285
+ ========
286
+
287
+ sympy.series.fourier.FourierSeries.truncate
288
+
289
+ Notes
290
+ =====
291
+
292
+ The behaviour of
293
+ :meth:`~sympy.series.fourier.FourierSeries.sigma_approximation`
294
+ is different from :meth:`~sympy.series.fourier.FourierSeries.truncate`
295
+ - it takes all nonzero terms of degree smaller than n, rather than
296
+ first n nonzero ones.
297
+
298
+ References
299
+ ==========
300
+
301
+ .. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon
302
+ .. [2] https://en.wikipedia.org/wiki/Sigma_approximation
303
+ """
304
+ terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n])
305
+ if t is not S.Zero]
306
+ return Add(*terms)
307
+
308
+ def shift(self, s):
309
+ """
310
+ Shift the function by a term independent of x.
311
+
312
+ Explanation
313
+ ===========
314
+
315
+ f(x) -> f(x) + s
316
+
317
+ This is fast, if Fourier series of f(x) is already
318
+ computed.
319
+
320
+ Examples
321
+ ========
322
+
323
+ >>> from sympy import fourier_series, pi
324
+ >>> from sympy.abc import x
325
+ >>> s = fourier_series(x**2, (x, -pi, pi))
326
+ >>> s.shift(1).truncate()
327
+ -4*cos(x) + cos(2*x) + 1 + pi**2/3
328
+ """
329
+ s, x = sympify(s), self.x
330
+
331
+ if x in s.free_symbols:
332
+ raise ValueError("'%s' should be independent of %s" % (s, x))
333
+
334
+ a0 = self.a0 + s
335
+ sfunc = self.function + s
336
+
337
+ return self.func(sfunc, self.args[1], (a0, self.an, self.bn))
338
+
339
+ def shiftx(self, s):
340
+ """
341
+ Shift x by a term independent of x.
342
+
343
+ Explanation
344
+ ===========
345
+
346
+ f(x) -> f(x + s)
347
+
348
+ This is fast, if Fourier series of f(x) is already
349
+ computed.
350
+
351
+ Examples
352
+ ========
353
+
354
+ >>> from sympy import fourier_series, pi
355
+ >>> from sympy.abc import x
356
+ >>> s = fourier_series(x**2, (x, -pi, pi))
357
+ >>> s.shiftx(1).truncate()
358
+ -4*cos(x + 1) + cos(2*x + 2) + pi**2/3
359
+ """
360
+ s, x = sympify(s), self.x
361
+
362
+ if x in s.free_symbols:
363
+ raise ValueError("'%s' should be independent of %s" % (s, x))
364
+
365
+ an = self.an.subs(x, x + s)
366
+ bn = self.bn.subs(x, x + s)
367
+ sfunc = self.function.subs(x, x + s)
368
+
369
+ return self.func(sfunc, self.args[1], (self.a0, an, bn))
370
+
371
+ def scale(self, s):
372
+ """
373
+ Scale the function by a term independent of x.
374
+
375
+ Explanation
376
+ ===========
377
+
378
+ f(x) -> s * f(x)
379
+
380
+ This is fast, if Fourier series of f(x) is already
381
+ computed.
382
+
383
+ Examples
384
+ ========
385
+
386
+ >>> from sympy import fourier_series, pi
387
+ >>> from sympy.abc import x
388
+ >>> s = fourier_series(x**2, (x, -pi, pi))
389
+ >>> s.scale(2).truncate()
390
+ -8*cos(x) + 2*cos(2*x) + 2*pi**2/3
391
+ """
392
+ s, x = sympify(s), self.x
393
+
394
+ if x in s.free_symbols:
395
+ raise ValueError("'%s' should be independent of %s" % (s, x))
396
+
397
+ an = self.an.coeff_mul(s)
398
+ bn = self.bn.coeff_mul(s)
399
+ a0 = self.a0 * s
400
+ sfunc = self.args[0] * s
401
+
402
+ return self.func(sfunc, self.args[1], (a0, an, bn))
403
+
404
+ def scalex(self, s):
405
+ """
406
+ Scale x by a term independent of x.
407
+
408
+ Explanation
409
+ ===========
410
+
411
+ f(x) -> f(s*x)
412
+
413
+ This is fast, if Fourier series of f(x) is already
414
+ computed.
415
+
416
+ Examples
417
+ ========
418
+
419
+ >>> from sympy import fourier_series, pi
420
+ >>> from sympy.abc import x
421
+ >>> s = fourier_series(x**2, (x, -pi, pi))
422
+ >>> s.scalex(2).truncate()
423
+ -4*cos(2*x) + cos(4*x) + pi**2/3
424
+ """
425
+ s, x = sympify(s), self.x
426
+
427
+ if x in s.free_symbols:
428
+ raise ValueError("'%s' should be independent of %s" % (s, x))
429
+
430
+ an = self.an.subs(x, x * s)
431
+ bn = self.bn.subs(x, x * s)
432
+ sfunc = self.function.subs(x, x * s)
433
+
434
+ return self.func(sfunc, self.args[1], (self.a0, an, bn))
435
+
436
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
437
+ for t in self:
438
+ if t is not S.Zero:
439
+ return t
440
+
441
+ def _eval_term(self, pt):
442
+ if pt == 0:
443
+ return self.a0
444
+ return self.an.coeff(pt) + self.bn.coeff(pt)
445
+
446
+ def __neg__(self):
447
+ return self.scale(-1)
448
+
449
+ def __add__(self, other):
450
+ if isinstance(other, FourierSeries):
451
+ if self.period != other.period:
452
+ raise ValueError("Both the series should have same periods")
453
+
454
+ x, y = self.x, other.x
455
+ function = self.function + other.function.subs(y, x)
456
+
457
+ if self.x not in function.free_symbols:
458
+ return function
459
+
460
+ an = self.an + other.an
461
+ bn = self.bn + other.bn
462
+ a0 = self.a0 + other.a0
463
+
464
+ return self.func(function, self.args[1], (a0, an, bn))
465
+
466
+ return Add(self, other)
467
+
468
+ def __sub__(self, other):
469
+ return self.__add__(-other)
470
+
471
+
472
+ class FiniteFourierSeries(FourierSeries):
473
+ r"""Represents Finite Fourier sine/cosine series.
474
+
475
+ For how to compute Fourier series, see the :func:`fourier_series`
476
+ docstring.
477
+
478
+ Parameters
479
+ ==========
480
+
481
+ f : Expr
482
+ Expression for finding fourier_series
483
+
484
+ limits : ( x, start, stop)
485
+ x is the independent variable for the expression f
486
+ (start, stop) is the period of the fourier series
487
+
488
+ exprs: (a0, an, bn) or Expr
489
+ a0 is the constant term a0 of the fourier series
490
+ an is a dictionary of coefficients of cos terms
491
+ an[k] = coefficient of cos(pi*(k/L)*x)
492
+ bn is a dictionary of coefficients of sin terms
493
+ bn[k] = coefficient of sin(pi*(k/L)*x)
494
+
495
+ or exprs can be an expression to be converted to fourier form
496
+
497
+ Methods
498
+ =======
499
+
500
+ This class is an extension of FourierSeries class.
501
+ Please refer to sympy.series.fourier.FourierSeries for
502
+ further information.
503
+
504
+ See Also
505
+ ========
506
+
507
+ sympy.series.fourier.FourierSeries
508
+ sympy.series.fourier.fourier_series
509
+ """
510
+
511
+ def __new__(cls, f, limits, exprs):
512
+ f = sympify(f)
513
+ limits = sympify(limits)
514
+ exprs = sympify(exprs)
515
+
516
+ if not (isinstance(exprs, Tuple) and len(exprs) == 3): # exprs is not of form (a0, an, bn)
517
+ # Converts the expression to fourier form
518
+ c, e = exprs.as_coeff_add()
519
+ from sympy.simplify.fu import TR10
520
+ rexpr = c + Add(*[TR10(i) for i in e])
521
+ a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add()
522
+
523
+ x = limits[0]
524
+ L = abs(limits[2] - limits[1]) / 2
525
+
526
+ a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ])
527
+ b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
528
+
529
+ an = {}
530
+ bn = {}
531
+
532
+ # separates the coefficients of sin and cos terms in dictionaries an, and bn
533
+ for p in exp_ls:
534
+ t = p.match(b * cos(a * (pi / L) * x))
535
+ q = p.match(b * sin(a * (pi / L) * x))
536
+ if t:
537
+ an[t[a]] = t[b] + an.get(t[a], S.Zero)
538
+ elif q:
539
+ bn[q[a]] = q[b] + bn.get(q[a], S.Zero)
540
+ else:
541
+ a0 += p
542
+
543
+ exprs = Tuple(a0, an, bn)
544
+
545
+ return Expr.__new__(cls, f, limits, exprs)
546
+
547
+ @property
548
+ def interval(self):
549
+ _length = 1 if self.a0 else 0
550
+ _length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1
551
+ return Interval(0, _length)
552
+
553
+ @property
554
+ def length(self):
555
+ return self.stop - self.start
556
+
557
+ def shiftx(self, s):
558
+ s, x = sympify(s), self.x
559
+
560
+ if x in s.free_symbols:
561
+ raise ValueError("'%s' should be independent of %s" % (s, x))
562
+
563
+ _expr = self.truncate().subs(x, x + s)
564
+ sfunc = self.function.subs(x, x + s)
565
+
566
+ return self.func(sfunc, self.args[1], _expr)
567
+
568
+ def scale(self, s):
569
+ s, x = sympify(s), self.x
570
+
571
+ if x in s.free_symbols:
572
+ raise ValueError("'%s' should be independent of %s" % (s, x))
573
+
574
+ _expr = self.truncate() * s
575
+ sfunc = self.function * s
576
+
577
+ return self.func(sfunc, self.args[1], _expr)
578
+
579
+ def scalex(self, s):
580
+ s, x = sympify(s), self.x
581
+
582
+ if x in s.free_symbols:
583
+ raise ValueError("'%s' should be independent of %s" % (s, x))
584
+
585
+ _expr = self.truncate().subs(x, x * s)
586
+ sfunc = self.function.subs(x, x * s)
587
+
588
+ return self.func(sfunc, self.args[1], _expr)
589
+
590
+ def _eval_term(self, pt):
591
+ if pt == 0:
592
+ return self.a0
593
+
594
+ _term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \
595
+ + self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x)
596
+ return _term
597
+
598
+ def __add__(self, other):
599
+ if isinstance(other, FourierSeries):
600
+ return other.__add__(fourier_series(self.function, self.args[1],\
601
+ finite=False))
602
+ elif isinstance(other, FiniteFourierSeries):
603
+ if self.period != other.period:
604
+ raise ValueError("Both the series should have same periods")
605
+
606
+ x, y = self.x, other.x
607
+ function = self.function + other.function.subs(y, x)
608
+
609
+ if self.x not in function.free_symbols:
610
+ return function
611
+
612
+ return fourier_series(function, limits=self.args[1])
613
+
614
+
615
+ def fourier_series(f, limits=None, finite=True):
616
+ r"""Computes the Fourier trigonometric series expansion.
617
+
618
+ Explanation
619
+ ===========
620
+
621
+ Fourier trigonometric series of $f(x)$ over the interval $(a, b)$
622
+ is defined as:
623
+
624
+ .. math::
625
+ \frac{a_0}{2} + \sum_{n=1}^{\infty}
626
+ (a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L}))
627
+
628
+ where the coefficients are:
629
+
630
+ .. math::
631
+ L = b - a
632
+
633
+ .. math::
634
+ a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx}
635
+
636
+ .. math::
637
+ a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx}
638
+
639
+ .. math::
640
+ b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx}
641
+
642
+ The condition whether the function $f(x)$ given should be periodic
643
+ or not is more than necessary, because it is sufficient to consider
644
+ the series to be converging to $f(x)$ only in the given interval,
645
+ not throughout the whole real line.
646
+
647
+ This also brings a lot of ease for the computation because
648
+ you do not have to make $f(x)$ artificially periodic by
649
+ wrapping it with piecewise, modulo operations,
650
+ but you can shape the function to look like the desired periodic
651
+ function only in the interval $(a, b)$, and the computed series will
652
+ automatically become the series of the periodic version of $f(x)$.
653
+
654
+ This property is illustrated in the examples section below.
655
+
656
+ Parameters
657
+ ==========
658
+
659
+ limits : (sym, start, end), optional
660
+ *sym* denotes the symbol the series is computed with respect to.
661
+
662
+ *start* and *end* denotes the start and the end of the interval
663
+ where the fourier series converges to the given function.
664
+
665
+ Default range is specified as $-\pi$ and $\pi$.
666
+
667
+ Returns
668
+ =======
669
+
670
+ FourierSeries
671
+ A symbolic object representing the Fourier trigonometric series.
672
+
673
+ Examples
674
+ ========
675
+
676
+ Computing the Fourier series of $f(x) = x^2$:
677
+
678
+ >>> from sympy import fourier_series, pi
679
+ >>> from sympy.abc import x
680
+ >>> f = x**2
681
+ >>> s = fourier_series(f, (x, -pi, pi))
682
+ >>> s1 = s.truncate(n=3)
683
+ >>> s1
684
+ -4*cos(x) + cos(2*x) + pi**2/3
685
+
686
+ Shifting of the Fourier series:
687
+
688
+ >>> s.shift(1).truncate()
689
+ -4*cos(x) + cos(2*x) + 1 + pi**2/3
690
+ >>> s.shiftx(1).truncate()
691
+ -4*cos(x + 1) + cos(2*x + 2) + pi**2/3
692
+
693
+ Scaling of the Fourier series:
694
+
695
+ >>> s.scale(2).truncate()
696
+ -8*cos(x) + 2*cos(2*x) + 2*pi**2/3
697
+ >>> s.scalex(2).truncate()
698
+ -4*cos(2*x) + cos(4*x) + pi**2/3
699
+
700
+ Computing the Fourier series of $f(x) = x$:
701
+
702
+ This illustrates how truncating to the higher order gives better
703
+ convergence.
704
+
705
+ .. plot::
706
+ :context: reset
707
+ :format: doctest
708
+ :include-source: True
709
+
710
+ >>> from sympy import fourier_series, pi, plot
711
+ >>> from sympy.abc import x
712
+ >>> f = x
713
+ >>> s = fourier_series(f, (x, -pi, pi))
714
+ >>> s1 = s.truncate(n = 3)
715
+ >>> s2 = s.truncate(n = 5)
716
+ >>> s3 = s.truncate(n = 7)
717
+ >>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True)
718
+
719
+ >>> p[0].line_color = (0, 0, 0)
720
+ >>> p[0].label = 'x'
721
+ >>> p[1].line_color = (0.7, 0.7, 0.7)
722
+ >>> p[1].label = 'n=3'
723
+ >>> p[2].line_color = (0.5, 0.5, 0.5)
724
+ >>> p[2].label = 'n=5'
725
+ >>> p[3].line_color = (0.3, 0.3, 0.3)
726
+ >>> p[3].label = 'n=7'
727
+
728
+ >>> p.show()
729
+
730
+ This illustrates how the series converges to different sawtooth
731
+ waves if the different ranges are specified.
732
+
733
+ .. plot::
734
+ :context: close-figs
735
+ :format: doctest
736
+ :include-source: True
737
+
738
+ >>> s1 = fourier_series(x, (x, -1, 1)).truncate(10)
739
+ >>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10)
740
+ >>> s3 = fourier_series(x, (x, 0, 1)).truncate(10)
741
+ >>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True)
742
+
743
+ >>> p[0].line_color = (0, 0, 0)
744
+ >>> p[0].label = 'x'
745
+ >>> p[1].line_color = (0.7, 0.7, 0.7)
746
+ >>> p[1].label = '[-1, 1]'
747
+ >>> p[2].line_color = (0.5, 0.5, 0.5)
748
+ >>> p[2].label = '[-pi, pi]'
749
+ >>> p[3].line_color = (0.3, 0.3, 0.3)
750
+ >>> p[3].label = '[0, 1]'
751
+
752
+ >>> p.show()
753
+
754
+ Notes
755
+ =====
756
+
757
+ Computing Fourier series can be slow
758
+ due to the integration required in computing
759
+ an, bn.
760
+
761
+ It is faster to compute Fourier series of a function
762
+ by using shifting and scaling on an already
763
+ computed Fourier series rather than computing
764
+ again.
765
+
766
+ e.g. If the Fourier series of ``x**2`` is known
767
+ the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``.
768
+
769
+ See Also
770
+ ========
771
+
772
+ sympy.series.fourier.FourierSeries
773
+
774
+ References
775
+ ==========
776
+
777
+ .. [1] https://mathworld.wolfram.com/FourierSeries.html
778
+ """
779
+ f = sympify(f)
780
+
781
+ limits = _process_limits(f, limits)
782
+ x = limits[0]
783
+
784
+ if x not in f.free_symbols:
785
+ return f
786
+
787
+ if finite:
788
+ L = abs(limits[2] - limits[1]) / 2
789
+ is_finite, res_f = finite_check(f, x, L)
790
+ if is_finite:
791
+ return FiniteFourierSeries(f, limits, res_f)
792
+
793
+ n = Dummy('n')
794
+ center = (limits[1] + limits[2]) / 2
795
+ if center.is_zero:
796
+ neg_f = f.subs(x, -x)
797
+ if f == neg_f:
798
+ a0, an = fourier_cos_seq(f, limits, n)
799
+ bn = SeqFormula(0, (1, oo))
800
+ return FourierSeries(f, limits, (a0, an, bn))
801
+ elif f == -neg_f:
802
+ a0 = S.Zero
803
+ an = SeqFormula(0, (1, oo))
804
+ bn = fourier_sin_seq(f, limits, n)
805
+ return FourierSeries(f, limits, (a0, an, bn))
806
+ a0, an = fourier_cos_seq(f, limits, n)
807
+ bn = fourier_sin_seq(f, limits, n)
808
+ return FourierSeries(f, limits, (a0, an, bn))
env-llmeval/lib/python3.10/site-packages/sympy/series/gruntz.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Limits
3
+ ======
4
+
5
+ Implemented according to the PhD thesis
6
+ https://www.cybertester.com/data/gruntz.pdf, which contains very thorough
7
+ descriptions of the algorithm including many examples. We summarize here
8
+ the gist of it.
9
+
10
+ All functions are sorted according to how rapidly varying they are at
11
+ infinity using the following rules. Any two functions f and g can be
12
+ compared using the properties of L:
13
+
14
+ L=lim log|f(x)| / log|g(x)| (for x -> oo)
15
+
16
+ We define >, < ~ according to::
17
+
18
+ 1. f > g .... L=+-oo
19
+
20
+ we say that:
21
+ - f is greater than any power of g
22
+ - f is more rapidly varying than g
23
+ - f goes to infinity/zero faster than g
24
+
25
+ 2. f < g .... L=0
26
+
27
+ we say that:
28
+ - f is lower than any power of g
29
+
30
+ 3. f ~ g .... L!=0, +-oo
31
+
32
+ we say that:
33
+ - both f and g are bounded from above and below by suitable integral
34
+ powers of the other
35
+
36
+ Examples
37
+ ========
38
+ ::
39
+ 2 < x < exp(x) < exp(x**2) < exp(exp(x))
40
+ 2 ~ 3 ~ -5
41
+ x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
42
+ exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
43
+ f ~ 1/f
44
+
45
+ So we can divide all the functions into comparability classes (x and x^2
46
+ belong to one class, exp(x) and exp(-x) belong to some other class). In
47
+ principle, we could compare any two functions, but in our algorithm, we
48
+ do not compare anything below the class 2~3~-5 (for example log(x) is
49
+ below this), so we set 2~3~-5 as the lowest comparability class.
50
+
51
+ Given the function f, we find the list of most rapidly varying (mrv set)
52
+ subexpressions of it. This list belongs to the same comparability class.
53
+ Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
54
+ element "w" (either from the list or a new one) from the same
55
+ comparability class which goes to zero at infinity. In our example we
56
+ set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
57
+ rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
58
+ into f. Then we expand f into a series in w::
59
+
60
+ f = c0*w^e0 + c1*w^e1 + ... + O(w^en), where e0<e1<...<en, c0!=0
61
+
62
+ but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero,
63
+ because w goes to zero faster than the ci and ei. So::
64
+
65
+ for e0>0, lim f = 0
66
+ for e0<0, lim f = +-oo (the sign depends on the sign of c0)
67
+ for e0=0, lim f = lim c0
68
+
69
+ We need to recursively compute limits at several places of the algorithm, but
70
+ as is shown in the PhD thesis, it always finishes.
71
+
72
+ Important functions from the implementation:
73
+
74
+ compare(a, b, x) compares "a" and "b" by computing the limit L.
75
+ mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
76
+ rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
77
+ leadterm(f, x) returns the lowest power term in the series of f
78
+ mrv_leadterm(e, x) returns the lead term (c0, e0) for e
79
+ limitinf(e, x) computes lim e (for x->oo)
80
+ limit(e, z, z0) computes any limit by converting it to the case x->oo
81
+
82
+ All the functions are really simple and straightforward except
83
+ rewrite(), which is the most difficult/complex part of the algorithm.
84
+ When the algorithm fails, the bugs are usually in the series expansion
85
+ (i.e. in SymPy) or in rewrite.
86
+
87
+ This code is almost exact rewrite of the Maple code inside the Gruntz
88
+ thesis.
89
+
90
+ Debugging
91
+ ---------
92
+
93
+ Because the gruntz algorithm is highly recursive, it's difficult to
94
+ figure out what went wrong inside a debugger. Instead, turn on nice
95
+ debug prints by defining the environment variable SYMPY_DEBUG. For
96
+ example:
97
+
98
+ [user@localhost]: SYMPY_DEBUG=True ./bin/isympy
99
+
100
+ In [1]: limit(sin(x)/x, x, 0)
101
+ limitinf(_x*sin(1/_x), _x) = 1
102
+ +-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
103
+ | +-mrv(_x*sin(1/_x), _x) = set([_x])
104
+ | | +-mrv(_x, _x) = set([_x])
105
+ | | +-mrv(sin(1/_x), _x) = set([_x])
106
+ | | +-mrv(1/_x, _x) = set([_x])
107
+ | | +-mrv(_x, _x) = set([_x])
108
+ | +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
109
+ | +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
110
+ | +-sign(_x, _x) = 1
111
+ | +-mrv_leadterm(1, _x) = (1, 0)
112
+ +-sign(0, _x) = 0
113
+ +-limitinf(1, _x) = 1
114
+
115
+ And check manually which line is wrong. Then go to the source code and
116
+ debug this function to figure out the exact problem.
117
+
118
+ """
119
+ from functools import reduce
120
+
121
+ from sympy.core import Basic, S, Mul, PoleError, expand_mul
122
+ from sympy.core.cache import cacheit
123
+ from sympy.core.numbers import ilcm, I, oo
124
+ from sympy.core.symbol import Dummy, Wild
125
+ from sympy.core.traversal import bottom_up
126
+
127
+ from sympy.functions import log, exp, sign as _sign
128
+ from sympy.series.order import Order
129
+ from sympy.utilities.exceptions import SymPyDeprecationWarning
130
+ from sympy.utilities.misc import debug_decorator as debug
131
+ from sympy.utilities.timeutils import timethis
132
+
133
+ timeit = timethis('gruntz')
134
+
135
+
136
+ def compare(a, b, x):
137
+ """Returns "<" if a<b, "=" for a == b, ">" for a>b"""
138
+ # log(exp(...)) must always be simplified here for termination
139
+ la, lb = log(a), log(b)
140
+ if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
141
+ la = a.exp
142
+ if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
143
+ lb = b.exp
144
+
145
+ c = limitinf(la/lb, x)
146
+ if c == 0:
147
+ return "<"
148
+ elif c.is_infinite:
149
+ return ">"
150
+ else:
151
+ return "="
152
+
153
+
154
+ class SubsSet(dict):
155
+ """
156
+ Stores (expr, dummy) pairs, and how to rewrite expr-s.
157
+
158
+ Explanation
159
+ ===========
160
+
161
+ The gruntz algorithm needs to rewrite certain expressions in term of a new
162
+ variable w. We cannot use subs, because it is just too smart for us. For
163
+ example::
164
+
165
+ > Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
166
+ > O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
167
+ > e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
168
+ > e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
169
+ -1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
170
+
171
+ is really not what we want!
172
+
173
+ So we do it the hard way and keep track of all the things we potentially
174
+ want to substitute by dummy variables. Consider the expression::
175
+
176
+ exp(x - exp(-x)) + exp(x) + x.
177
+
178
+ The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
179
+ We introduce corresponding dummy variables d1, d2, d3 and rewrite::
180
+
181
+ d3 + d1 + x.
182
+
183
+ This class first of all keeps track of the mapping expr->variable, i.e.
184
+ will at this stage be a dictionary::
185
+
186
+ {exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
187
+
188
+ [It turns out to be more convenient this way round.]
189
+ But sometimes expressions in the mrv set have other expressions from the
190
+ mrv set as subexpressions, and we need to keep track of that as well. In
191
+ this case, d3 is really exp(x - d2), so rewrites at this stage is::
192
+
193
+ {d3: exp(x-d2)}.
194
+
195
+ The function rewrite uses all this information to correctly rewrite our
196
+ expression in terms of w. In this case w can be chosen to be exp(-x),
197
+ i.e. d2. The correct rewriting then is::
198
+
199
+ exp(-w)/w + 1/w + x.
200
+ """
201
+ def __init__(self):
202
+ self.rewrites = {}
203
+
204
+ def __repr__(self):
205
+ return super().__repr__() + ', ' + self.rewrites.__repr__()
206
+
207
+ def __getitem__(self, key):
208
+ if key not in self:
209
+ self[key] = Dummy()
210
+ return dict.__getitem__(self, key)
211
+
212
+ def do_subs(self, e):
213
+ """Substitute the variables with expressions"""
214
+ for expr, var in self.items():
215
+ e = e.xreplace({var: expr})
216
+ return e
217
+
218
+ def meets(self, s2):
219
+ """Tell whether or not self and s2 have non-empty intersection"""
220
+ return set(self.keys()).intersection(list(s2.keys())) != set()
221
+
222
+ def union(self, s2, exps=None):
223
+ """Compute the union of self and s2, adjusting exps"""
224
+ res = self.copy()
225
+ tr = {}
226
+ for expr, var in s2.items():
227
+ if expr in self:
228
+ if exps:
229
+ exps = exps.xreplace({var: res[expr]})
230
+ tr[var] = res[expr]
231
+ else:
232
+ res[expr] = var
233
+ for var, rewr in s2.rewrites.items():
234
+ res.rewrites[var] = rewr.xreplace(tr)
235
+ return res, exps
236
+
237
+ def copy(self):
238
+ """Create a shallow copy of SubsSet"""
239
+ r = SubsSet()
240
+ r.rewrites = self.rewrites.copy()
241
+ for expr, var in self.items():
242
+ r[expr] = var
243
+ return r
244
+
245
+
246
+ @debug
247
+ def mrv(e, x):
248
+ """Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
249
+ and e rewritten in terms of these"""
250
+ from sympy.simplify.powsimp import powsimp
251
+ e = powsimp(e, deep=True, combine='exp')
252
+ if not isinstance(e, Basic):
253
+ raise TypeError("e should be an instance of Basic")
254
+ if not e.has(x):
255
+ return SubsSet(), e
256
+ elif e == x:
257
+ s = SubsSet()
258
+ return s, s[x]
259
+ elif e.is_Mul or e.is_Add:
260
+ i, d = e.as_independent(x) # throw away x-independent terms
261
+ if d.func != e.func:
262
+ s, expr = mrv(d, x)
263
+ return s, e.func(i, expr)
264
+ a, b = d.as_two_terms()
265
+ s1, e1 = mrv(a, x)
266
+ s2, e2 = mrv(b, x)
267
+ return mrv_max1(s1, s2, e.func(i, e1, e2), x)
268
+ elif e.is_Pow and e.base != S.Exp1:
269
+ e1 = S.One
270
+ while e.is_Pow:
271
+ b1 = e.base
272
+ e1 *= e.exp
273
+ e = b1
274
+ if b1 == 1:
275
+ return SubsSet(), b1
276
+ if e1.has(x):
277
+ base_lim = limitinf(b1, x)
278
+ if base_lim is S.One:
279
+ return mrv(exp(e1 * (b1 - 1)), x)
280
+ return mrv(exp(e1 * log(b1)), x)
281
+ else:
282
+ s, expr = mrv(b1, x)
283
+ return s, expr**e1
284
+ elif isinstance(e, log):
285
+ s, expr = mrv(e.args[0], x)
286
+ return s, log(expr)
287
+ elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
288
+ # We know from the theory of this algorithm that exp(log(...)) may always
289
+ # be simplified here, and doing so is vital for termination.
290
+ if isinstance(e.exp, log):
291
+ return mrv(e.exp.args[0], x)
292
+ # if a product has an infinite factor the result will be
293
+ # infinite if there is no zero, otherwise NaN; here, we
294
+ # consider the result infinite if any factor is infinite
295
+ li = limitinf(e.exp, x)
296
+ if any(_.is_infinite for _ in Mul.make_args(li)):
297
+ s1 = SubsSet()
298
+ e1 = s1[e]
299
+ s2, e2 = mrv(e.exp, x)
300
+ su = s1.union(s2)[0]
301
+ su.rewrites[e1] = exp(e2)
302
+ return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
303
+ else:
304
+ s, expr = mrv(e.exp, x)
305
+ return s, exp(expr)
306
+ elif e.is_Function:
307
+ l = [mrv(a, x) for a in e.args]
308
+ l2 = [s for (s, _) in l if s != SubsSet()]
309
+ if len(l2) != 1:
310
+ # e.g. something like BesselJ(x, x)
311
+ raise NotImplementedError("MRV set computation for functions in"
312
+ " several variables not implemented.")
313
+ s, ss = l2[0], SubsSet()
314
+ args = [ss.do_subs(x[1]) for x in l]
315
+ return s, e.func(*args)
316
+ elif e.is_Derivative:
317
+ raise NotImplementedError("MRV set computation for derivatives"
318
+ " not implemented yet.")
319
+ raise NotImplementedError(
320
+ "Don't know how to calculate the mrv of '%s'" % e)
321
+
322
+
323
+ def mrv_max3(f, expsf, g, expsg, union, expsboth, x):
324
+ """
325
+ Computes the maximum of two sets of expressions f and g, which
326
+ are in the same comparability class, i.e. max() compares (two elements of)
327
+ f and g and returns either (f, expsf) [if f is larger], (g, expsg)
328
+ [if g is larger] or (union, expsboth) [if f, g are of the same class].
329
+ """
330
+ if not isinstance(f, SubsSet):
331
+ raise TypeError("f should be an instance of SubsSet")
332
+ if not isinstance(g, SubsSet):
333
+ raise TypeError("g should be an instance of SubsSet")
334
+ if f == SubsSet():
335
+ return g, expsg
336
+ elif g == SubsSet():
337
+ return f, expsf
338
+ elif f.meets(g):
339
+ return union, expsboth
340
+
341
+ c = compare(list(f.keys())[0], list(g.keys())[0], x)
342
+ if c == ">":
343
+ return f, expsf
344
+ elif c == "<":
345
+ return g, expsg
346
+ else:
347
+ if c != "=":
348
+ raise ValueError("c should be =")
349
+ return union, expsboth
350
+
351
+
352
+ def mrv_max1(f, g, exps, x):
353
+ """Computes the maximum of two sets of expressions f and g, which
354
+ are in the same comparability class, i.e. mrv_max1() compares (two elements of)
355
+ f and g and returns the set, which is in the higher comparability class
356
+ of the union of both, if they have the same order of variation.
357
+ Also returns exps, with the appropriate substitutions made.
358
+ """
359
+ u, b = f.union(g, exps)
360
+ return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps),
361
+ u, b, x)
362
+
363
+
364
+ @debug
365
+ @cacheit
366
+ @timeit
367
+ def sign(e, x):
368
+ """
369
+ Returns a sign of an expression e(x) for x->oo.
370
+
371
+ ::
372
+
373
+ e > 0 for x sufficiently large ... 1
374
+ e == 0 for x sufficiently large ... 0
375
+ e < 0 for x sufficiently large ... -1
376
+
377
+ The result of this function is currently undefined if e changes sign
378
+ arbitrarily often for arbitrarily large x (e.g. sin(x)).
379
+
380
+ Note that this returns zero only if e is *constantly* zero
381
+ for x sufficiently large. [If e is constant, of course, this is just
382
+ the same thing as the sign of e.]
383
+ """
384
+ if not isinstance(e, Basic):
385
+ raise TypeError("e should be an instance of Basic")
386
+
387
+ if e.is_positive:
388
+ return 1
389
+ elif e.is_negative:
390
+ return -1
391
+ elif e.is_zero:
392
+ return 0
393
+
394
+ elif not e.has(x):
395
+ from sympy.simplify import logcombine
396
+ e = logcombine(e)
397
+ return _sign(e)
398
+ elif e == x:
399
+ return 1
400
+ elif e.is_Mul:
401
+ a, b = e.as_two_terms()
402
+ sa = sign(a, x)
403
+ if not sa:
404
+ return 0
405
+ return sa * sign(b, x)
406
+ elif isinstance(e, exp):
407
+ return 1
408
+ elif e.is_Pow:
409
+ if e.base == S.Exp1:
410
+ return 1
411
+ s = sign(e.base, x)
412
+ if s == 1:
413
+ return 1
414
+ if e.exp.is_Integer:
415
+ return s**e.exp
416
+ elif isinstance(e, log):
417
+ return sign(e.args[0] - 1, x)
418
+
419
+ # if all else fails, do it the hard way
420
+ c0, e0 = mrv_leadterm(e, x)
421
+ return sign(c0, x)
422
+
423
+
424
+ @debug
425
+ @timeit
426
+ @cacheit
427
+ def limitinf(e, x):
428
+ """Limit e(x) for x-> oo."""
429
+ # rewrite e in terms of tractable functions only
430
+
431
+ old = e
432
+ if not e.has(x):
433
+ return e # e is a constant
434
+ from sympy.simplify.powsimp import powdenest
435
+ from sympy.calculus.util import AccumBounds
436
+ if e.has(Order):
437
+ e = e.expand().removeO()
438
+ if not x.is_positive or x.is_integer:
439
+ # We make sure that x.is_positive is True and x.is_integer is None
440
+ # so we get all the correct mathematical behavior from the expression.
441
+ # We need a fresh variable.
442
+ p = Dummy('p', positive=True)
443
+ e = e.subs(x, p)
444
+ x = p
445
+ e = e.rewrite('tractable', deep=True, limitvar=x)
446
+ e = powdenest(e)
447
+ if isinstance(e, AccumBounds):
448
+ if mrv_leadterm(e.min, x) != mrv_leadterm(e.max, x):
449
+ raise NotImplementedError
450
+ c0, e0 = mrv_leadterm(e.min, x)
451
+ else:
452
+ c0, e0 = mrv_leadterm(e, x)
453
+ sig = sign(e0, x)
454
+ if sig == 1:
455
+ return S.Zero # e0>0: lim f = 0
456
+ elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0)
457
+ if c0.match(I*Wild("a", exclude=[I])):
458
+ return c0*oo
459
+ s = sign(c0, x)
460
+ # the leading term shouldn't be 0:
461
+ if s == 0:
462
+ raise ValueError("Leading term should not be 0")
463
+ return s*oo
464
+ elif sig == 0:
465
+ if c0 == old:
466
+ c0 = c0.cancel()
467
+ return limitinf(c0, x) # e0=0: lim f = lim c0
468
+ else:
469
+ raise ValueError("{} could not be evaluated".format(sig))
470
+
471
+
472
+ def moveup2(s, x):
473
+ r = SubsSet()
474
+ for expr, var in s.items():
475
+ r[expr.xreplace({x: exp(x)})] = var
476
+ for var, expr in s.rewrites.items():
477
+ r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
478
+ return r
479
+
480
+
481
+ def moveup(l, x):
482
+ return [e.xreplace({x: exp(x)}) for e in l]
483
+
484
+
485
+ @debug
486
+ @timeit
487
+ def calculate_series(e, x, logx=None):
488
+ """ Calculates at least one term of the series of ``e`` in ``x``.
489
+
490
+ This is a place that fails most often, so it is in its own function.
491
+ """
492
+
493
+ SymPyDeprecationWarning(
494
+ feature="calculate_series",
495
+ useinstead="series() with suitable n, or as_leading_term",
496
+ issue=21838,
497
+ deprecated_since_version="1.12"
498
+ ).warn()
499
+
500
+ from sympy.simplify.powsimp import powdenest
501
+
502
+ for t in e.lseries(x, logx=logx):
503
+ # bottom_up function is required for a specific case - when e is
504
+ # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p)
505
+ t = bottom_up(t, lambda w:
506
+ getattr(w, 'normal', lambda: w)())
507
+ # And the expression
508
+ # `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)`
509
+ # from the first test of test_gruntz_eval_special needs to
510
+ # be expanded. But other forms need to be have at least
511
+ # factor_terms applied. `factor` accomplishes both and is
512
+ # faster than using `factor_terms` for the gruntz suite. It
513
+ # does not appear that use of `cancel` is necessary.
514
+ # t = cancel(t, expand=False)
515
+ t = t.factor()
516
+
517
+ if t.has(exp) and t.has(log):
518
+ t = powdenest(t)
519
+
520
+ if not t.is_zero:
521
+ break
522
+
523
+ return t
524
+
525
+
526
+ @debug
527
+ @timeit
528
+ @cacheit
529
+ def mrv_leadterm(e, x):
530
+ """Returns (c0, e0) for e."""
531
+ Omega = SubsSet()
532
+ if not e.has(x):
533
+ return (e, S.Zero)
534
+ if Omega == SubsSet():
535
+ Omega, exps = mrv(e, x)
536
+ if not Omega:
537
+ # e really does not depend on x after simplification
538
+ return exps, S.Zero
539
+ if x in Omega:
540
+ # move the whole omega up (exponentiate each term):
541
+ Omega_up = moveup2(Omega, x)
542
+ exps_up = moveup([exps], x)[0]
543
+ # NOTE: there is no need to move this down!
544
+ Omega = Omega_up
545
+ exps = exps_up
546
+ #
547
+ # The positive dummy, w, is used here so log(w*2) etc. will expand;
548
+ # a unique dummy is needed in this algorithm
549
+ #
550
+ # For limits of complex functions, the algorithm would have to be
551
+ # improved, or just find limits of Re and Im components separately.
552
+ #
553
+ w = Dummy("w", positive=True)
554
+ f, logw = rewrite(exps, Omega, x, w)
555
+ try:
556
+ lt = f.leadterm(w, logx=logw)
557
+ except (NotImplementedError, PoleError, ValueError):
558
+ n0 = 1
559
+ _series = Order(1)
560
+ incr = S.One
561
+ while _series.is_Order:
562
+ _series = f._eval_nseries(w, n=n0+incr, logx=logw)
563
+ incr *= 2
564
+ series = _series.expand().removeO()
565
+ try:
566
+ lt = series.leadterm(w, logx=logw)
567
+ except (NotImplementedError, PoleError, ValueError):
568
+ lt = f.as_coeff_exponent(w)
569
+ if lt[0].has(w):
570
+ base = f.as_base_exp()[0].as_coeff_exponent(w)
571
+ ex = f.as_base_exp()[1]
572
+ lt = (base[0]**ex, base[1]*ex)
573
+ return (lt[0].subs(log(w), logw), lt[1])
574
+
575
+
576
+ def build_expression_tree(Omega, rewrites):
577
+ r""" Helper function for rewrite.
578
+
579
+ We need to sort Omega (mrv set) so that we replace an expression before
580
+ we replace any expression in terms of which it has to be rewritten::
581
+
582
+ e1 ---> e2 ---> e3
583
+ \
584
+ -> e4
585
+
586
+ Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
587
+ To do this we assemble the nodes into a tree, and sort them by height.
588
+
589
+ This function builds the tree, rewrites then sorts the nodes.
590
+ """
591
+ class Node:
592
+ def __init__(self):
593
+ self.before = []
594
+ self.expr = None
595
+ self.var = None
596
+ def ht(self):
597
+ return reduce(lambda x, y: x + y,
598
+ [x.ht() for x in self.before], 1)
599
+ nodes = {}
600
+ for expr, v in Omega:
601
+ n = Node()
602
+ n.var = v
603
+ n.expr = expr
604
+ nodes[v] = n
605
+ for _, v in Omega:
606
+ if v in rewrites:
607
+ n = nodes[v]
608
+ r = rewrites[v]
609
+ for _, v2 in Omega:
610
+ if r.has(v2):
611
+ n.before.append(nodes[v2])
612
+
613
+ return nodes
614
+
615
+
616
+ @debug
617
+ @timeit
618
+ def rewrite(e, Omega, x, wsym):
619
+ """e(x) ... the function
620
+ Omega ... the mrv set
621
+ wsym ... the symbol which is going to be used for w
622
+
623
+ Returns the rewritten e in terms of w and log(w). See test_rewrite1()
624
+ for examples and correct results.
625
+ """
626
+
627
+ from sympy import AccumBounds
628
+ if not isinstance(Omega, SubsSet):
629
+ raise TypeError("Omega should be an instance of SubsSet")
630
+ if len(Omega) == 0:
631
+ raise ValueError("Length cannot be 0")
632
+ # all items in Omega must be exponentials
633
+ for t in Omega.keys():
634
+ if not isinstance(t, exp):
635
+ raise ValueError("Value should be exp")
636
+ rewrites = Omega.rewrites
637
+ Omega = list(Omega.items())
638
+
639
+ nodes = build_expression_tree(Omega, rewrites)
640
+ Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
641
+
642
+ # make sure we know the sign of each exp() term; after the loop,
643
+ # g is going to be the "w" - the simplest one in the mrv set
644
+ for g, _ in Omega:
645
+ sig = sign(g.exp, x)
646
+ if sig != 1 and sig != -1 and not sig.has(AccumBounds):
647
+ raise NotImplementedError('Result depends on the sign of %s' % sig)
648
+ if sig == 1:
649
+ wsym = 1/wsym # if g goes to oo, substitute 1/w
650
+ # O2 is a list, which results by rewriting each item in Omega using "w"
651
+ O2 = []
652
+ denominators = []
653
+ for f, var in Omega:
654
+ c = limitinf(f.exp/g.exp, x)
655
+ if c.is_Rational:
656
+ denominators.append(c.q)
657
+ arg = f.exp
658
+ if var in rewrites:
659
+ if not isinstance(rewrites[var], exp):
660
+ raise ValueError("Value should be exp")
661
+ arg = rewrites[var].args[0]
662
+ O2.append((var, exp((arg - c*g.exp).expand())*wsym**c))
663
+
664
+ # Remember that Omega contains subexpressions of "e". So now we find
665
+ # them in "e" and substitute them for our rewriting, stored in O2
666
+
667
+ # the following powsimp is necessary to automatically combine exponentials,
668
+ # so that the .xreplace() below succeeds:
669
+ # TODO this should not be necessary
670
+ from sympy.simplify.powsimp import powsimp
671
+ f = powsimp(e, deep=True, combine='exp')
672
+ for a, b in O2:
673
+ f = f.xreplace({a: b})
674
+
675
+ for _, var in Omega:
676
+ assert not f.has(var)
677
+
678
+ # finally compute the logarithm of w (logw).
679
+ logw = g.exp
680
+ if sig == 1:
681
+ logw = -logw # log(w)->log(1/w)=-log(w)
682
+
683
+ # Some parts of SymPy have difficulty computing series expansions with
684
+ # non-integral exponents. The following heuristic improves the situation:
685
+ exponent = reduce(ilcm, denominators, 1)
686
+ f = f.subs({wsym: wsym**exponent})
687
+ logw /= exponent
688
+
689
+ # bottom_up function is required for a specific case - when f is
690
+ # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p). No current simplification
691
+ # methods reduce this to 0 while not expanding polynomials.
692
+ f = bottom_up(f, lambda w: getattr(w, 'normal', lambda: w)())
693
+ f = expand_mul(f)
694
+
695
+ return f, logw
696
+
697
+
698
+ def gruntz(e, z, z0, dir="+"):
699
+ """
700
+ Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
701
+
702
+ Explanation
703
+ ===========
704
+
705
+ ``z0`` can be any expression, including oo and -oo.
706
+
707
+ For ``dir="+"`` (default) it calculates the limit from the right
708
+ (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
709
+ (oo or -oo), the dir argument does not matter.
710
+
711
+ This algorithm is fully described in the module docstring in the gruntz.py
712
+ file. It relies heavily on the series expansion. Most frequently, gruntz()
713
+ is only used if the faster limit() function (which uses heuristics) fails.
714
+ """
715
+ if not z.is_symbol:
716
+ raise NotImplementedError("Second argument must be a Symbol")
717
+
718
+ # convert all limits to the limit z->oo; sign of z is handled in limitinf
719
+ r = None
720
+ if z0 in (oo, I*oo):
721
+ e0 = e
722
+ elif z0 in (-oo, -I*oo):
723
+ e0 = e.subs(z, -z)
724
+ else:
725
+ if str(dir) == "-":
726
+ e0 = e.subs(z, z0 - 1/z)
727
+ elif str(dir) == "+":
728
+ e0 = e.subs(z, z0 + 1/z)
729
+ else:
730
+ raise NotImplementedError("dir must be '+' or '-'")
731
+
732
+ r = limitinf(e0, z)
733
+
734
+ # This is a bit of a heuristic for nice results... we always rewrite
735
+ # tractable functions in terms of familiar intractable ones.
736
+ # It might be nicer to rewrite the exactly to what they were initially,
737
+ # but that would take some work to implement.
738
+ return r.rewrite('intractable', deep=True)
env-llmeval/lib/python3.10/site-packages/sympy/series/kauers.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def finite_diff(expression, variable, increment=1):
2
+ """
3
+ Takes as input a polynomial expression and the variable used to construct
4
+ it and returns the difference between function's value when the input is
5
+ incremented to 1 and the original function value. If you want an increment
6
+ other than one supply it as a third argument.
7
+
8
+ Examples
9
+ ========
10
+
11
+ >>> from sympy.abc import x, y, z
12
+ >>> from sympy.series.kauers import finite_diff
13
+ >>> finite_diff(x**2, x)
14
+ 2*x + 1
15
+ >>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y)
16
+ 3*y**2 + 7*y + 6
17
+ >>> finite_diff(x**2 + 3*x + 8, x, 2)
18
+ 4*x + 10
19
+ >>> finite_diff(z**3 + 8*z, z, 3)
20
+ 9*z**2 + 27*z + 51
21
+ """
22
+ expression = expression.expand()
23
+ expression2 = expression.subs(variable, variable + increment)
24
+ expression2 = expression2.expand()
25
+ return expression2 - expression
26
+
27
+ def finite_diff_kauers(sum):
28
+ """
29
+ Takes as input a Sum instance and returns the difference between the sum
30
+ with the upper index incremented by 1 and the original sum. For example,
31
+ if S(n) is a sum, then finite_diff_kauers will return S(n + 1) - S(n).
32
+
33
+ Examples
34
+ ========
35
+
36
+ >>> from sympy.series.kauers import finite_diff_kauers
37
+ >>> from sympy import Sum
38
+ >>> from sympy.abc import x, y, m, n, k
39
+ >>> finite_diff_kauers(Sum(k, (k, 1, n)))
40
+ n + 1
41
+ >>> finite_diff_kauers(Sum(1/k, (k, 1, n)))
42
+ 1/(n + 1)
43
+ >>> finite_diff_kauers(Sum((x*y**2), (x, 1, n), (y, 1, m)))
44
+ (m + 1)**2*(n + 1)
45
+ >>> finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n)))
46
+ (m + 1)*(n + 1)
47
+ """
48
+ function = sum.function
49
+ for l in sum.limits:
50
+ function = function.subs(l[0], l[- 1] + 1)
51
+ return function
env-llmeval/lib/python3.10/site-packages/sympy/series/limits.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul
3
+ from sympy.core.exprtools import factor_terms
4
+ from sympy.core.numbers import Float, _illegal
5
+ from sympy.functions.combinatorial.factorials import factorial
6
+ from sympy.functions.elementary.complexes import (Abs, sign, arg, re)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.special.gamma_functions import gamma
9
+ from sympy.polys import PolynomialError, factor
10
+ from sympy.series.order import Order
11
+ from .gruntz import gruntz
12
+
13
+ def limit(e, z, z0, dir="+"):
14
+ """Computes the limit of ``e(z)`` at the point ``z0``.
15
+
16
+ Parameters
17
+ ==========
18
+
19
+ e : expression, the limit of which is to be taken
20
+
21
+ z : symbol representing the variable in the limit.
22
+ Other symbols are treated as constants. Multivariate limits
23
+ are not supported.
24
+
25
+ z0 : the value toward which ``z`` tends. Can be any expression,
26
+ including ``oo`` and ``-oo``.
27
+
28
+ dir : string, optional (default: "+")
29
+ The limit is bi-directional if ``dir="+-"``, from the right
30
+ (z->z0+) if ``dir="+"``, and from the left (z->z0-) if
31
+ ``dir="-"``. For infinite ``z0`` (``oo`` or ``-oo``), the ``dir``
32
+ argument is determined from the direction of the infinity
33
+ (i.e., ``dir="-"`` for ``oo``).
34
+
35
+ Examples
36
+ ========
37
+
38
+ >>> from sympy import limit, sin, oo
39
+ >>> from sympy.abc import x
40
+ >>> limit(sin(x)/x, x, 0)
41
+ 1
42
+ >>> limit(1/x, x, 0) # default dir='+'
43
+ oo
44
+ >>> limit(1/x, x, 0, dir="-")
45
+ -oo
46
+ >>> limit(1/x, x, 0, dir='+-')
47
+ zoo
48
+ >>> limit(1/x, x, oo)
49
+ 0
50
+
51
+ Notes
52
+ =====
53
+
54
+ First we try some heuristics for easy and frequent cases like "x", "1/x",
55
+ "x**2" and similar, so that it's fast. For all other cases, we use the
56
+ Gruntz algorithm (see the gruntz() function).
57
+
58
+ See Also
59
+ ========
60
+
61
+ limit_seq : returns the limit of a sequence.
62
+ """
63
+
64
+ return Limit(e, z, z0, dir).doit(deep=False)
65
+
66
+
67
+ def heuristics(e, z, z0, dir):
68
+ """Computes the limit of an expression term-wise.
69
+ Parameters are the same as for the ``limit`` function.
70
+ Works with the arguments of expression ``e`` one by one, computing
71
+ the limit of each and then combining the results. This approach
72
+ works only for simple limits, but it is fast.
73
+ """
74
+
75
+ rv = None
76
+ if z0 is S.Infinity:
77
+ rv = limit(e.subs(z, 1/z), z, S.Zero, "+")
78
+ if isinstance(rv, Limit):
79
+ return
80
+ elif e.is_Mul or e.is_Add or e.is_Pow or e.is_Function:
81
+ r = []
82
+ from sympy.simplify.simplify import together
83
+ for a in e.args:
84
+ l = limit(a, z, z0, dir)
85
+ if l.has(S.Infinity) and l.is_finite is None:
86
+ if isinstance(e, Add):
87
+ m = factor_terms(e)
88
+ if not isinstance(m, Mul): # try together
89
+ m = together(m)
90
+ if not isinstance(m, Mul): # try factor if the previous methods failed
91
+ m = factor(e)
92
+ if isinstance(m, Mul):
93
+ return heuristics(m, z, z0, dir)
94
+ return
95
+ return
96
+ elif isinstance(l, Limit):
97
+ return
98
+ elif l is S.NaN:
99
+ return
100
+ else:
101
+ r.append(l)
102
+ if r:
103
+ rv = e.func(*r)
104
+ if rv is S.NaN and e.is_Mul and any(isinstance(rr, AccumBounds) for rr in r):
105
+ r2 = []
106
+ e2 = []
107
+ for ii, rval in enumerate(r):
108
+ if isinstance(rval, AccumBounds):
109
+ r2.append(rval)
110
+ else:
111
+ e2.append(e.args[ii])
112
+
113
+ if len(e2) > 0:
114
+ e3 = Mul(*e2).simplify()
115
+ l = limit(e3, z, z0, dir)
116
+ rv = l * Mul(*r2)
117
+
118
+ if rv is S.NaN:
119
+ try:
120
+ from sympy.simplify.ratsimp import ratsimp
121
+ rat_e = ratsimp(e)
122
+ except PolynomialError:
123
+ return
124
+ if rat_e is S.NaN or rat_e == e:
125
+ return
126
+ return limit(rat_e, z, z0, dir)
127
+ return rv
128
+
129
+
130
+ class Limit(Expr):
131
+ """Represents an unevaluated limit.
132
+
133
+ Examples
134
+ ========
135
+
136
+ >>> from sympy import Limit, sin
137
+ >>> from sympy.abc import x
138
+ >>> Limit(sin(x)/x, x, 0)
139
+ Limit(sin(x)/x, x, 0, dir='+')
140
+ >>> Limit(1/x, x, 0, dir="-")
141
+ Limit(1/x, x, 0, dir='-')
142
+
143
+ """
144
+
145
+ def __new__(cls, e, z, z0, dir="+"):
146
+ e = sympify(e)
147
+ z = sympify(z)
148
+ z0 = sympify(z0)
149
+
150
+ if z0 in (S.Infinity, S.ImaginaryUnit*S.Infinity):
151
+ dir = "-"
152
+ elif z0 in (S.NegativeInfinity, S.ImaginaryUnit*S.NegativeInfinity):
153
+ dir = "+"
154
+
155
+ if(z0.has(z)):
156
+ raise NotImplementedError("Limits approaching a variable point are"
157
+ " not supported (%s -> %s)" % (z, z0))
158
+ if isinstance(dir, str):
159
+ dir = Symbol(dir)
160
+ elif not isinstance(dir, Symbol):
161
+ raise TypeError("direction must be of type basestring or "
162
+ "Symbol, not %s" % type(dir))
163
+ if str(dir) not in ('+', '-', '+-'):
164
+ raise ValueError("direction must be one of '+', '-' "
165
+ "or '+-', not %s" % dir)
166
+
167
+ obj = Expr.__new__(cls)
168
+ obj._args = (e, z, z0, dir)
169
+ return obj
170
+
171
+
172
+ @property
173
+ def free_symbols(self):
174
+ e = self.args[0]
175
+ isyms = e.free_symbols
176
+ isyms.difference_update(self.args[1].free_symbols)
177
+ isyms.update(self.args[2].free_symbols)
178
+ return isyms
179
+
180
+
181
+ def pow_heuristics(self, e):
182
+ _, z, z0, _ = self.args
183
+ b1, e1 = e.base, e.exp
184
+ if not b1.has(z):
185
+ res = limit(e1*log(b1), z, z0)
186
+ return exp(res)
187
+
188
+ ex_lim = limit(e1, z, z0)
189
+ base_lim = limit(b1, z, z0)
190
+
191
+ if base_lim is S.One:
192
+ if ex_lim in (S.Infinity, S.NegativeInfinity):
193
+ res = limit(e1*(b1 - 1), z, z0)
194
+ return exp(res)
195
+ if base_lim is S.NegativeInfinity and ex_lim is S.Infinity:
196
+ return S.ComplexInfinity
197
+
198
+
199
+ def doit(self, **hints):
200
+ """Evaluates the limit.
201
+
202
+ Parameters
203
+ ==========
204
+
205
+ deep : bool, optional (default: True)
206
+ Invoke the ``doit`` method of the expressions involved before
207
+ taking the limit.
208
+
209
+ hints : optional keyword arguments
210
+ To be passed to ``doit`` methods; only used if deep is True.
211
+ """
212
+
213
+ e, z, z0, dir = self.args
214
+
215
+ if str(dir) == '+-':
216
+ r = limit(e, z, z0, dir='+')
217
+ l = limit(e, z, z0, dir='-')
218
+ if isinstance(r, Limit) and isinstance(l, Limit):
219
+ if r.args[0] == l.args[0]:
220
+ return self
221
+ if r == l:
222
+ return l
223
+ if r.is_infinite and l.is_infinite:
224
+ return S.ComplexInfinity
225
+ raise ValueError("The limit does not exist since "
226
+ "left hand limit = %s and right hand limit = %s"
227
+ % (l, r))
228
+
229
+ if z0 is S.ComplexInfinity:
230
+ raise NotImplementedError("Limits at complex "
231
+ "infinity are not implemented")
232
+
233
+ if z0.is_infinite:
234
+ cdir = sign(z0)
235
+ cdir = cdir/abs(cdir)
236
+ e = e.subs(z, cdir*z)
237
+ dir = "-"
238
+ z0 = S.Infinity
239
+
240
+ if hints.get('deep', True):
241
+ e = e.doit(**hints)
242
+ z = z.doit(**hints)
243
+ z0 = z0.doit(**hints)
244
+
245
+ if e == z:
246
+ return z0
247
+
248
+ if not e.has(z):
249
+ return e
250
+
251
+ if z0 is S.NaN:
252
+ return S.NaN
253
+
254
+ if e.has(*_illegal):
255
+ return self
256
+
257
+ if e.is_Order:
258
+ return Order(limit(e.expr, z, z0), *e.args[1:])
259
+
260
+ cdir = 0
261
+ if str(dir) == "+":
262
+ cdir = 1
263
+ elif str(dir) == "-":
264
+ cdir = -1
265
+
266
+ def set_signs(expr):
267
+ if not expr.args:
268
+ return expr
269
+ newargs = tuple(set_signs(arg) for arg in expr.args)
270
+ if newargs != expr.args:
271
+ expr = expr.func(*newargs)
272
+ abs_flag = isinstance(expr, Abs)
273
+ arg_flag = isinstance(expr, arg)
274
+ sign_flag = isinstance(expr, sign)
275
+ if abs_flag or sign_flag or arg_flag:
276
+ sig = limit(expr.args[0], z, z0, dir)
277
+ if sig.is_zero:
278
+ sig = limit(1/expr.args[0], z, z0, dir)
279
+ if sig.is_extended_real:
280
+ if (sig < 0) == True:
281
+ return (-expr.args[0] if abs_flag else
282
+ S.NegativeOne if sign_flag else S.Pi)
283
+ elif (sig > 0) == True:
284
+ return (expr.args[0] if abs_flag else
285
+ S.One if sign_flag else S.Zero)
286
+ return expr
287
+
288
+ if e.has(Float):
289
+ # Convert floats like 0.5 to exact SymPy numbers like S.Half, to
290
+ # prevent rounding errors which can lead to unexpected execution
291
+ # of conditional blocks that work on comparisons
292
+ # Also see comments in https://github.com/sympy/sympy/issues/19453
293
+ from sympy.simplify.simplify import nsimplify
294
+ e = nsimplify(e)
295
+ e = set_signs(e)
296
+
297
+
298
+ if e.is_meromorphic(z, z0):
299
+ if z0 is S.Infinity:
300
+ newe = e.subs(z, 1/z)
301
+ # cdir changes sign as oo- should become 0+
302
+ cdir = -cdir
303
+ else:
304
+ newe = e.subs(z, z + z0)
305
+ try:
306
+ coeff, ex = newe.leadterm(z, cdir=cdir)
307
+ except ValueError:
308
+ pass
309
+ else:
310
+ if ex > 0:
311
+ return S.Zero
312
+ elif ex == 0:
313
+ return coeff
314
+ if cdir == 1 or not(int(ex) & 1):
315
+ return S.Infinity*sign(coeff)
316
+ elif cdir == -1:
317
+ return S.NegativeInfinity*sign(coeff)
318
+ else:
319
+ return S.ComplexInfinity
320
+
321
+ if z0 is S.Infinity:
322
+ if e.is_Mul:
323
+ e = factor_terms(e)
324
+ newe = e.subs(z, 1/z)
325
+ # cdir changes sign as oo- should become 0+
326
+ cdir = -cdir
327
+ else:
328
+ newe = e.subs(z, z + z0)
329
+ try:
330
+ coeff, ex = newe.leadterm(z, cdir=cdir)
331
+ except (ValueError, NotImplementedError, PoleError):
332
+ # The NotImplementedError catching is for custom functions
333
+ from sympy.simplify.powsimp import powsimp
334
+ e = powsimp(e)
335
+ if e.is_Pow:
336
+ r = self.pow_heuristics(e)
337
+ if r is not None:
338
+ return r
339
+ try:
340
+ coeff = newe.as_leading_term(z, cdir=cdir)
341
+ if coeff != newe and coeff.has(exp):
342
+ return gruntz(coeff, z, 0, "-" if re(cdir).is_negative else "+")
343
+ except (ValueError, NotImplementedError, PoleError):
344
+ pass
345
+ else:
346
+ if isinstance(coeff, AccumBounds) and ex == S.Zero:
347
+ return coeff
348
+ if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
349
+ return self
350
+ if not coeff.has(z):
351
+ if ex.is_positive:
352
+ return S.Zero
353
+ elif ex == 0:
354
+ return coeff
355
+ elif ex.is_negative:
356
+ if cdir == 1:
357
+ return S.Infinity*sign(coeff)
358
+ elif cdir == -1:
359
+ return S.NegativeInfinity*sign(coeff)*S.NegativeOne**(S.One + ex)
360
+ else:
361
+ return S.ComplexInfinity
362
+ else:
363
+ raise NotImplementedError("Not sure of sign of %s" % ex)
364
+
365
+ # gruntz fails on factorials but works with the gamma function
366
+ # If no factorial term is present, e should remain unchanged.
367
+ # factorial is defined to be zero for negative inputs (which
368
+ # differs from gamma) so only rewrite for positive z0.
369
+ if z0.is_extended_positive:
370
+ e = e.rewrite(factorial, gamma)
371
+
372
+ l = None
373
+
374
+ try:
375
+ r = gruntz(e, z, z0, dir)
376
+ if r is S.NaN or l is S.NaN:
377
+ raise PoleError()
378
+ except (PoleError, ValueError):
379
+ if l is not None:
380
+ raise
381
+ r = heuristics(e, z, z0, dir)
382
+ if r is None:
383
+ return self
384
+
385
+ return r
env-llmeval/lib/python3.10/site-packages/sympy/series/limitseq.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Limits of sequences"""
2
+
3
+ from sympy.calculus.accumulationbounds import AccumulationBounds
4
+ from sympy.core.add import Add
5
+ from sympy.core.function import PoleError
6
+ from sympy.core.power import Pow
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import Dummy
9
+ from sympy.core.sympify import sympify
10
+ from sympy.functions.combinatorial.numbers import fibonacci
11
+ from sympy.functions.combinatorial.factorials import factorial, subfactorial
12
+ from sympy.functions.special.gamma_functions import gamma
13
+ from sympy.functions.elementary.complexes import Abs
14
+ from sympy.functions.elementary.miscellaneous import Max, Min
15
+ from sympy.functions.elementary.trigonometric import cos, sin
16
+ from sympy.series.limits import Limit
17
+
18
+
19
+ def difference_delta(expr, n=None, step=1):
20
+ """Difference Operator.
21
+
22
+ Explanation
23
+ ===========
24
+
25
+ Discrete analog of differential operator. Given a sequence x[n],
26
+ returns the sequence x[n + step] - x[n].
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy import difference_delta as dd
32
+ >>> from sympy.abc import n
33
+ >>> dd(n*(n + 1), n)
34
+ 2*n + 2
35
+ >>> dd(n*(n + 1), n, 2)
36
+ 4*n + 6
37
+
38
+ References
39
+ ==========
40
+
41
+ .. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html
42
+ """
43
+ expr = sympify(expr)
44
+
45
+ if n is None:
46
+ f = expr.free_symbols
47
+ if len(f) == 1:
48
+ n = f.pop()
49
+ elif len(f) == 0:
50
+ return S.Zero
51
+ else:
52
+ raise ValueError("Since there is more than one variable in the"
53
+ " expression, a variable must be supplied to"
54
+ " take the difference of %s" % expr)
55
+ step = sympify(step)
56
+ if step.is_number is False or step.is_finite is False:
57
+ raise ValueError("Step should be a finite number.")
58
+
59
+ if hasattr(expr, '_eval_difference_delta'):
60
+ result = expr._eval_difference_delta(n, step)
61
+ if result:
62
+ return result
63
+
64
+ return expr.subs(n, n + step) - expr
65
+
66
+
67
+ def dominant(expr, n):
68
+ """Finds the dominant term in a sum, that is a term that dominates
69
+ every other term.
70
+
71
+ Explanation
72
+ ===========
73
+
74
+ If limit(a/b, n, oo) is oo then a dominates b.
75
+ If limit(a/b, n, oo) is 0 then b dominates a.
76
+ Otherwise, a and b are comparable.
77
+
78
+ If there is no unique dominant term, then returns ``None``.
79
+
80
+ Examples
81
+ ========
82
+
83
+ >>> from sympy import Sum
84
+ >>> from sympy.series.limitseq import dominant
85
+ >>> from sympy.abc import n, k
86
+ >>> dominant(5*n**3 + 4*n**2 + n + 1, n)
87
+ 5*n**3
88
+ >>> dominant(2**n + Sum(k, (k, 0, n)), n)
89
+ 2**n
90
+
91
+ See Also
92
+ ========
93
+
94
+ sympy.series.limitseq.dominant
95
+ """
96
+ terms = Add.make_args(expr.expand(func=True))
97
+ term0 = terms[-1]
98
+ comp = [term0] # comparable terms
99
+ for t in terms[:-1]:
100
+ r = term0/t
101
+ e = r.gammasimp()
102
+ if e == r:
103
+ e = r.factor()
104
+ l = limit_seq(e, n)
105
+ if l is None:
106
+ return None
107
+ elif l.is_zero:
108
+ term0 = t
109
+ comp = [term0]
110
+ elif l not in [S.Infinity, S.NegativeInfinity]:
111
+ comp.append(t)
112
+ if len(comp) > 1:
113
+ return None
114
+ return term0
115
+
116
+
117
+ def _limit_inf(expr, n):
118
+ try:
119
+ return Limit(expr, n, S.Infinity).doit(deep=False)
120
+ except (NotImplementedError, PoleError):
121
+ return None
122
+
123
+
124
+ def _limit_seq(expr, n, trials):
125
+ from sympy.concrete.summations import Sum
126
+
127
+ for i in range(trials):
128
+ if not expr.has(Sum):
129
+ result = _limit_inf(expr, n)
130
+ if result is not None:
131
+ return result
132
+
133
+ num, den = expr.as_numer_denom()
134
+ if not den.has(n) or not num.has(n):
135
+ result = _limit_inf(expr.doit(), n)
136
+ if result is not None:
137
+ return result
138
+ return None
139
+
140
+ num, den = (difference_delta(t.expand(), n) for t in [num, den])
141
+ expr = (num / den).gammasimp()
142
+
143
+ if not expr.has(Sum):
144
+ result = _limit_inf(expr, n)
145
+ if result is not None:
146
+ return result
147
+
148
+ num, den = expr.as_numer_denom()
149
+
150
+ num = dominant(num, n)
151
+ if num is None:
152
+ return None
153
+
154
+ den = dominant(den, n)
155
+ if den is None:
156
+ return None
157
+
158
+ expr = (num / den).gammasimp()
159
+
160
+
161
+ def limit_seq(expr, n=None, trials=5):
162
+ """Finds the limit of a sequence as index ``n`` tends to infinity.
163
+
164
+ Parameters
165
+ ==========
166
+
167
+ expr : Expr
168
+ SymPy expression for the ``n-th`` term of the sequence
169
+ n : Symbol, optional
170
+ The index of the sequence, an integer that tends to positive
171
+ infinity. If None, inferred from the expression unless it has
172
+ multiple symbols.
173
+ trials: int, optional
174
+ The algorithm is highly recursive. ``trials`` is a safeguard from
175
+ infinite recursion in case the limit is not easily computed by the
176
+ algorithm. Try increasing ``trials`` if the algorithm returns ``None``.
177
+
178
+ Admissible Terms
179
+ ================
180
+
181
+ The algorithm is designed for sequences built from rational functions,
182
+ indefinite sums, and indefinite products over an indeterminate n. Terms of
183
+ alternating sign are also allowed, but more complex oscillatory behavior is
184
+ not supported.
185
+
186
+ Examples
187
+ ========
188
+
189
+ >>> from sympy import limit_seq, Sum, binomial
190
+ >>> from sympy.abc import n, k, m
191
+ >>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)
192
+ 5/3
193
+ >>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)
194
+ 3/4
195
+ >>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)
196
+ 4
197
+
198
+ See Also
199
+ ========
200
+
201
+ sympy.series.limitseq.dominant
202
+
203
+ References
204
+ ==========
205
+
206
+ .. [1] Computing Limits of Sequences - Manuel Kauers
207
+ """
208
+
209
+ from sympy.concrete.summations import Sum
210
+ if n is None:
211
+ free = expr.free_symbols
212
+ if len(free) == 1:
213
+ n = free.pop()
214
+ elif not free:
215
+ return expr
216
+ else:
217
+ raise ValueError("Expression has more than one variable. "
218
+ "Please specify a variable.")
219
+ elif n not in expr.free_symbols:
220
+ return expr
221
+
222
+ expr = expr.rewrite(fibonacci, S.GoldenRatio)
223
+ expr = expr.rewrite(factorial, subfactorial, gamma)
224
+ n_ = Dummy("n", integer=True, positive=True)
225
+ n1 = Dummy("n", odd=True, positive=True)
226
+ n2 = Dummy("n", even=True, positive=True)
227
+
228
+ # If there is a negative term raised to a power involving n, or a
229
+ # trigonometric function, then consider even and odd n separately.
230
+ powers = (p.as_base_exp() for p in expr.atoms(Pow))
231
+ if (any(b.is_negative and e.has(n) for b, e in powers) or
232
+ expr.has(cos, sin)):
233
+ L1 = _limit_seq(expr.xreplace({n: n1}), n1, trials)
234
+ if L1 is not None:
235
+ L2 = _limit_seq(expr.xreplace({n: n2}), n2, trials)
236
+ if L1 != L2:
237
+ if L1.is_comparable and L2.is_comparable:
238
+ return AccumulationBounds(Min(L1, L2), Max(L1, L2))
239
+ else:
240
+ return None
241
+ else:
242
+ L1 = _limit_seq(expr.xreplace({n: n_}), n_, trials)
243
+ if L1 is not None:
244
+ return L1
245
+ else:
246
+ if expr.is_Add:
247
+ limits = [limit_seq(term, n, trials) for term in expr.args]
248
+ if any(result is None for result in limits):
249
+ return None
250
+ else:
251
+ return Add(*limits)
252
+ # Maybe the absolute value is easier to deal with (though not if
253
+ # it has a Sum). If it tends to 0, the limit is 0.
254
+ elif not expr.has(Sum):
255
+ lim = _limit_seq(Abs(expr.xreplace({n: n_})), n_, trials)
256
+ if lim is not None and lim.is_zero:
257
+ return S.Zero
env-llmeval/lib/python3.10/site-packages/sympy/series/order.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, sympify, Expr, Dummy, Add, Mul
2
+ from sympy.core.cache import cacheit
3
+ from sympy.core.containers import Tuple
4
+ from sympy.core.function import Function, PoleError, expand_power_base, expand_log
5
+ from sympy.core.sorting import default_sort_key
6
+ from sympy.functions.elementary.exponential import exp, log
7
+ from sympy.sets.sets import Complement
8
+ from sympy.utilities.iterables import uniq, is_sequence
9
+
10
+
11
+ class Order(Expr):
12
+ r""" Represents the limiting behavior of some function.
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ The order of a function characterizes the function based on the limiting
18
+ behavior of the function as it goes to some limit. Only taking the limit
19
+ point to be a number is currently supported. This is expressed in
20
+ big O notation [1]_.
21
+
22
+ The formal definition for the order of a function `g(x)` about a point `a`
23
+ is such that `g(x) = O(f(x))` as `x \rightarrow a` if and only if there
24
+ exists a `\delta > 0` and an `M > 0` such that `|g(x)| \leq M|f(x)|` for
25
+ `|x-a| < \delta`. This is equivalent to `\limsup_{x \rightarrow a}
26
+ |g(x)/f(x)| < \infty`.
27
+
28
+ Let's illustrate it on the following example by taking the expansion of
29
+ `\sin(x)` about 0:
30
+
31
+ .. math ::
32
+ \sin(x) = x - x^3/3! + O(x^5)
33
+
34
+ where in this case `O(x^5) = x^5/5! - x^7/7! + \cdots`. By the definition
35
+ of `O`, there is a `\delta > 0` and an `M` such that:
36
+
37
+ .. math ::
38
+ |x^5/5! - x^7/7! + ....| <= M|x^5| \text{ for } |x| < \delta
39
+
40
+ or by the alternate definition:
41
+
42
+ .. math ::
43
+ \lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \infty
44
+
45
+ which surely is true, because
46
+
47
+ .. math ::
48
+ \lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5!
49
+
50
+
51
+ As it is usually used, the order of a function can be intuitively thought
52
+ of representing all terms of powers greater than the one specified. For
53
+ example, `O(x^3)` corresponds to any terms proportional to `x^3,
54
+ x^4,\ldots` and any higher power. For a polynomial, this leaves terms
55
+ proportional to `x^2`, `x` and constants.
56
+
57
+ Examples
58
+ ========
59
+
60
+ >>> from sympy import O, oo, cos, pi
61
+ >>> from sympy.abc import x, y
62
+
63
+ >>> O(x + x**2)
64
+ O(x)
65
+ >>> O(x + x**2, (x, 0))
66
+ O(x)
67
+ >>> O(x + x**2, (x, oo))
68
+ O(x**2, (x, oo))
69
+
70
+ >>> O(1 + x*y)
71
+ O(1, x, y)
72
+ >>> O(1 + x*y, (x, 0), (y, 0))
73
+ O(1, x, y)
74
+ >>> O(1 + x*y, (x, oo), (y, oo))
75
+ O(x*y, (x, oo), (y, oo))
76
+
77
+ >>> O(1) in O(1, x)
78
+ True
79
+ >>> O(1, x) in O(1)
80
+ False
81
+ >>> O(x) in O(1, x)
82
+ True
83
+ >>> O(x**2) in O(x)
84
+ True
85
+
86
+ >>> O(x)*x
87
+ O(x**2)
88
+ >>> O(x) - O(x)
89
+ O(x)
90
+ >>> O(cos(x))
91
+ O(1)
92
+ >>> O(cos(x), (x, pi/2))
93
+ O(x - pi/2, (x, pi/2))
94
+
95
+ References
96
+ ==========
97
+
98
+ .. [1] `Big O notation <https://en.wikipedia.org/wiki/Big_O_notation>`_
99
+
100
+ Notes
101
+ =====
102
+
103
+ In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading
104
+ term. ``O(f(x), x)`` is automatically transformed to
105
+ ``O(f(x).as_leading_term(x),x)``.
106
+
107
+ ``O(expr*f(x), x)`` is ``O(f(x), x)``
108
+
109
+ ``O(expr, x)`` is ``O(1)``
110
+
111
+ ``O(0, x)`` is 0.
112
+
113
+ Multivariate O is also supported:
114
+
115
+ ``O(f(x, y), x, y)`` is transformed to
116
+ ``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)``
117
+
118
+ In the multivariate case, it is assumed the limits w.r.t. the various
119
+ symbols commute.
120
+
121
+ If no symbols are passed then all symbols in the expression are used
122
+ and the limit point is assumed to be zero.
123
+
124
+ """
125
+
126
+ is_Order = True
127
+
128
+ __slots__ = ()
129
+
130
+ @cacheit
131
+ def __new__(cls, expr, *args, **kwargs):
132
+ expr = sympify(expr)
133
+
134
+ if not args:
135
+ if expr.is_Order:
136
+ variables = expr.variables
137
+ point = expr.point
138
+ else:
139
+ variables = list(expr.free_symbols)
140
+ point = [S.Zero]*len(variables)
141
+ else:
142
+ args = list(args if is_sequence(args) else [args])
143
+ variables, point = [], []
144
+ if is_sequence(args[0]):
145
+ for a in args:
146
+ v, p = list(map(sympify, a))
147
+ variables.append(v)
148
+ point.append(p)
149
+ else:
150
+ variables = list(map(sympify, args))
151
+ point = [S.Zero]*len(variables)
152
+
153
+ if not all(v.is_symbol for v in variables):
154
+ raise TypeError('Variables are not symbols, got %s' % variables)
155
+
156
+ if len(list(uniq(variables))) != len(variables):
157
+ raise ValueError('Variables are supposed to be unique symbols, got %s' % variables)
158
+
159
+ if expr.is_Order:
160
+ expr_vp = dict(expr.args[1:])
161
+ new_vp = dict(expr_vp)
162
+ vp = dict(zip(variables, point))
163
+ for v, p in vp.items():
164
+ if v in new_vp.keys():
165
+ if p != new_vp[v]:
166
+ raise NotImplementedError(
167
+ "Mixing Order at different points is not supported.")
168
+ else:
169
+ new_vp[v] = p
170
+ if set(expr_vp.keys()) == set(new_vp.keys()):
171
+ return expr
172
+ else:
173
+ variables = list(new_vp.keys())
174
+ point = [new_vp[v] for v in variables]
175
+
176
+ if expr is S.NaN:
177
+ return S.NaN
178
+
179
+ if any(x in p.free_symbols for x in variables for p in point):
180
+ raise ValueError('Got %s as a point.' % point)
181
+
182
+ if variables:
183
+ if any(p != point[0] for p in point):
184
+ raise NotImplementedError(
185
+ "Multivariable orders at different points are not supported.")
186
+ if point[0] in (S.Infinity, S.Infinity*S.ImaginaryUnit):
187
+ s = {k: 1/Dummy() for k in variables}
188
+ rs = {1/v: 1/k for k, v in s.items()}
189
+ ps = [S.Zero for p in point]
190
+ elif point[0] in (S.NegativeInfinity, S.NegativeInfinity*S.ImaginaryUnit):
191
+ s = {k: -1/Dummy() for k in variables}
192
+ rs = {-1/v: -1/k for k, v in s.items()}
193
+ ps = [S.Zero for p in point]
194
+ elif point[0] is not S.Zero:
195
+ s = {k: Dummy() + point[0] for k in variables}
196
+ rs = {(v - point[0]).together(): k - point[0] for k, v in s.items()}
197
+ ps = [S.Zero for p in point]
198
+ else:
199
+ s = ()
200
+ rs = ()
201
+ ps = list(point)
202
+
203
+ expr = expr.subs(s)
204
+
205
+ if expr.is_Add:
206
+ expr = expr.factor()
207
+
208
+ if s:
209
+ args = tuple([r[0] for r in rs.items()])
210
+ else:
211
+ args = tuple(variables)
212
+
213
+ if len(variables) > 1:
214
+ # XXX: better way? We need this expand() to
215
+ # workaround e.g: expr = x*(x + y).
216
+ # (x*(x + y)).as_leading_term(x, y) currently returns
217
+ # x*y (wrong order term!). That's why we want to deal with
218
+ # expand()'ed expr (handled in "if expr.is_Add" branch below).
219
+ expr = expr.expand()
220
+
221
+ old_expr = None
222
+ while old_expr != expr:
223
+ old_expr = expr
224
+ if expr.is_Add:
225
+ lst = expr.extract_leading_order(args)
226
+ expr = Add(*[f.expr for (e, f) in lst])
227
+
228
+ elif expr:
229
+ try:
230
+ expr = expr.as_leading_term(*args)
231
+ except PoleError:
232
+ if isinstance(expr, Function) or\
233
+ all(isinstance(arg, Function) for arg in expr.args):
234
+ # It is not possible to simplify an expression
235
+ # containing only functions (which raise error on
236
+ # call to leading term) further
237
+ pass
238
+ else:
239
+ orders = []
240
+ pts = tuple(zip(args, ps))
241
+ for arg in expr.args:
242
+ try:
243
+ lt = arg.as_leading_term(*args)
244
+ except PoleError:
245
+ lt = arg
246
+ if lt not in args:
247
+ order = Order(lt)
248
+ else:
249
+ order = Order(lt, *pts)
250
+ orders.append(order)
251
+ if expr.is_Add:
252
+ new_expr = Order(Add(*orders), *pts)
253
+ if new_expr.is_Add:
254
+ new_expr = Order(Add(*[a.expr for a in new_expr.args]), *pts)
255
+ expr = new_expr.expr
256
+ elif expr.is_Mul:
257
+ expr = Mul(*[a.expr for a in orders])
258
+ elif expr.is_Pow:
259
+ e = expr.exp
260
+ b = expr.base
261
+ expr = exp(e * log(b))
262
+
263
+ # It would probably be better to handle this somewhere
264
+ # else. This is needed for a testcase in which there is a
265
+ # symbol with the assumptions zero=True.
266
+ if expr.is_zero:
267
+ expr = S.Zero
268
+ else:
269
+ expr = expr.as_independent(*args, as_Add=False)[1]
270
+
271
+ expr = expand_power_base(expr)
272
+ expr = expand_log(expr)
273
+
274
+ if len(args) == 1:
275
+ # The definition of O(f(x)) symbol explicitly stated that
276
+ # the argument of f(x) is irrelevant. That's why we can
277
+ # combine some power exponents (only "on top" of the
278
+ # expression tree for f(x)), e.g.:
279
+ # x**p * (-x)**q -> x**(p+q) for real p, q.
280
+ x = args[0]
281
+ margs = list(Mul.make_args(
282
+ expr.as_independent(x, as_Add=False)[1]))
283
+
284
+ for i, t in enumerate(margs):
285
+ if t.is_Pow:
286
+ b, q = t.args
287
+ if b in (x, -x) and q.is_real and not q.has(x):
288
+ margs[i] = x**q
289
+ elif b.is_Pow and not b.exp.has(x):
290
+ b, r = b.args
291
+ if b in (x, -x) and r.is_real:
292
+ margs[i] = x**(r*q)
293
+ elif b.is_Mul and b.args[0] is S.NegativeOne:
294
+ b = -b
295
+ if b.is_Pow and not b.exp.has(x):
296
+ b, r = b.args
297
+ if b in (x, -x) and r.is_real:
298
+ margs[i] = x**(r*q)
299
+
300
+ expr = Mul(*margs)
301
+
302
+ expr = expr.subs(rs)
303
+
304
+ if expr.is_Order:
305
+ expr = expr.expr
306
+
307
+ if not expr.has(*variables) and not expr.is_zero:
308
+ expr = S.One
309
+
310
+ # create Order instance:
311
+ vp = dict(zip(variables, point))
312
+ variables.sort(key=default_sort_key)
313
+ point = [vp[v] for v in variables]
314
+ args = (expr,) + Tuple(*zip(variables, point))
315
+ obj = Expr.__new__(cls, *args)
316
+ return obj
317
+
318
+ def _eval_nseries(self, x, n, logx, cdir=0):
319
+ return self
320
+
321
+ @property
322
+ def expr(self):
323
+ return self.args[0]
324
+
325
+ @property
326
+ def variables(self):
327
+ if self.args[1:]:
328
+ return tuple(x[0] for x in self.args[1:])
329
+ else:
330
+ return ()
331
+
332
+ @property
333
+ def point(self):
334
+ if self.args[1:]:
335
+ return tuple(x[1] for x in self.args[1:])
336
+ else:
337
+ return ()
338
+
339
+ @property
340
+ def free_symbols(self):
341
+ return self.expr.free_symbols | set(self.variables)
342
+
343
+ def _eval_power(b, e):
344
+ if e.is_Number and e.is_nonnegative:
345
+ return b.func(b.expr ** e, *b.args[1:])
346
+ if e == O(1):
347
+ return b
348
+ return
349
+
350
+ def as_expr_variables(self, order_symbols):
351
+ if order_symbols is None:
352
+ order_symbols = self.args[1:]
353
+ else:
354
+ if (not all(o[1] == order_symbols[0][1] for o in order_symbols) and
355
+ not all(p == self.point[0] for p in self.point)): # pragma: no cover
356
+ raise NotImplementedError('Order at points other than 0 '
357
+ 'or oo not supported, got %s as a point.' % self.point)
358
+ if order_symbols and order_symbols[0][1] != self.point[0]:
359
+ raise NotImplementedError(
360
+ "Multiplying Order at different points is not supported.")
361
+ order_symbols = dict(order_symbols)
362
+ for s, p in dict(self.args[1:]).items():
363
+ if s not in order_symbols.keys():
364
+ order_symbols[s] = p
365
+ order_symbols = sorted(order_symbols.items(), key=lambda x: default_sort_key(x[0]))
366
+ return self.expr, tuple(order_symbols)
367
+
368
+ def removeO(self):
369
+ return S.Zero
370
+
371
+ def getO(self):
372
+ return self
373
+
374
+ @cacheit
375
+ def contains(self, expr):
376
+ r"""
377
+ Return True if expr belongs to Order(self.expr, \*self.variables).
378
+ Return False if self belongs to expr.
379
+ Return None if the inclusion relation cannot be determined
380
+ (e.g. when self and expr have different symbols).
381
+ """
382
+ expr = sympify(expr)
383
+ if expr.is_zero:
384
+ return True
385
+ if expr is S.NaN:
386
+ return False
387
+ point = self.point[0] if self.point else S.Zero
388
+ if expr.is_Order:
389
+ if (any(p != point for p in expr.point) or
390
+ any(p != point for p in self.point)):
391
+ return None
392
+ if expr.expr == self.expr:
393
+ # O(1) + O(1), O(1) + O(1, x), etc.
394
+ return all(x in self.args[1:] for x in expr.args[1:])
395
+ if expr.expr.is_Add:
396
+ return all(self.contains(x) for x in expr.expr.args)
397
+ if self.expr.is_Add and point.is_zero:
398
+ return any(self.func(x, *self.args[1:]).contains(expr)
399
+ for x in self.expr.args)
400
+ if self.variables and expr.variables:
401
+ common_symbols = tuple(
402
+ [s for s in self.variables if s in expr.variables])
403
+ elif self.variables:
404
+ common_symbols = self.variables
405
+ else:
406
+ common_symbols = expr.variables
407
+ if not common_symbols:
408
+ return None
409
+ if (self.expr.is_Pow and len(self.variables) == 1
410
+ and self.variables == expr.variables):
411
+ symbol = self.variables[0]
412
+ other = expr.expr.as_independent(symbol, as_Add=False)[1]
413
+ if (other.is_Pow and other.base == symbol and
414
+ self.expr.base == symbol):
415
+ if point.is_zero:
416
+ rv = (self.expr.exp - other.exp).is_nonpositive
417
+ if point.is_infinite:
418
+ rv = (self.expr.exp - other.exp).is_nonnegative
419
+ if rv is not None:
420
+ return rv
421
+
422
+ from sympy.simplify.powsimp import powsimp
423
+ r = None
424
+ ratio = self.expr/expr.expr
425
+ ratio = powsimp(ratio, deep=True, combine='exp')
426
+ for s in common_symbols:
427
+ from sympy.series.limits import Limit
428
+ l = Limit(ratio, s, point).doit(heuristics=False)
429
+ if not isinstance(l, Limit):
430
+ l = l != 0
431
+ else:
432
+ l = None
433
+ if r is None:
434
+ r = l
435
+ else:
436
+ if r != l:
437
+ return
438
+ return r
439
+
440
+ if self.expr.is_Pow and len(self.variables) == 1:
441
+ symbol = self.variables[0]
442
+ other = expr.as_independent(symbol, as_Add=False)[1]
443
+ if (other.is_Pow and other.base == symbol and
444
+ self.expr.base == symbol):
445
+ if point.is_zero:
446
+ rv = (self.expr.exp - other.exp).is_nonpositive
447
+ if point.is_infinite:
448
+ rv = (self.expr.exp - other.exp).is_nonnegative
449
+ if rv is not None:
450
+ return rv
451
+
452
+ obj = self.func(expr, *self.args[1:])
453
+ return self.contains(obj)
454
+
455
+ def __contains__(self, other):
456
+ result = self.contains(other)
457
+ if result is None:
458
+ raise TypeError('contains did not evaluate to a bool')
459
+ return result
460
+
461
+ def _eval_subs(self, old, new):
462
+ if old in self.variables:
463
+ newexpr = self.expr.subs(old, new)
464
+ i = self.variables.index(old)
465
+ newvars = list(self.variables)
466
+ newpt = list(self.point)
467
+ if new.is_symbol:
468
+ newvars[i] = new
469
+ else:
470
+ syms = new.free_symbols
471
+ if len(syms) == 1 or old in syms:
472
+ if old in syms:
473
+ var = self.variables[i]
474
+ else:
475
+ var = syms.pop()
476
+ # First, try to substitute self.point in the "new"
477
+ # expr to see if this is a fixed point.
478
+ # E.g. O(y).subs(y, sin(x))
479
+ point = new.subs(var, self.point[i])
480
+ if point != self.point[i]:
481
+ from sympy.solvers.solveset import solveset
482
+ d = Dummy()
483
+ sol = solveset(old - new.subs(var, d), d)
484
+ if isinstance(sol, Complement):
485
+ e1 = sol.args[0]
486
+ e2 = sol.args[1]
487
+ sol = set(e1) - set(e2)
488
+ res = [dict(zip((d, ), sol))]
489
+ point = d.subs(res[0]).limit(old, self.point[i])
490
+ newvars[i] = var
491
+ newpt[i] = point
492
+ elif old not in syms:
493
+ del newvars[i], newpt[i]
494
+ if not syms and new == self.point[i]:
495
+ newvars.extend(syms)
496
+ newpt.extend([S.Zero]*len(syms))
497
+ else:
498
+ return
499
+ return Order(newexpr, *zip(newvars, newpt))
500
+
501
+ def _eval_conjugate(self):
502
+ expr = self.expr._eval_conjugate()
503
+ if expr is not None:
504
+ return self.func(expr, *self.args[1:])
505
+
506
+ def _eval_derivative(self, x):
507
+ return self.func(self.expr.diff(x), *self.args[1:]) or self
508
+
509
+ def _eval_transpose(self):
510
+ expr = self.expr._eval_transpose()
511
+ if expr is not None:
512
+ return self.func(expr, *self.args[1:])
513
+
514
+ def __neg__(self):
515
+ return self
516
+
517
+ O = Order