applied-ai-018 commited on
Commit
3dd82bf
·
verified ·
1 Parent(s): 373249e

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. ckpts/universal/global_step120/zero/24.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step120/zero/5.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step120/zero/7.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
  4. venv/lib/python3.10/site-packages/sympy/concrete/__init__.py +8 -0
  5. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/__init__.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/delta.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_intlimits.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_limits.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/gosper.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/guess.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/products.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/summations.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/sympy/concrete/delta.py +331 -0
  14. venv/lib/python3.10/site-packages/sympy/concrete/expr_with_intlimits.py +354 -0
  15. venv/lib/python3.10/site-packages/sympy/concrete/expr_with_limits.py +603 -0
  16. venv/lib/python3.10/site-packages/sympy/concrete/gosper.py +227 -0
  17. venv/lib/python3.10/site-packages/sympy/concrete/guess.py +473 -0
  18. venv/lib/python3.10/site-packages/sympy/concrete/products.py +610 -0
  19. venv/lib/python3.10/site-packages/sympy/concrete/summations.py +1646 -0
  20. venv/lib/python3.10/site-packages/sympy/concrete/tests/__init__.py +0 -0
  21. venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_delta.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_gosper.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_guess.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_products.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_sums_products.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/sympy/concrete/tests/test_delta.py +499 -0
  28. venv/lib/python3.10/site-packages/sympy/concrete/tests/test_gosper.py +204 -0
  29. venv/lib/python3.10/site-packages/sympy/concrete/tests/test_guess.py +82 -0
  30. venv/lib/python3.10/site-packages/sympy/concrete/tests/test_products.py +410 -0
  31. venv/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py +1646 -0
  32. venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/__init__.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/determinant.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrices.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/repmatrix.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py +0 -0
  37. venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/bench_matrix.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py +21 -0
  40. venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_companion.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_diagonal.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_matmul.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_special.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_trace.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/sympy/matrices/tests/__init__.py +0 -0
  47. venv/lib/python3.10/site-packages/sympy/matrices/tests/test_graph.py +108 -0
  48. venv/lib/python3.10/site-packages/sympy/matrices/tests/test_matrices.py +0 -0
  49. venv/lib/python3.10/site-packages/sympy/matrices/tests/test_sparsetools.py +132 -0
  50. venv/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py +11 -0
ckpts/universal/global_step120/zero/24.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a5e66bec4cd39fd11ff0abb189a1c135677584714caf25577412440de9c583d
3
+ size 33555612
ckpts/universal/global_step120/zero/5.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56c00fff2cf4387d9e031b7ed37573bce9e34027296d41e652fbc6b2ad56cee4
3
+ size 33555533
ckpts/universal/global_step120/zero/7.mlp.dense_h_to_4h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94e850a68e721f623d9f9eea5fb35c677d26e0318639373bd748828e58951108
3
+ size 33555612
venv/lib/python3.10/site-packages/sympy/concrete/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .products import product, Product
2
+ from .summations import summation, Sum
3
+
4
+ __all__ = [
5
+ 'product', 'Product',
6
+
7
+ 'summation', 'Sum',
8
+ ]
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (339 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/delta.cpython-310.pyc ADDED
Binary file (9.22 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_intlimits.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_limits.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/gosper.cpython-310.pyc ADDED
Binary file (5.41 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/guess.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/products.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/__pycache__/summations.cpython-310.pyc ADDED
Binary file (42.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/delta.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements sums and products containing the Kronecker Delta function.
3
+
4
+ References
5
+ ==========
6
+
7
+ .. [1] https://mathworld.wolfram.com/KroneckerDelta.html
8
+
9
+ """
10
+ from .products import product
11
+ from .summations import Sum, summation
12
+ from sympy.core import Add, Mul, S, Dummy
13
+ from sympy.core.cache import cacheit
14
+ from sympy.core.sorting import default_sort_key
15
+ from sympy.functions import KroneckerDelta, Piecewise, piecewise_fold
16
+ from sympy.polys.polytools import factor
17
+ from sympy.sets.sets import Interval
18
+ from sympy.solvers.solvers import solve
19
+
20
+
21
+ @cacheit
22
+ def _expand_delta(expr, index):
23
+ """
24
+ Expand the first Add containing a simple KroneckerDelta.
25
+ """
26
+ if not expr.is_Mul:
27
+ return expr
28
+ delta = None
29
+ func = Add
30
+ terms = [S.One]
31
+ for h in expr.args:
32
+ if delta is None and h.is_Add and _has_simple_delta(h, index):
33
+ delta = True
34
+ func = h.func
35
+ terms = [terms[0]*t for t in h.args]
36
+ else:
37
+ terms = [t*h for t in terms]
38
+ return func(*terms)
39
+
40
+
41
+ @cacheit
42
+ def _extract_delta(expr, index):
43
+ """
44
+ Extract a simple KroneckerDelta from the expression.
45
+
46
+ Explanation
47
+ ===========
48
+
49
+ Returns the tuple ``(delta, newexpr)`` where:
50
+
51
+ - ``delta`` is a simple KroneckerDelta expression if one was found,
52
+ or ``None`` if no simple KroneckerDelta expression was found.
53
+
54
+ - ``newexpr`` is a Mul containing the remaining terms; ``expr`` is
55
+ returned unchanged if no simple KroneckerDelta expression was found.
56
+
57
+ Examples
58
+ ========
59
+
60
+ >>> from sympy import KroneckerDelta
61
+ >>> from sympy.concrete.delta import _extract_delta
62
+ >>> from sympy.abc import x, y, i, j, k
63
+ >>> _extract_delta(4*x*y*KroneckerDelta(i, j), i)
64
+ (KroneckerDelta(i, j), 4*x*y)
65
+ >>> _extract_delta(4*x*y*KroneckerDelta(i, j), k)
66
+ (None, 4*x*y*KroneckerDelta(i, j))
67
+
68
+ See Also
69
+ ========
70
+
71
+ sympy.functions.special.tensor_functions.KroneckerDelta
72
+ deltaproduct
73
+ deltasummation
74
+ """
75
+ if not _has_simple_delta(expr, index):
76
+ return (None, expr)
77
+ if isinstance(expr, KroneckerDelta):
78
+ return (expr, S.One)
79
+ if not expr.is_Mul:
80
+ raise ValueError("Incorrect expr")
81
+ delta = None
82
+ terms = []
83
+
84
+ for arg in expr.args:
85
+ if delta is None and _is_simple_delta(arg, index):
86
+ delta = arg
87
+ else:
88
+ terms.append(arg)
89
+ return (delta, expr.func(*terms))
90
+
91
+
92
+ @cacheit
93
+ def _has_simple_delta(expr, index):
94
+ """
95
+ Returns True if ``expr`` is an expression that contains a KroneckerDelta
96
+ that is simple in the index ``index``, meaning that this KroneckerDelta
97
+ is nonzero for a single value of the index ``index``.
98
+ """
99
+ if expr.has(KroneckerDelta):
100
+ if _is_simple_delta(expr, index):
101
+ return True
102
+ if expr.is_Add or expr.is_Mul:
103
+ for arg in expr.args:
104
+ if _has_simple_delta(arg, index):
105
+ return True
106
+ return False
107
+
108
+
109
+ @cacheit
110
+ def _is_simple_delta(delta, index):
111
+ """
112
+ Returns True if ``delta`` is a KroneckerDelta and is nonzero for a single
113
+ value of the index ``index``.
114
+ """
115
+ if isinstance(delta, KroneckerDelta) and delta.has(index):
116
+ p = (delta.args[0] - delta.args[1]).as_poly(index)
117
+ if p:
118
+ return p.degree() == 1
119
+ return False
120
+
121
+
122
+ @cacheit
123
+ def _remove_multiple_delta(expr):
124
+ """
125
+ Evaluate products of KroneckerDelta's.
126
+ """
127
+ if expr.is_Add:
128
+ return expr.func(*list(map(_remove_multiple_delta, expr.args)))
129
+ if not expr.is_Mul:
130
+ return expr
131
+ eqs = []
132
+ newargs = []
133
+ for arg in expr.args:
134
+ if isinstance(arg, KroneckerDelta):
135
+ eqs.append(arg.args[0] - arg.args[1])
136
+ else:
137
+ newargs.append(arg)
138
+ if not eqs:
139
+ return expr
140
+ solns = solve(eqs, dict=True)
141
+ if len(solns) == 0:
142
+ return S.Zero
143
+ elif len(solns) == 1:
144
+ for key in solns[0].keys():
145
+ newargs.append(KroneckerDelta(key, solns[0][key]))
146
+ expr2 = expr.func(*newargs)
147
+ if expr != expr2:
148
+ return _remove_multiple_delta(expr2)
149
+ return expr
150
+
151
+
152
+ @cacheit
153
+ def _simplify_delta(expr):
154
+ """
155
+ Rewrite a KroneckerDelta's indices in its simplest form.
156
+ """
157
+ if isinstance(expr, KroneckerDelta):
158
+ try:
159
+ slns = solve(expr.args[0] - expr.args[1], dict=True)
160
+ if slns and len(slns) == 1:
161
+ return Mul(*[KroneckerDelta(*(key, value))
162
+ for key, value in slns[0].items()])
163
+ except NotImplementedError:
164
+ pass
165
+ return expr
166
+
167
+
168
+ @cacheit
169
+ def deltaproduct(f, limit):
170
+ """
171
+ Handle products containing a KroneckerDelta.
172
+
173
+ See Also
174
+ ========
175
+
176
+ deltasummation
177
+ sympy.functions.special.tensor_functions.KroneckerDelta
178
+ sympy.concrete.products.product
179
+ """
180
+ if ((limit[2] - limit[1]) < 0) == True:
181
+ return S.One
182
+
183
+ if not f.has(KroneckerDelta):
184
+ return product(f, limit)
185
+
186
+ if f.is_Add:
187
+ # Identify the term in the Add that has a simple KroneckerDelta
188
+ delta = None
189
+ terms = []
190
+ for arg in sorted(f.args, key=default_sort_key):
191
+ if delta is None and _has_simple_delta(arg, limit[0]):
192
+ delta = arg
193
+ else:
194
+ terms.append(arg)
195
+ newexpr = f.func(*terms)
196
+ k = Dummy("kprime", integer=True)
197
+ if isinstance(limit[1], int) and isinstance(limit[2], int):
198
+ result = deltaproduct(newexpr, limit) + sum([
199
+ deltaproduct(newexpr, (limit[0], limit[1], ik - 1)) *
200
+ delta.subs(limit[0], ik) *
201
+ deltaproduct(newexpr, (limit[0], ik + 1, limit[2])) for ik in range(int(limit[1]), int(limit[2] + 1))]
202
+ )
203
+ else:
204
+ result = deltaproduct(newexpr, limit) + deltasummation(
205
+ deltaproduct(newexpr, (limit[0], limit[1], k - 1)) *
206
+ delta.subs(limit[0], k) *
207
+ deltaproduct(newexpr, (limit[0], k + 1, limit[2])),
208
+ (k, limit[1], limit[2]),
209
+ no_piecewise=_has_simple_delta(newexpr, limit[0])
210
+ )
211
+ return _remove_multiple_delta(result)
212
+
213
+ delta, _ = _extract_delta(f, limit[0])
214
+
215
+ if not delta:
216
+ g = _expand_delta(f, limit[0])
217
+ if f != g:
218
+ try:
219
+ return factor(deltaproduct(g, limit))
220
+ except AssertionError:
221
+ return deltaproduct(g, limit)
222
+ return product(f, limit)
223
+
224
+ return _remove_multiple_delta(f.subs(limit[0], limit[1])*KroneckerDelta(limit[2], limit[1])) + \
225
+ S.One*_simplify_delta(KroneckerDelta(limit[2], limit[1] - 1))
226
+
227
+
228
+ @cacheit
229
+ def deltasummation(f, limit, no_piecewise=False):
230
+ """
231
+ Handle summations containing a KroneckerDelta.
232
+
233
+ Explanation
234
+ ===========
235
+
236
+ The idea for summation is the following:
237
+
238
+ - If we are dealing with a KroneckerDelta expression, i.e. KroneckerDelta(g(x), j),
239
+ we try to simplify it.
240
+
241
+ If we could simplify it, then we sum the resulting expression.
242
+ We already know we can sum a simplified expression, because only
243
+ simple KroneckerDelta expressions are involved.
244
+
245
+ If we could not simplify it, there are two cases:
246
+
247
+ 1) The expression is a simple expression: we return the summation,
248
+ taking care if we are dealing with a Derivative or with a proper
249
+ KroneckerDelta.
250
+
251
+ 2) The expression is not simple (i.e. KroneckerDelta(cos(x))): we can do
252
+ nothing at all.
253
+
254
+ - If the expr is a multiplication expr having a KroneckerDelta term:
255
+
256
+ First we expand it.
257
+
258
+ If the expansion did work, then we try to sum the expansion.
259
+
260
+ If not, we try to extract a simple KroneckerDelta term, then we have two
261
+ cases:
262
+
263
+ 1) We have a simple KroneckerDelta term, so we return the summation.
264
+
265
+ 2) We did not have a simple term, but we do have an expression with
266
+ simplified KroneckerDelta terms, so we sum this expression.
267
+
268
+ Examples
269
+ ========
270
+
271
+ >>> from sympy import oo, symbols
272
+ >>> from sympy.abc import k
273
+ >>> i, j = symbols('i, j', integer=True, finite=True)
274
+ >>> from sympy.concrete.delta import deltasummation
275
+ >>> from sympy import KroneckerDelta
276
+ >>> deltasummation(KroneckerDelta(i, k), (k, -oo, oo))
277
+ 1
278
+ >>> deltasummation(KroneckerDelta(i, k), (k, 0, oo))
279
+ Piecewise((1, i >= 0), (0, True))
280
+ >>> deltasummation(KroneckerDelta(i, k), (k, 1, 3))
281
+ Piecewise((1, (i >= 1) & (i <= 3)), (0, True))
282
+ >>> deltasummation(k*KroneckerDelta(i, j)*KroneckerDelta(j, k), (k, -oo, oo))
283
+ j*KroneckerDelta(i, j)
284
+ >>> deltasummation(j*KroneckerDelta(i, j), (j, -oo, oo))
285
+ i
286
+ >>> deltasummation(i*KroneckerDelta(i, j), (i, -oo, oo))
287
+ j
288
+
289
+ See Also
290
+ ========
291
+
292
+ deltaproduct
293
+ sympy.functions.special.tensor_functions.KroneckerDelta
294
+ sympy.concrete.sums.summation
295
+ """
296
+ if ((limit[2] - limit[1]) < 0) == True:
297
+ return S.Zero
298
+
299
+ if not f.has(KroneckerDelta):
300
+ return summation(f, limit)
301
+
302
+ x = limit[0]
303
+
304
+ g = _expand_delta(f, x)
305
+ if g.is_Add:
306
+ return piecewise_fold(
307
+ g.func(*[deltasummation(h, limit, no_piecewise) for h in g.args]))
308
+
309
+ # try to extract a simple KroneckerDelta term
310
+ delta, expr = _extract_delta(g, x)
311
+
312
+ if (delta is not None) and (delta.delta_range is not None):
313
+ dinf, dsup = delta.delta_range
314
+ if (limit[1] - dinf <= 0) == True and (limit[2] - dsup >= 0) == True:
315
+ no_piecewise = True
316
+
317
+ if not delta:
318
+ return summation(f, limit)
319
+
320
+ solns = solve(delta.args[0] - delta.args[1], x)
321
+ if len(solns) == 0:
322
+ return S.Zero
323
+ elif len(solns) != 1:
324
+ return Sum(f, limit)
325
+ value = solns[0]
326
+ if no_piecewise:
327
+ return expr.subs(x, value)
328
+ return Piecewise(
329
+ (expr.subs(x, value), Interval(*limit[1:3]).as_relational(value)),
330
+ (S.Zero, True)
331
+ )
venv/lib/python3.10/site-packages/sympy/concrete/expr_with_intlimits.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.expr_with_limits import ExprWithLimits
2
+ from sympy.core.singleton import S
3
+ from sympy.core.relational import Eq
4
+
5
+ class ReorderError(NotImplementedError):
6
+ """
7
+ Exception raised when trying to reorder dependent limits.
8
+ """
9
+ def __init__(self, expr, msg):
10
+ super().__init__(
11
+ "%s could not be reordered: %s." % (expr, msg))
12
+
13
+ class ExprWithIntLimits(ExprWithLimits):
14
+ """
15
+ Superclass for Product and Sum.
16
+
17
+ See Also
18
+ ========
19
+
20
+ sympy.concrete.expr_with_limits.ExprWithLimits
21
+ sympy.concrete.products.Product
22
+ sympy.concrete.summations.Sum
23
+ """
24
+ __slots__ = ()
25
+
26
+ def change_index(self, var, trafo, newvar=None):
27
+ r"""
28
+ Change index of a Sum or Product.
29
+
30
+ Perform a linear transformation `x \mapsto a x + b` on the index variable
31
+ `x`. For `a` the only values allowed are `\pm 1`. A new variable to be used
32
+ after the change of index can also be specified.
33
+
34
+ Explanation
35
+ ===========
36
+
37
+ ``change_index(expr, var, trafo, newvar=None)`` where ``var`` specifies the
38
+ index variable `x` to transform. The transformation ``trafo`` must be linear
39
+ and given in terms of ``var``. If the optional argument ``newvar`` is
40
+ provided then ``var`` gets replaced by ``newvar`` in the final expression.
41
+
42
+ Examples
43
+ ========
44
+
45
+ >>> from sympy import Sum, Product, simplify
46
+ >>> from sympy.abc import x, y, a, b, c, d, u, v, i, j, k, l
47
+
48
+ >>> S = Sum(x, (x, a, b))
49
+ >>> S.doit()
50
+ -a**2/2 + a/2 + b**2/2 + b/2
51
+
52
+ >>> Sn = S.change_index(x, x + 1, y)
53
+ >>> Sn
54
+ Sum(y - 1, (y, a + 1, b + 1))
55
+ >>> Sn.doit()
56
+ -a**2/2 + a/2 + b**2/2 + b/2
57
+
58
+ >>> Sn = S.change_index(x, -x, y)
59
+ >>> Sn
60
+ Sum(-y, (y, -b, -a))
61
+ >>> Sn.doit()
62
+ -a**2/2 + a/2 + b**2/2 + b/2
63
+
64
+ >>> Sn = S.change_index(x, x+u)
65
+ >>> Sn
66
+ Sum(-u + x, (x, a + u, b + u))
67
+ >>> Sn.doit()
68
+ -a**2/2 - a*u + a/2 + b**2/2 + b*u + b/2 - u*(-a + b + 1) + u
69
+ >>> simplify(Sn.doit())
70
+ -a**2/2 + a/2 + b**2/2 + b/2
71
+
72
+ >>> Sn = S.change_index(x, -x - u, y)
73
+ >>> Sn
74
+ Sum(-u - y, (y, -b - u, -a - u))
75
+ >>> Sn.doit()
76
+ -a**2/2 - a*u + a/2 + b**2/2 + b*u + b/2 - u*(-a + b + 1) + u
77
+ >>> simplify(Sn.doit())
78
+ -a**2/2 + a/2 + b**2/2 + b/2
79
+
80
+ >>> P = Product(i*j**2, (i, a, b), (j, c, d))
81
+ >>> P
82
+ Product(i*j**2, (i, a, b), (j, c, d))
83
+ >>> P2 = P.change_index(i, i+3, k)
84
+ >>> P2
85
+ Product(j**2*(k - 3), (k, a + 3, b + 3), (j, c, d))
86
+ >>> P3 = P2.change_index(j, -j, l)
87
+ >>> P3
88
+ Product(l**2*(k - 3), (k, a + 3, b + 3), (l, -d, -c))
89
+
90
+ When dealing with symbols only, we can make a
91
+ general linear transformation:
92
+
93
+ >>> Sn = S.change_index(x, u*x+v, y)
94
+ >>> Sn
95
+ Sum((-v + y)/u, (y, b*u + v, a*u + v))
96
+ >>> Sn.doit()
97
+ -v*(a*u - b*u + 1)/u + (a**2*u**2/2 + a*u*v + a*u/2 - b**2*u**2/2 - b*u*v + b*u/2 + v)/u
98
+ >>> simplify(Sn.doit())
99
+ a**2*u/2 + a/2 - b**2*u/2 + b/2
100
+
101
+ However, the last result can be inconsistent with usual
102
+ summation where the index increment is always 1. This is
103
+ obvious as we get back the original value only for ``u``
104
+ equal +1 or -1.
105
+
106
+ See Also
107
+ ========
108
+
109
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index,
110
+ reorder_limit,
111
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder,
112
+ sympy.concrete.summations.Sum.reverse_order,
113
+ sympy.concrete.products.Product.reverse_order
114
+ """
115
+ if newvar is None:
116
+ newvar = var
117
+
118
+ limits = []
119
+ for limit in self.limits:
120
+ if limit[0] == var:
121
+ p = trafo.as_poly(var)
122
+ if p.degree() != 1:
123
+ raise ValueError("Index transformation is not linear")
124
+ alpha = p.coeff_monomial(var)
125
+ beta = p.coeff_monomial(S.One)
126
+ if alpha.is_number:
127
+ if alpha == S.One:
128
+ limits.append((newvar, alpha*limit[1] + beta, alpha*limit[2] + beta))
129
+ elif alpha == S.NegativeOne:
130
+ limits.append((newvar, alpha*limit[2] + beta, alpha*limit[1] + beta))
131
+ else:
132
+ raise ValueError("Linear transformation results in non-linear summation stepsize")
133
+ else:
134
+ # Note that the case of alpha being symbolic can give issues if alpha < 0.
135
+ limits.append((newvar, alpha*limit[2] + beta, alpha*limit[1] + beta))
136
+ else:
137
+ limits.append(limit)
138
+
139
+ function = self.function.subs(var, (var - beta)/alpha)
140
+ function = function.subs(var, newvar)
141
+
142
+ return self.func(function, *limits)
143
+
144
+
145
+ def index(expr, x):
146
+ """
147
+ Return the index of a dummy variable in the list of limits.
148
+
149
+ Explanation
150
+ ===========
151
+
152
+ ``index(expr, x)`` returns the index of the dummy variable ``x`` in the
153
+ limits of ``expr``. Note that we start counting with 0 at the inner-most
154
+ limits tuple.
155
+
156
+ Examples
157
+ ========
158
+
159
+ >>> from sympy.abc import x, y, a, b, c, d
160
+ >>> from sympy import Sum, Product
161
+ >>> Sum(x*y, (x, a, b), (y, c, d)).index(x)
162
+ 0
163
+ >>> Sum(x*y, (x, a, b), (y, c, d)).index(y)
164
+ 1
165
+ >>> Product(x*y, (x, a, b), (y, c, d)).index(x)
166
+ 0
167
+ >>> Product(x*y, (x, a, b), (y, c, d)).index(y)
168
+ 1
169
+
170
+ See Also
171
+ ========
172
+
173
+ reorder_limit, reorder, sympy.concrete.summations.Sum.reverse_order,
174
+ sympy.concrete.products.Product.reverse_order
175
+ """
176
+ variables = [limit[0] for limit in expr.limits]
177
+
178
+ if variables.count(x) != 1:
179
+ raise ValueError(expr, "Number of instances of variable not equal to one")
180
+ else:
181
+ return variables.index(x)
182
+
183
+ def reorder(expr, *arg):
184
+ """
185
+ Reorder limits in a expression containing a Sum or a Product.
186
+
187
+ Explanation
188
+ ===========
189
+
190
+ ``expr.reorder(*arg)`` reorders the limits in the expression ``expr``
191
+ according to the list of tuples given by ``arg``. These tuples can
192
+ contain numerical indices or index variable names or involve both.
193
+
194
+ Examples
195
+ ========
196
+
197
+ >>> from sympy import Sum, Product
198
+ >>> from sympy.abc import x, y, z, a, b, c, d, e, f
199
+
200
+ >>> Sum(x*y, (x, a, b), (y, c, d)).reorder((x, y))
201
+ Sum(x*y, (y, c, d), (x, a, b))
202
+
203
+ >>> Sum(x*y*z, (x, a, b), (y, c, d), (z, e, f)).reorder((x, y), (x, z), (y, z))
204
+ Sum(x*y*z, (z, e, f), (y, c, d), (x, a, b))
205
+
206
+ >>> P = Product(x*y*z, (x, a, b), (y, c, d), (z, e, f))
207
+ >>> P.reorder((x, y), (x, z), (y, z))
208
+ Product(x*y*z, (z, e, f), (y, c, d), (x, a, b))
209
+
210
+ We can also select the index variables by counting them, starting
211
+ with the inner-most one:
212
+
213
+ >>> Sum(x**2, (x, a, b), (x, c, d)).reorder((0, 1))
214
+ Sum(x**2, (x, c, d), (x, a, b))
215
+
216
+ And of course we can mix both schemes:
217
+
218
+ >>> Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x))
219
+ Sum(x*y, (y, c, d), (x, a, b))
220
+ >>> Sum(x*y, (x, a, b), (y, c, d)).reorder((y, 0))
221
+ Sum(x*y, (y, c, d), (x, a, b))
222
+
223
+ See Also
224
+ ========
225
+
226
+ reorder_limit, index, sympy.concrete.summations.Sum.reverse_order,
227
+ sympy.concrete.products.Product.reverse_order
228
+ """
229
+ new_expr = expr
230
+
231
+ for r in arg:
232
+ if len(r) != 2:
233
+ raise ValueError(r, "Invalid number of arguments")
234
+
235
+ index1 = r[0]
236
+ index2 = r[1]
237
+
238
+ if not isinstance(r[0], int):
239
+ index1 = expr.index(r[0])
240
+ if not isinstance(r[1], int):
241
+ index2 = expr.index(r[1])
242
+
243
+ new_expr = new_expr.reorder_limit(index1, index2)
244
+
245
+ return new_expr
246
+
247
+
248
+ def reorder_limit(expr, x, y):
249
+ """
250
+ Interchange two limit tuples of a Sum or Product expression.
251
+
252
+ Explanation
253
+ ===========
254
+
255
+ ``expr.reorder_limit(x, y)`` interchanges two limit tuples. The
256
+ arguments ``x`` and ``y`` are integers corresponding to the index
257
+ variables of the two limits which are to be interchanged. The
258
+ expression ``expr`` has to be either a Sum or a Product.
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy.abc import x, y, z, a, b, c, d, e, f
264
+ >>> from sympy import Sum, Product
265
+
266
+ >>> Sum(x*y*z, (x, a, b), (y, c, d), (z, e, f)).reorder_limit(0, 2)
267
+ Sum(x*y*z, (z, e, f), (y, c, d), (x, a, b))
268
+ >>> Sum(x**2, (x, a, b), (x, c, d)).reorder_limit(1, 0)
269
+ Sum(x**2, (x, c, d), (x, a, b))
270
+
271
+ >>> Product(x*y*z, (x, a, b), (y, c, d), (z, e, f)).reorder_limit(0, 2)
272
+ Product(x*y*z, (z, e, f), (y, c, d), (x, a, b))
273
+
274
+ See Also
275
+ ========
276
+
277
+ index, reorder, sympy.concrete.summations.Sum.reverse_order,
278
+ sympy.concrete.products.Product.reverse_order
279
+ """
280
+ var = {limit[0] for limit in expr.limits}
281
+ limit_x = expr.limits[x]
282
+ limit_y = expr.limits[y]
283
+
284
+ if (len(set(limit_x[1].free_symbols).intersection(var)) == 0 and
285
+ len(set(limit_x[2].free_symbols).intersection(var)) == 0 and
286
+ len(set(limit_y[1].free_symbols).intersection(var)) == 0 and
287
+ len(set(limit_y[2].free_symbols).intersection(var)) == 0):
288
+
289
+ limits = []
290
+ for i, limit in enumerate(expr.limits):
291
+ if i == x:
292
+ limits.append(limit_y)
293
+ elif i == y:
294
+ limits.append(limit_x)
295
+ else:
296
+ limits.append(limit)
297
+
298
+ return type(expr)(expr.function, *limits)
299
+ else:
300
+ raise ReorderError(expr, "could not interchange the two limits specified")
301
+
302
+ @property
303
+ def has_empty_sequence(self):
304
+ """
305
+ Returns True if the Sum or Product is computed for an empty sequence.
306
+
307
+ Examples
308
+ ========
309
+
310
+ >>> from sympy import Sum, Product, Symbol
311
+ >>> m = Symbol('m')
312
+ >>> Sum(m, (m, 1, 0)).has_empty_sequence
313
+ True
314
+
315
+ >>> Sum(m, (m, 1, 1)).has_empty_sequence
316
+ False
317
+
318
+ >>> M = Symbol('M', integer=True, positive=True)
319
+ >>> Product(m, (m, 1, M)).has_empty_sequence
320
+ False
321
+
322
+ >>> Product(m, (m, 2, M)).has_empty_sequence
323
+
324
+ >>> Product(m, (m, M + 1, M)).has_empty_sequence
325
+ True
326
+
327
+ >>> N = Symbol('N', integer=True, positive=True)
328
+ >>> Sum(m, (m, N, M)).has_empty_sequence
329
+
330
+ >>> N = Symbol('N', integer=True, negative=True)
331
+ >>> Sum(m, (m, N, M)).has_empty_sequence
332
+ False
333
+
334
+ See Also
335
+ ========
336
+
337
+ has_reversed_limits
338
+ has_finite_limits
339
+
340
+ """
341
+ ret_None = False
342
+ for lim in self.limits:
343
+ dif = lim[1] - lim[2]
344
+ eq = Eq(dif, 1)
345
+ if eq == True:
346
+ return True
347
+ elif eq == False:
348
+ continue
349
+ else:
350
+ ret_None = True
351
+
352
+ if ret_None:
353
+ return None
354
+ return False
venv/lib/python3.10/site-packages/sympy/concrete/expr_with_limits.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.containers import Tuple
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.function import AppliedUndef, UndefinedFunction
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.relational import Equality, Relational
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import Symbol, Dummy
9
+ from sympy.core.sympify import sympify
10
+ from sympy.functions.elementary.piecewise import (piecewise_fold,
11
+ Piecewise)
12
+ from sympy.logic.boolalg import BooleanFunction
13
+ from sympy.matrices.matrices import MatrixBase
14
+ from sympy.sets.sets import Interval, Set
15
+ from sympy.sets.fancysets import Range
16
+ from sympy.tensor.indexed import Idx
17
+ from sympy.utilities import flatten
18
+ from sympy.utilities.iterables import sift, is_sequence
19
+ from sympy.utilities.exceptions import sympy_deprecation_warning
20
+
21
+
22
+ def _common_new(cls, function, *symbols, discrete, **assumptions):
23
+ """Return either a special return value or the tuple,
24
+ (function, limits, orientation). This code is common to
25
+ both ExprWithLimits and AddWithLimits."""
26
+ function = sympify(function)
27
+
28
+ if isinstance(function, Equality):
29
+ # This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y))
30
+ # but that is only valid for definite integrals.
31
+ limits, orientation = _process_limits(*symbols, discrete=discrete)
32
+ if not (limits and all(len(limit) == 3 for limit in limits)):
33
+ sympy_deprecation_warning(
34
+ """
35
+ Creating a indefinite integral with an Eq() argument is
36
+ deprecated.
37
+
38
+ This is because indefinite integrals do not preserve equality
39
+ due to the arbitrary constants. If you want an equality of
40
+ indefinite integrals, use Eq(Integral(a, x), Integral(b, x))
41
+ explicitly.
42
+ """,
43
+ deprecated_since_version="1.6",
44
+ active_deprecations_target="deprecated-indefinite-integral-eq",
45
+ stacklevel=5,
46
+ )
47
+
48
+ lhs = function.lhs
49
+ rhs = function.rhs
50
+ return Equality(cls(lhs, *symbols, **assumptions), \
51
+ cls(rhs, *symbols, **assumptions))
52
+
53
+ if function is S.NaN:
54
+ return S.NaN
55
+
56
+ if symbols:
57
+ limits, orientation = _process_limits(*symbols, discrete=discrete)
58
+ for i, li in enumerate(limits):
59
+ if len(li) == 4:
60
+ function = function.subs(li[0], li[-1])
61
+ limits[i] = Tuple(*li[:-1])
62
+ else:
63
+ # symbol not provided -- we can still try to compute a general form
64
+ free = function.free_symbols
65
+ if len(free) != 1:
66
+ raise ValueError(
67
+ "specify dummy variables for %s" % function)
68
+ limits, orientation = [Tuple(s) for s in free], 1
69
+
70
+ # denest any nested calls
71
+ while cls == type(function):
72
+ limits = list(function.limits) + limits
73
+ function = function.function
74
+
75
+ # Any embedded piecewise functions need to be brought out to the
76
+ # top level. We only fold Piecewise that contain the integration
77
+ # variable.
78
+ reps = {}
79
+ symbols_of_integration = {i[0] for i in limits}
80
+ for p in function.atoms(Piecewise):
81
+ if not p.has(*symbols_of_integration):
82
+ reps[p] = Dummy()
83
+ # mask off those that don't
84
+ function = function.xreplace(reps)
85
+ # do the fold
86
+ function = piecewise_fold(function)
87
+ # remove the masking
88
+ function = function.xreplace({v: k for k, v in reps.items()})
89
+
90
+ return function, limits, orientation
91
+
92
+
93
+ def _process_limits(*symbols, discrete=None):
94
+ """Process the list of symbols and convert them to canonical limits,
95
+ storing them as Tuple(symbol, lower, upper). The orientation of
96
+ the function is also returned when the upper limit is missing
97
+ so (x, 1, None) becomes (x, None, 1) and the orientation is changed.
98
+ In the case that a limit is specified as (symbol, Range), a list of
99
+ length 4 may be returned if a change of variables is needed; the
100
+ expression that should replace the symbol in the expression is
101
+ the fourth element in the list.
102
+ """
103
+ limits = []
104
+ orientation = 1
105
+ if discrete is None:
106
+ err_msg = 'discrete must be True or False'
107
+ elif discrete:
108
+ err_msg = 'use Range, not Interval or Relational'
109
+ else:
110
+ err_msg = 'use Interval or Relational, not Range'
111
+ for V in symbols:
112
+ if isinstance(V, (Relational, BooleanFunction)):
113
+ if discrete:
114
+ raise TypeError(err_msg)
115
+ variable = V.atoms(Symbol).pop()
116
+ V = (variable, V.as_set())
117
+ elif isinstance(V, Symbol) or getattr(V, '_diff_wrt', False):
118
+ if isinstance(V, Idx):
119
+ if V.lower is None or V.upper is None:
120
+ limits.append(Tuple(V))
121
+ else:
122
+ limits.append(Tuple(V, V.lower, V.upper))
123
+ else:
124
+ limits.append(Tuple(V))
125
+ continue
126
+ if is_sequence(V) and not isinstance(V, Set):
127
+ if len(V) == 2 and isinstance(V[1], Set):
128
+ V = list(V)
129
+ if isinstance(V[1], Interval): # includes Reals
130
+ if discrete:
131
+ raise TypeError(err_msg)
132
+ V[1:] = V[1].inf, V[1].sup
133
+ elif isinstance(V[1], Range):
134
+ if not discrete:
135
+ raise TypeError(err_msg)
136
+ lo = V[1].inf
137
+ hi = V[1].sup
138
+ dx = abs(V[1].step) # direction doesn't matter
139
+ if dx == 1:
140
+ V[1:] = [lo, hi]
141
+ else:
142
+ if lo is not S.NegativeInfinity:
143
+ V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo]
144
+ else:
145
+ V = [V[0]] + [0, S.Infinity, -dx*V[0] + hi]
146
+ else:
147
+ # more complicated sets would require splitting, e.g.
148
+ # Union(Interval(1, 3), interval(6,10))
149
+ raise NotImplementedError(
150
+ 'expecting Range' if discrete else
151
+ 'Relational or single Interval' )
152
+ V = sympify(flatten(V)) # list of sympified elements/None
153
+ if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False):
154
+ newsymbol = V[0]
155
+ if len(V) == 3:
156
+ # general case
157
+ if V[2] is None and V[1] is not None:
158
+ orientation *= -1
159
+ V = [newsymbol] + [i for i in V[1:] if i is not None]
160
+
161
+ lenV = len(V)
162
+ if not isinstance(newsymbol, Idx) or lenV == 3:
163
+ if lenV == 4:
164
+ limits.append(Tuple(*V))
165
+ continue
166
+ if lenV == 3:
167
+ if isinstance(newsymbol, Idx):
168
+ # Idx represents an integer which may have
169
+ # specified values it can take on; if it is
170
+ # given such a value, an error is raised here
171
+ # if the summation would try to give it a larger
172
+ # or smaller value than permitted. None and Symbolic
173
+ # values will not raise an error.
174
+ lo, hi = newsymbol.lower, newsymbol.upper
175
+ try:
176
+ if lo is not None and not bool(V[1] >= lo):
177
+ raise ValueError("Summation will set Idx value too low.")
178
+ except TypeError:
179
+ pass
180
+ try:
181
+ if hi is not None and not bool(V[2] <= hi):
182
+ raise ValueError("Summation will set Idx value too high.")
183
+ except TypeError:
184
+ pass
185
+ limits.append(Tuple(*V))
186
+ continue
187
+ if lenV == 1 or (lenV == 2 and V[1] is None):
188
+ limits.append(Tuple(newsymbol))
189
+ continue
190
+ elif lenV == 2:
191
+ limits.append(Tuple(newsymbol, V[1]))
192
+ continue
193
+
194
+ raise ValueError('Invalid limits given: %s' % str(symbols))
195
+
196
+ return limits, orientation
197
+
198
+
199
+ class ExprWithLimits(Expr):
200
+ __slots__ = ('is_commutative',)
201
+
202
+ def __new__(cls, function, *symbols, **assumptions):
203
+ from sympy.concrete.products import Product
204
+ pre = _common_new(cls, function, *symbols,
205
+ discrete=issubclass(cls, Product), **assumptions)
206
+ if isinstance(pre, tuple):
207
+ function, limits, _ = pre
208
+ else:
209
+ return pre
210
+
211
+ # limits must have upper and lower bounds; the indefinite form
212
+ # is not supported. This restriction does not apply to AddWithLimits
213
+ if any(len(l) != 3 or None in l for l in limits):
214
+ raise ValueError('ExprWithLimits requires values for lower and upper bounds.')
215
+
216
+ obj = Expr.__new__(cls, **assumptions)
217
+ arglist = [function]
218
+ arglist.extend(limits)
219
+ obj._args = tuple(arglist)
220
+ obj.is_commutative = function.is_commutative # limits already checked
221
+
222
+ return obj
223
+
224
+ @property
225
+ def function(self):
226
+ """Return the function applied across limits.
227
+
228
+ Examples
229
+ ========
230
+
231
+ >>> from sympy import Integral
232
+ >>> from sympy.abc import x
233
+ >>> Integral(x**2, (x,)).function
234
+ x**2
235
+
236
+ See Also
237
+ ========
238
+
239
+ limits, variables, free_symbols
240
+ """
241
+ return self._args[0]
242
+
243
+ @property
244
+ def kind(self):
245
+ return self.function.kind
246
+
247
+ @property
248
+ def limits(self):
249
+ """Return the limits of expression.
250
+
251
+ Examples
252
+ ========
253
+
254
+ >>> from sympy import Integral
255
+ >>> from sympy.abc import x, i
256
+ >>> Integral(x**i, (i, 1, 3)).limits
257
+ ((i, 1, 3),)
258
+
259
+ See Also
260
+ ========
261
+
262
+ function, variables, free_symbols
263
+ """
264
+ return self._args[1:]
265
+
266
+ @property
267
+ def variables(self):
268
+ """Return a list of the limit variables.
269
+
270
+ >>> from sympy import Sum
271
+ >>> from sympy.abc import x, i
272
+ >>> Sum(x**i, (i, 1, 3)).variables
273
+ [i]
274
+
275
+ See Also
276
+ ========
277
+
278
+ function, limits, free_symbols
279
+ as_dummy : Rename dummy variables
280
+ sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
281
+ """
282
+ return [l[0] for l in self.limits]
283
+
284
+ @property
285
+ def bound_symbols(self):
286
+ """Return only variables that are dummy variables.
287
+
288
+ Examples
289
+ ========
290
+
291
+ >>> from sympy import Integral
292
+ >>> from sympy.abc import x, i, j, k
293
+ >>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols
294
+ [i, j]
295
+
296
+ See Also
297
+ ========
298
+
299
+ function, limits, free_symbols
300
+ as_dummy : Rename dummy variables
301
+ sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
302
+ """
303
+ return [l[0] for l in self.limits if len(l) != 1]
304
+
305
+ @property
306
+ def free_symbols(self):
307
+ """
308
+ This method returns the symbols in the object, excluding those
309
+ that take on a specific value (i.e. the dummy symbols).
310
+
311
+ Examples
312
+ ========
313
+
314
+ >>> from sympy import Sum
315
+ >>> from sympy.abc import x, y
316
+ >>> Sum(x, (x, y, 1)).free_symbols
317
+ {y}
318
+ """
319
+ # don't test for any special values -- nominal free symbols
320
+ # should be returned, e.g. don't return set() if the
321
+ # function is zero -- treat it like an unevaluated expression.
322
+ function, limits = self.function, self.limits
323
+ # mask off non-symbol integration variables that have
324
+ # more than themself as a free symbol
325
+ reps = {i[0]: i[0] if i[0].free_symbols == {i[0]} else Dummy()
326
+ for i in self.limits}
327
+ function = function.xreplace(reps)
328
+ isyms = function.free_symbols
329
+ for xab in limits:
330
+ v = reps[xab[0]]
331
+ if len(xab) == 1:
332
+ isyms.add(v)
333
+ continue
334
+ # take out the target symbol
335
+ if v in isyms:
336
+ isyms.remove(v)
337
+ # add in the new symbols
338
+ for i in xab[1:]:
339
+ isyms.update(i.free_symbols)
340
+ reps = {v: k for k, v in reps.items()}
341
+ return {reps.get(_, _) for _ in isyms}
342
+
343
+ @property
344
+ def is_number(self):
345
+ """Return True if the Sum has no free symbols, else False."""
346
+ return not self.free_symbols
347
+
348
+ def _eval_interval(self, x, a, b):
349
+ limits = [(i if i[0] != x else (x, a, b)) for i in self.limits]
350
+ integrand = self.function
351
+ return self.func(integrand, *limits)
352
+
353
+ def _eval_subs(self, old, new):
354
+ """
355
+ Perform substitutions over non-dummy variables
356
+ of an expression with limits. Also, can be used
357
+ to specify point-evaluation of an abstract antiderivative.
358
+
359
+ Examples
360
+ ========
361
+
362
+ >>> from sympy import Sum, oo
363
+ >>> from sympy.abc import s, n
364
+ >>> Sum(1/n**s, (n, 1, oo)).subs(s, 2)
365
+ Sum(n**(-2), (n, 1, oo))
366
+
367
+ >>> from sympy import Integral
368
+ >>> from sympy.abc import x, a
369
+ >>> Integral(a*x**2, x).subs(x, 4)
370
+ Integral(a*x**2, (x, 4))
371
+
372
+ See Also
373
+ ========
374
+
375
+ variables : Lists the integration variables
376
+ transform : Perform mapping on the dummy variable for integrals
377
+ change_index : Perform mapping on the sum and product dummy variables
378
+
379
+ """
380
+ func, limits = self.function, list(self.limits)
381
+
382
+ # If one of the expressions we are replacing is used as a func index
383
+ # one of two things happens.
384
+ # - the old variable first appears as a free variable
385
+ # so we perform all free substitutions before it becomes
386
+ # a func index.
387
+ # - the old variable first appears as a func index, in
388
+ # which case we ignore. See change_index.
389
+
390
+ # Reorder limits to match standard mathematical practice for scoping
391
+ limits.reverse()
392
+
393
+ if not isinstance(old, Symbol) or \
394
+ old.free_symbols.intersection(self.free_symbols):
395
+ sub_into_func = True
396
+ for i, xab in enumerate(limits):
397
+ if 1 == len(xab) and old == xab[0]:
398
+ if new._diff_wrt:
399
+ xab = (new,)
400
+ else:
401
+ xab = (old, old)
402
+ limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
403
+ if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0:
404
+ sub_into_func = False
405
+ break
406
+ if isinstance(old, (AppliedUndef, UndefinedFunction)):
407
+ sy2 = set(self.variables).intersection(set(new.atoms(Symbol)))
408
+ sy1 = set(self.variables).intersection(set(old.args))
409
+ if not sy2.issubset(sy1):
410
+ raise ValueError(
411
+ "substitution cannot create dummy dependencies")
412
+ sub_into_func = True
413
+ if sub_into_func:
414
+ func = func.subs(old, new)
415
+ else:
416
+ # old is a Symbol and a dummy variable of some limit
417
+ for i, xab in enumerate(limits):
418
+ if len(xab) == 3:
419
+ limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
420
+ if old == xab[0]:
421
+ break
422
+ # simplify redundant limits (x, x) to (x, )
423
+ for i, xab in enumerate(limits):
424
+ if len(xab) == 2 and (xab[0] - xab[1]).is_zero:
425
+ limits[i] = Tuple(xab[0], )
426
+
427
+ # Reorder limits back to representation-form
428
+ limits.reverse()
429
+
430
+ return self.func(func, *limits)
431
+
432
+ @property
433
+ def has_finite_limits(self):
434
+ """
435
+ Returns True if the limits are known to be finite, either by the
436
+ explicit bounds, assumptions on the bounds, or assumptions on the
437
+ variables. False if known to be infinite, based on the bounds.
438
+ None if not enough information is available to determine.
439
+
440
+ Examples
441
+ ========
442
+
443
+ >>> from sympy import Sum, Integral, Product, oo, Symbol
444
+ >>> x = Symbol('x')
445
+ >>> Sum(x, (x, 1, 8)).has_finite_limits
446
+ True
447
+
448
+ >>> Integral(x, (x, 1, oo)).has_finite_limits
449
+ False
450
+
451
+ >>> M = Symbol('M')
452
+ >>> Sum(x, (x, 1, M)).has_finite_limits
453
+
454
+ >>> N = Symbol('N', integer=True)
455
+ >>> Product(x, (x, 1, N)).has_finite_limits
456
+ True
457
+
458
+ See Also
459
+ ========
460
+
461
+ has_reversed_limits
462
+
463
+ """
464
+
465
+ ret_None = False
466
+ for lim in self.limits:
467
+ if len(lim) == 3:
468
+ if any(l.is_infinite for l in lim[1:]):
469
+ # Any of the bounds are +/-oo
470
+ return False
471
+ elif any(l.is_infinite is None for l in lim[1:]):
472
+ # Maybe there are assumptions on the variable?
473
+ if lim[0].is_infinite is None:
474
+ ret_None = True
475
+ else:
476
+ if lim[0].is_infinite is None:
477
+ ret_None = True
478
+
479
+ if ret_None:
480
+ return None
481
+ return True
482
+
483
+ @property
484
+ def has_reversed_limits(self):
485
+ """
486
+ Returns True if the limits are known to be in reversed order, either
487
+ by the explicit bounds, assumptions on the bounds, or assumptions on the
488
+ variables. False if known to be in normal order, based on the bounds.
489
+ None if not enough information is available to determine.
490
+
491
+ Examples
492
+ ========
493
+
494
+ >>> from sympy import Sum, Integral, Product, oo, Symbol
495
+ >>> x = Symbol('x')
496
+ >>> Sum(x, (x, 8, 1)).has_reversed_limits
497
+ True
498
+
499
+ >>> Sum(x, (x, 1, oo)).has_reversed_limits
500
+ False
501
+
502
+ >>> M = Symbol('M')
503
+ >>> Integral(x, (x, 1, M)).has_reversed_limits
504
+
505
+ >>> N = Symbol('N', integer=True, positive=True)
506
+ >>> Sum(x, (x, 1, N)).has_reversed_limits
507
+ False
508
+
509
+ >>> Product(x, (x, 2, N)).has_reversed_limits
510
+
511
+ >>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits
512
+ False
513
+
514
+ See Also
515
+ ========
516
+
517
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence
518
+
519
+ """
520
+ ret_None = False
521
+ for lim in self.limits:
522
+ if len(lim) == 3:
523
+ var, a, b = lim
524
+ dif = b - a
525
+ if dif.is_extended_negative:
526
+ return True
527
+ elif dif.is_extended_nonnegative:
528
+ continue
529
+ else:
530
+ ret_None = True
531
+ else:
532
+ return None
533
+ if ret_None:
534
+ return None
535
+ return False
536
+
537
+
538
+ class AddWithLimits(ExprWithLimits):
539
+ r"""Represents unevaluated oriented additions.
540
+ Parent class for Integral and Sum.
541
+ """
542
+
543
+ __slots__ = ()
544
+
545
+ def __new__(cls, function, *symbols, **assumptions):
546
+ from sympy.concrete.summations import Sum
547
+ pre = _common_new(cls, function, *symbols,
548
+ discrete=issubclass(cls, Sum), **assumptions)
549
+ if isinstance(pre, tuple):
550
+ function, limits, orientation = pre
551
+ else:
552
+ return pre
553
+
554
+ obj = Expr.__new__(cls, **assumptions)
555
+ arglist = [orientation*function] # orientation not used in ExprWithLimits
556
+ arglist.extend(limits)
557
+ obj._args = tuple(arglist)
558
+ obj.is_commutative = function.is_commutative # limits already checked
559
+
560
+ return obj
561
+
562
+ def _eval_adjoint(self):
563
+ if all(x.is_real for x in flatten(self.limits)):
564
+ return self.func(self.function.adjoint(), *self.limits)
565
+ return None
566
+
567
+ def _eval_conjugate(self):
568
+ if all(x.is_real for x in flatten(self.limits)):
569
+ return self.func(self.function.conjugate(), *self.limits)
570
+ return None
571
+
572
+ def _eval_transpose(self):
573
+ if all(x.is_real for x in flatten(self.limits)):
574
+ return self.func(self.function.transpose(), *self.limits)
575
+ return None
576
+
577
+ def _eval_factor(self, **hints):
578
+ if 1 == len(self.limits):
579
+ summand = self.function.factor(**hints)
580
+ if summand.is_Mul:
581
+ out = sift(summand.args, lambda w: w.is_commutative \
582
+ and not set(self.variables) & w.free_symbols)
583
+ return Mul(*out[True])*self.func(Mul(*out[False]), \
584
+ *self.limits)
585
+ else:
586
+ summand = self.func(self.function, *self.limits[0:-1]).factor()
587
+ if not summand.has(self.variables[-1]):
588
+ return self.func(1, [self.limits[-1]]).doit()*summand
589
+ elif isinstance(summand, Mul):
590
+ return self.func(summand, self.limits[-1]).factor()
591
+ return self
592
+
593
+ def _eval_expand_basic(self, **hints):
594
+ summand = self.function.expand(**hints)
595
+ force = hints.get('force', False)
596
+ if (summand.is_Add and (force or summand.is_commutative and
597
+ self.has_finite_limits is not False)):
598
+ return Add(*[self.func(i, *self.limits) for i in summand.args])
599
+ elif isinstance(summand, MatrixBase):
600
+ return summand.applyfunc(lambda x: self.func(x, *self.limits))
601
+ elif summand != self.function:
602
+ return self.func(summand, *self.limits)
603
+ return self
venv/lib/python3.10/site-packages/sympy/concrete/gosper.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gosper's algorithm for hypergeometric summation. """
2
+
3
+ from sympy.core import S, Dummy, symbols
4
+ from sympy.polys import Poly, parallel_poly_from_expr, factor
5
+ from sympy.utilities.iterables import is_sequence
6
+
7
+
8
+ def gosper_normal(f, g, n, polys=True):
9
+ r"""
10
+ Compute the Gosper's normal form of ``f`` and ``g``.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ Given relatively prime univariate polynomials ``f`` and ``g``,
16
+ rewrite their quotient to a normal form defined as follows:
17
+
18
+ .. math::
19
+ \frac{f(n)}{g(n)} = Z \cdot \frac{A(n) C(n+1)}{B(n) C(n)}
20
+
21
+ where ``Z`` is an arbitrary constant and ``A``, ``B``, ``C`` are
22
+ monic polynomials in ``n`` with the following properties:
23
+
24
+ 1. `\gcd(A(n), B(n+h)) = 1 \forall h \in \mathbb{N}`
25
+ 2. `\gcd(B(n), C(n+1)) = 1`
26
+ 3. `\gcd(A(n), C(n)) = 1`
27
+
28
+ This normal form, or rational factorization in other words, is a
29
+ crucial step in Gosper's algorithm and in solving of difference
30
+ equations. It can be also used to decide if two hypergeometric
31
+ terms are similar or not.
32
+
33
+ This procedure will return a tuple containing elements of this
34
+ factorization in the form ``(Z*A, B, C)``.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.concrete.gosper import gosper_normal
40
+ >>> from sympy.abc import n
41
+
42
+ >>> gosper_normal(4*n+5, 2*(4*n+1)*(2*n+3), n, polys=False)
43
+ (1/4, n + 3/2, n + 1/4)
44
+
45
+ """
46
+ (p, q), opt = parallel_poly_from_expr(
47
+ (f, g), n, field=True, extension=True)
48
+
49
+ a, A = p.LC(), p.monic()
50
+ b, B = q.LC(), q.monic()
51
+
52
+ C, Z = A.one, a/b
53
+ h = Dummy('h')
54
+
55
+ D = Poly(n + h, n, h, domain=opt.domain)
56
+
57
+ R = A.resultant(B.compose(D))
58
+ roots = set(R.ground_roots().keys())
59
+
60
+ for r in set(roots):
61
+ if not r.is_Integer or r < 0:
62
+ roots.remove(r)
63
+
64
+ for i in sorted(roots):
65
+ d = A.gcd(B.shift(+i))
66
+
67
+ A = A.quo(d)
68
+ B = B.quo(d.shift(-i))
69
+
70
+ for j in range(1, i + 1):
71
+ C *= d.shift(-j)
72
+
73
+ A = A.mul_ground(Z)
74
+
75
+ if not polys:
76
+ A = A.as_expr()
77
+ B = B.as_expr()
78
+ C = C.as_expr()
79
+
80
+ return A, B, C
81
+
82
+
83
+ def gosper_term(f, n):
84
+ r"""
85
+ Compute Gosper's hypergeometric term for ``f``.
86
+
87
+ Explanation
88
+ ===========
89
+
90
+ Suppose ``f`` is a hypergeometric term such that:
91
+
92
+ .. math::
93
+ s_n = \sum_{k=0}^{n-1} f_k
94
+
95
+ and `f_k` does not depend on `n`. Returns a hypergeometric
96
+ term `g_n` such that `g_{n+1} - g_n = f_n`.
97
+
98
+ Examples
99
+ ========
100
+
101
+ >>> from sympy.concrete.gosper import gosper_term
102
+ >>> from sympy import factorial
103
+ >>> from sympy.abc import n
104
+
105
+ >>> gosper_term((4*n + 1)*factorial(n)/factorial(2*n + 1), n)
106
+ (-n - 1/2)/(n + 1/4)
107
+
108
+ """
109
+ from sympy.simplify import hypersimp
110
+ r = hypersimp(f, n)
111
+
112
+ if r is None:
113
+ return None # 'f' is *not* a hypergeometric term
114
+
115
+ p, q = r.as_numer_denom()
116
+
117
+ A, B, C = gosper_normal(p, q, n)
118
+ B = B.shift(-1)
119
+
120
+ N = S(A.degree())
121
+ M = S(B.degree())
122
+ K = S(C.degree())
123
+
124
+ if (N != M) or (A.LC() != B.LC()):
125
+ D = {K - max(N, M)}
126
+ elif not N:
127
+ D = {K - N + 1, S.Zero}
128
+ else:
129
+ D = {K - N + 1, (B.nth(N - 1) - A.nth(N - 1))/A.LC()}
130
+
131
+ for d in set(D):
132
+ if not d.is_Integer or d < 0:
133
+ D.remove(d)
134
+
135
+ if not D:
136
+ return None # 'f(n)' is *not* Gosper-summable
137
+
138
+ d = max(D)
139
+
140
+ coeffs = symbols('c:%s' % (d + 1), cls=Dummy)
141
+ domain = A.get_domain().inject(*coeffs)
142
+
143
+ x = Poly(coeffs, n, domain=domain)
144
+ H = A*x.shift(1) - B*x - C
145
+
146
+ from sympy.solvers.solvers import solve
147
+ solution = solve(H.coeffs(), coeffs)
148
+
149
+ if solution is None:
150
+ return None # 'f(n)' is *not* Gosper-summable
151
+
152
+ x = x.as_expr().subs(solution)
153
+
154
+ for coeff in coeffs:
155
+ if coeff not in solution:
156
+ x = x.subs(coeff, 0)
157
+
158
+ if x.is_zero:
159
+ return None # 'f(n)' is *not* Gosper-summable
160
+ else:
161
+ return B.as_expr()*x/C.as_expr()
162
+
163
+
164
+ def gosper_sum(f, k):
165
+ r"""
166
+ Gosper's hypergeometric summation algorithm.
167
+
168
+ Explanation
169
+ ===========
170
+
171
+ Given a hypergeometric term ``f`` such that:
172
+
173
+ .. math ::
174
+ s_n = \sum_{k=0}^{n-1} f_k
175
+
176
+ and `f(n)` does not depend on `n`, returns `g_{n} - g(0)` where
177
+ `g_{n+1} - g_n = f_n`, or ``None`` if `s_n` cannot be expressed
178
+ in closed form as a sum of hypergeometric terms.
179
+
180
+ Examples
181
+ ========
182
+
183
+ >>> from sympy.concrete.gosper import gosper_sum
184
+ >>> from sympy import factorial
185
+ >>> from sympy.abc import n, k
186
+
187
+ >>> f = (4*k + 1)*factorial(k)/factorial(2*k + 1)
188
+ >>> gosper_sum(f, (k, 0, n))
189
+ (-factorial(n) + 2*factorial(2*n + 1))/factorial(2*n + 1)
190
+ >>> _.subs(n, 2) == sum(f.subs(k, i) for i in [0, 1, 2])
191
+ True
192
+ >>> gosper_sum(f, (k, 3, n))
193
+ (-60*factorial(n) + factorial(2*n + 1))/(60*factorial(2*n + 1))
194
+ >>> _.subs(n, 5) == sum(f.subs(k, i) for i in [3, 4, 5])
195
+ True
196
+
197
+ References
198
+ ==========
199
+
200
+ .. [1] Marko Petkovsek, Herbert S. Wilf, Doron Zeilberger, A = B,
201
+ AK Peters, Ltd., Wellesley, MA, USA, 1997, pp. 73--100
202
+
203
+ """
204
+ indefinite = False
205
+
206
+ if is_sequence(k):
207
+ k, a, b = k
208
+ else:
209
+ indefinite = True
210
+
211
+ g = gosper_term(f, k)
212
+
213
+ if g is None:
214
+ return None
215
+
216
+ if indefinite:
217
+ result = f*g
218
+ else:
219
+ result = (f*(g + 1)).subs(k, b) - (f*g).subs(k, a)
220
+
221
+ if result is S.NaN:
222
+ try:
223
+ result = (f*(g + 1)).limit(k, b) - (f*g).limit(k, a)
224
+ except NotImplementedError:
225
+ result = None
226
+
227
+ return factor(result)
venv/lib/python3.10/site-packages/sympy/concrete/guess.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various algorithms for helping identifying numbers and sequences."""
2
+
3
+
4
+ from sympy.concrete.products import (Product, product)
5
+ from sympy.core import Function, S
6
+ from sympy.core.add import Add
7
+ from sympy.core.numbers import Integer, Rational
8
+ from sympy.core.symbol import Symbol, symbols
9
+ from sympy.core.sympify import sympify
10
+ from sympy.functions.elementary.exponential import exp
11
+ from sympy.functions.elementary.integers import floor
12
+ from sympy.integrals.integrals import integrate
13
+ from sympy.polys.polyfuncs import rational_interpolate as rinterp
14
+ from sympy.polys.polytools import lcm
15
+ from sympy.simplify.radsimp import denom
16
+ from sympy.utilities import public
17
+
18
+
19
+ @public
20
+ def find_simple_recurrence_vector(l):
21
+ """
22
+ This function is used internally by other functions from the
23
+ sympy.concrete.guess module. While most users may want to rather use the
24
+ function find_simple_recurrence when looking for recurrence relations
25
+ among rational numbers, the current function may still be useful when
26
+ some post-processing has to be done.
27
+
28
+ Explanation
29
+ ===========
30
+
31
+ The function returns a vector of length n when a recurrence relation of
32
+ order n is detected in the sequence of rational numbers v.
33
+
34
+ If the returned vector has a length 1, then the returned value is always
35
+ the list [0], which means that no relation has been found.
36
+
37
+ While the functions is intended to be used with rational numbers, it should
38
+ work for other kinds of real numbers except for some cases involving
39
+ quadratic numbers; for that reason it should be used with some caution when
40
+ the argument is not a list of rational numbers.
41
+
42
+ Examples
43
+ ========
44
+
45
+ >>> from sympy.concrete.guess import find_simple_recurrence_vector
46
+ >>> from sympy import fibonacci
47
+ >>> find_simple_recurrence_vector([fibonacci(k) for k in range(12)])
48
+ [1, -1, -1]
49
+
50
+ See Also
51
+ ========
52
+
53
+ See the function sympy.concrete.guess.find_simple_recurrence which is more
54
+ user-friendly.
55
+
56
+ """
57
+ q1 = [0]
58
+ q2 = [1]
59
+ b, z = 0, len(l) >> 1
60
+ while len(q2) <= z:
61
+ while l[b]==0:
62
+ b += 1
63
+ if b == len(l):
64
+ c = 1
65
+ for x in q2:
66
+ c = lcm(c, denom(x))
67
+ if q2[0]*c < 0: c = -c
68
+ for k in range(len(q2)):
69
+ q2[k] = int(q2[k]*c)
70
+ return q2
71
+ a = S.One/l[b]
72
+ m = [a]
73
+ for k in range(b+1, len(l)):
74
+ m.append(-sum(l[j+1]*m[b-j-1] for j in range(b, k))*a)
75
+ l, m = m, [0] * max(len(q2), b+len(q1))
76
+ for k, q in enumerate(q2):
77
+ m[k] = a*q
78
+ for k, q in enumerate(q1):
79
+ m[k+b] += q
80
+ while m[-1]==0: m.pop() # because trailing zeros can occur
81
+ q1, q2, b = q2, m, 1
82
+ return [0]
83
+
84
+ @public
85
+ def find_simple_recurrence(v, A=Function('a'), N=Symbol('n')):
86
+ """
87
+ Detects and returns a recurrence relation from a sequence of several integer
88
+ (or rational) terms. The name of the function in the returned expression is
89
+ 'a' by default; the main variable is 'n' by default. The smallest index in
90
+ the returned expression is always n (and never n-1, n-2, etc.).
91
+
92
+ Examples
93
+ ========
94
+
95
+ >>> from sympy.concrete.guess import find_simple_recurrence
96
+ >>> from sympy import fibonacci
97
+ >>> find_simple_recurrence([fibonacci(k) for k in range(12)])
98
+ -a(n) - a(n + 1) + a(n + 2)
99
+
100
+ >>> from sympy import Function, Symbol
101
+ >>> a = [1, 1, 1]
102
+ >>> for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
103
+ >>> find_simple_recurrence(a, A=Function('f'), N=Symbol('i'))
104
+ -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3)
105
+
106
+ """
107
+ p = find_simple_recurrence_vector(v)
108
+ n = len(p)
109
+ if n <= 1: return S.Zero
110
+
111
+ return Add(*[A(N+n-1-k)*p[k] for k in range(n)])
112
+
113
+
114
+ @public
115
+ def rationalize(x, maxcoeff=10000):
116
+ """
117
+ Helps identifying a rational number from a float (or mpmath.mpf) value by
118
+ using a continued fraction. The algorithm stops as soon as a large partial
119
+ quotient is detected (greater than 10000 by default).
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy.concrete.guess import rationalize
125
+ >>> from mpmath import cos, pi
126
+ >>> rationalize(cos(pi/3))
127
+ 1/2
128
+
129
+ >>> from mpmath import mpf
130
+ >>> rationalize(mpf("0.333333333333333"))
131
+ 1/3
132
+
133
+ While the function is rather intended to help 'identifying' rational
134
+ values, it may be used in some cases for approximating real numbers.
135
+ (Though other functions may be more relevant in that case.)
136
+
137
+ >>> rationalize(pi, maxcoeff = 250)
138
+ 355/113
139
+
140
+ See Also
141
+ ========
142
+
143
+ Several other methods can approximate a real number as a rational, like:
144
+
145
+ * fractions.Fraction.from_decimal
146
+ * fractions.Fraction.from_float
147
+ * mpmath.identify
148
+ * mpmath.pslq by using the following syntax: mpmath.pslq([x, 1])
149
+ * mpmath.findpoly by using the following syntax: mpmath.findpoly(x, 1)
150
+ * sympy.simplify.nsimplify (which is a more general function)
151
+
152
+ The main difference between the current function and all these variants is
153
+ that control focuses on magnitude of partial quotients here rather than on
154
+ global precision of the approximation. If the real is "known to be" a
155
+ rational number, the current function should be able to detect it correctly
156
+ with the default settings even when denominator is great (unless its
157
+ expansion contains unusually big partial quotients) which may occur
158
+ when studying sequences of increasing numbers. If the user cares more
159
+ on getting simple fractions, other methods may be more convenient.
160
+
161
+ """
162
+ p0, p1 = 0, 1
163
+ q0, q1 = 1, 0
164
+ a = floor(x)
165
+ while a < maxcoeff or q1==0:
166
+ p = a*p1 + p0
167
+ q = a*q1 + q0
168
+ p0, p1 = p1, p
169
+ q0, q1 = q1, q
170
+ if x==a: break
171
+ x = 1/(x-a)
172
+ a = floor(x)
173
+ return sympify(p) / q
174
+
175
+
176
+ @public
177
+ def guess_generating_function_rational(v, X=Symbol('x')):
178
+ """
179
+ Tries to "guess" a rational generating function for a sequence of rational
180
+ numbers v.
181
+
182
+ Examples
183
+ ========
184
+
185
+ >>> from sympy.concrete.guess import guess_generating_function_rational
186
+ >>> from sympy import fibonacci
187
+ >>> l = [fibonacci(k) for k in range(5,15)]
188
+ >>> guess_generating_function_rational(l)
189
+ (3*x + 5)/(-x**2 - x + 1)
190
+
191
+ See Also
192
+ ========
193
+
194
+ sympy.series.approximants
195
+ mpmath.pade
196
+
197
+ """
198
+ # a) compute the denominator as q
199
+ q = find_simple_recurrence_vector(v)
200
+ n = len(q)
201
+ if n <= 1: return None
202
+ # b) compute the numerator as p
203
+ p = [sum(v[i-k]*q[k] for k in range(min(i+1, n)))
204
+ for i in range(len(v)>>1)]
205
+ return (sum(p[k]*X**k for k in range(len(p)))
206
+ / sum(q[k]*X**k for k in range(n)))
207
+
208
+
209
+ @public
210
+ def guess_generating_function(v, X=Symbol('x'), types=['all'], maxsqrtn=2):
211
+ """
212
+ Tries to "guess" a generating function for a sequence of rational numbers v.
213
+ Only a few patterns are implemented yet.
214
+
215
+ Explanation
216
+ ===========
217
+
218
+ The function returns a dictionary where keys are the name of a given type of
219
+ generating function. Six types are currently implemented:
220
+
221
+ type | formal definition
222
+ -------+----------------------------------------------------------------
223
+ ogf | f(x) = Sum( a_k * x^k , k: 0..infinity )
224
+ egf | f(x) = Sum( a_k * x^k / k! , k: 0..infinity )
225
+ lgf | f(x) = Sum( (-1)^(k+1) a_k * x^k / k , k: 1..infinity )
226
+ | (with initial index being hold as 1 rather than 0)
227
+ hlgf | f(x) = Sum( a_k * x^k / k , k: 1..infinity )
228
+ | (with initial index being hold as 1 rather than 0)
229
+ lgdogf | f(x) = derivate( log(Sum( a_k * x^k, k: 0..infinity )), x)
230
+ lgdegf | f(x) = derivate( log(Sum( a_k * x^k / k!, k: 0..infinity )), x)
231
+
232
+ In order to spare time, the user can select only some types of generating
233
+ functions (default being ['all']). While forgetting to use a list in the
234
+ case of a single type may seem to work most of the time as in: types='ogf'
235
+ this (convenient) syntax may lead to unexpected extra results in some cases.
236
+
237
+ Discarding a type when calling the function does not mean that the type will
238
+ not be present in the returned dictionary; it only means that no extra
239
+ computation will be performed for that type, but the function may still add
240
+ it in the result when it can be easily converted from another type.
241
+
242
+ Two generating functions (lgdogf and lgdegf) are not even computed if the
243
+ initial term of the sequence is 0; it may be useful in that case to try
244
+ again after having removed the leading zeros.
245
+
246
+ Examples
247
+ ========
248
+
249
+ >>> from sympy.concrete.guess import guess_generating_function as ggf
250
+ >>> ggf([k+1 for k in range(12)], types=['ogf', 'lgf', 'hlgf'])
251
+ {'hlgf': 1/(1 - x), 'lgf': 1/(x + 1), 'ogf': 1/(x**2 - 2*x + 1)}
252
+
253
+ >>> from sympy import sympify
254
+ >>> l = sympify("[3/2, 11/2, 0, -121/2, -363/2, 121]")
255
+ >>> ggf(l)
256
+ {'ogf': (x + 3/2)/(11*x**2 - 3*x + 1)}
257
+
258
+ >>> from sympy import fibonacci
259
+ >>> ggf([fibonacci(k) for k in range(5, 15)], types=['ogf'])
260
+ {'ogf': (3*x + 5)/(-x**2 - x + 1)}
261
+
262
+ >>> from sympy import factorial
263
+ >>> ggf([factorial(k) for k in range(12)], types=['ogf', 'egf', 'lgf'])
264
+ {'egf': 1/(1 - x)}
265
+
266
+ >>> ggf([k+1 for k in range(12)], types=['egf'])
267
+ {'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)}
268
+
269
+ N-th root of a rational function can also be detected (below is an example
270
+ coming from the sequence A108626 from https://oeis.org).
271
+ The greatest n-th root to be tested is specified as maxsqrtn (default 2).
272
+
273
+ >>> ggf([1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf']
274
+ sqrt(1/(x**4 + 2*x**2 - 4*x + 1))
275
+
276
+ References
277
+ ==========
278
+
279
+ .. [1] "Concrete Mathematics", R.L. Graham, D.E. Knuth, O. Patashnik
280
+ .. [2] https://oeis.org/wiki/Generating_functions
281
+
282
+ """
283
+ # List of all types of all g.f. known by the algorithm
284
+ if 'all' in types:
285
+ types = ('ogf', 'egf', 'lgf', 'hlgf', 'lgdogf', 'lgdegf')
286
+
287
+ result = {}
288
+
289
+ # Ordinary Generating Function (ogf)
290
+ if 'ogf' in types:
291
+ # Perform some convolutions of the sequence with itself
292
+ t = [1] + [0]*(len(v) - 1)
293
+ for d in range(max(1, maxsqrtn)):
294
+ t = [sum(t[n-i]*v[i] for i in range(n+1)) for n in range(len(v))]
295
+ g = guess_generating_function_rational(t, X=X)
296
+ if g:
297
+ result['ogf'] = g**Rational(1, d+1)
298
+ break
299
+
300
+ # Exponential Generating Function (egf)
301
+ if 'egf' in types:
302
+ # Transform sequence (division by factorial)
303
+ w, f = [], S.One
304
+ for i, k in enumerate(v):
305
+ f *= i if i else 1
306
+ w.append(k/f)
307
+ # Perform some convolutions of the sequence with itself
308
+ t = [1] + [0]*(len(w) - 1)
309
+ for d in range(max(1, maxsqrtn)):
310
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
311
+ g = guess_generating_function_rational(t, X=X)
312
+ if g:
313
+ result['egf'] = g**Rational(1, d+1)
314
+ break
315
+
316
+ # Logarithmic Generating Function (lgf)
317
+ if 'lgf' in types:
318
+ # Transform sequence (multiplication by (-1)^(n+1) / n)
319
+ w, f = [], S.NegativeOne
320
+ for i, k in enumerate(v):
321
+ f = -f
322
+ w.append(f*k/Integer(i+1))
323
+ # Perform some convolutions of the sequence with itself
324
+ t = [1] + [0]*(len(w) - 1)
325
+ for d in range(max(1, maxsqrtn)):
326
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
327
+ g = guess_generating_function_rational(t, X=X)
328
+ if g:
329
+ result['lgf'] = g**Rational(1, d+1)
330
+ break
331
+
332
+ # Hyperbolic logarithmic Generating Function (hlgf)
333
+ if 'hlgf' in types:
334
+ # Transform sequence (division by n+1)
335
+ w = []
336
+ for i, k in enumerate(v):
337
+ w.append(k/Integer(i+1))
338
+ # Perform some convolutions of the sequence with itself
339
+ t = [1] + [0]*(len(w) - 1)
340
+ for d in range(max(1, maxsqrtn)):
341
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
342
+ g = guess_generating_function_rational(t, X=X)
343
+ if g:
344
+ result['hlgf'] = g**Rational(1, d+1)
345
+ break
346
+
347
+ # Logarithmic derivative of ordinary generating Function (lgdogf)
348
+ if v[0] != 0 and ('lgdogf' in types
349
+ or ('ogf' in types and 'ogf' not in result)):
350
+ # Transform sequence by computing f'(x)/f(x)
351
+ # because log(f(x)) = integrate( f'(x)/f(x) )
352
+ a, w = sympify(v[0]), []
353
+ for n in range(len(v)-1):
354
+ w.append(
355
+ (v[n+1]*(n+1) - sum(w[-i-1]*v[i+1] for i in range(n)))/a)
356
+ # Perform some convolutions of the sequence with itself
357
+ t = [1] + [0]*(len(w) - 1)
358
+ for d in range(max(1, maxsqrtn)):
359
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
360
+ g = guess_generating_function_rational(t, X=X)
361
+ if g:
362
+ result['lgdogf'] = g**Rational(1, d+1)
363
+ if 'ogf' not in result:
364
+ result['ogf'] = exp(integrate(result['lgdogf'], X))
365
+ break
366
+
367
+ # Logarithmic derivative of exponential generating Function (lgdegf)
368
+ if v[0] != 0 and ('lgdegf' in types
369
+ or ('egf' in types and 'egf' not in result)):
370
+ # Transform sequence / step 1 (division by factorial)
371
+ z, f = [], S.One
372
+ for i, k in enumerate(v):
373
+ f *= i if i else 1
374
+ z.append(k/f)
375
+ # Transform sequence / step 2 by computing f'(x)/f(x)
376
+ # because log(f(x)) = integrate( f'(x)/f(x) )
377
+ a, w = z[0], []
378
+ for n in range(len(z)-1):
379
+ w.append(
380
+ (z[n+1]*(n+1) - sum(w[-i-1]*z[i+1] for i in range(n)))/a)
381
+ # Perform some convolutions of the sequence with itself
382
+ t = [1] + [0]*(len(w) - 1)
383
+ for d in range(max(1, maxsqrtn)):
384
+ t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
385
+ g = guess_generating_function_rational(t, X=X)
386
+ if g:
387
+ result['lgdegf'] = g**Rational(1, d+1)
388
+ if 'egf' not in result:
389
+ result['egf'] = exp(integrate(result['lgdegf'], X))
390
+ break
391
+
392
+ return result
393
+
394
+
395
+ @public
396
+ def guess(l, all=False, evaluate=True, niter=2, variables=None):
397
+ """
398
+ This function is adapted from the Rate.m package for Mathematica
399
+ written by Christian Krattenthaler.
400
+ It tries to guess a formula from a given sequence of rational numbers.
401
+
402
+ Explanation
403
+ ===========
404
+
405
+ In order to speed up the process, the 'all' variable is set to False by
406
+ default, stopping the computation as some results are returned during an
407
+ iteration; the variable can be set to True if more iterations are needed
408
+ (other formulas may be found; however they may be equivalent to the first
409
+ ones).
410
+
411
+ Another option is the 'evaluate' variable (default is True); setting it
412
+ to False will leave the involved products unevaluated.
413
+
414
+ By default, the number of iterations is set to 2 but a greater value (up
415
+ to len(l)-1) can be specified with the optional 'niter' variable.
416
+ More and more convoluted results are found when the order of the
417
+ iteration gets higher:
418
+
419
+ * first iteration returns polynomial or rational functions;
420
+ * second iteration returns products of rising factorials and their
421
+ inverses;
422
+ * third iteration returns products of products of rising factorials
423
+ and their inverses;
424
+ * etc.
425
+
426
+ The returned formulas contain symbols i0, i1, i2, ... where the main
427
+ variables is i0 (and auxiliary variables are i1, i2, ...). A list of
428
+ other symbols can be provided in the 'variables' option; the length of
429
+ the least should be the value of 'niter' (more is acceptable but only
430
+ the first symbols will be used); in this case, the main variable will be
431
+ the first symbol in the list.
432
+
433
+ Examples
434
+ ========
435
+
436
+ >>> from sympy.concrete.guess import guess
437
+ >>> guess([1,2,6,24,120], evaluate=False)
438
+ [Product(i1 + 1, (i1, 1, i0 - 1))]
439
+
440
+ >>> from sympy import symbols
441
+ >>> r = guess([1,2,7,42,429,7436,218348,10850216], niter=4)
442
+ >>> i0 = symbols("i0")
443
+ >>> [r[0].subs(i0,n).doit() for n in range(1,10)]
444
+ [1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460]
445
+ """
446
+ if any(a==0 for a in l[:-1]):
447
+ return []
448
+ N = len(l)
449
+ niter = min(N-1, niter)
450
+ myprod = product if evaluate else Product
451
+ g = []
452
+ res = []
453
+ if variables is None:
454
+ symb = symbols('i:'+str(niter))
455
+ else:
456
+ symb = variables
457
+ for k, s in enumerate(symb):
458
+ g.append(l)
459
+ n, r = len(l), []
460
+ for i in range(n-2-1, -1, -1):
461
+ ri = rinterp(enumerate(g[k][:-1], start=1), i, X=s)
462
+ if ((denom(ri).subs({s:n}) != 0)
463
+ and (ri.subs({s:n}) - g[k][-1] == 0)
464
+ and ri not in r):
465
+ r.append(ri)
466
+ if r:
467
+ for i in range(k-1, -1, -1):
468
+ r = [g[i][0]
469
+ * myprod(v, (symb[i+1], 1, symb[i]-1)) for v in r]
470
+ if not all: return r
471
+ res += r
472
+ l = [Rational(l[i+1], l[i]) for i in range(N-k-1)]
473
+ return res
venv/lib/python3.10/site-packages/sympy/concrete/products.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+
3
+ from .expr_with_intlimits import ExprWithIntLimits
4
+ from .summations import Sum, summation, _dummy_with_inherited_properties_concrete
5
+ from sympy.core.expr import Expr
6
+ from sympy.core.exprtools import factor_terms
7
+ from sympy.core.function import Derivative
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.singleton import S
10
+ from sympy.core.symbol import Dummy, Symbol
11
+ from sympy.functions.combinatorial.factorials import RisingFactorial
12
+ from sympy.functions.elementary.exponential import exp, log
13
+ from sympy.functions.special.tensor_functions import KroneckerDelta
14
+ from sympy.polys import quo, roots
15
+
16
+
17
+ class Product(ExprWithIntLimits):
18
+ r"""
19
+ Represents unevaluated products.
20
+
21
+ Explanation
22
+ ===========
23
+
24
+ ``Product`` represents a finite or infinite product, with the first
25
+ argument being the general form of terms in the series, and the second
26
+ argument being ``(dummy_variable, start, end)``, with ``dummy_variable``
27
+ taking all integer values from ``start`` through ``end``. In accordance
28
+ with long-standing mathematical convention, the end term is included in
29
+ the product.
30
+
31
+ Finite products
32
+ ===============
33
+
34
+ For finite products (and products with symbolic limits assumed to be finite)
35
+ we follow the analogue of the summation convention described by Karr [1],
36
+ especially definition 3 of section 1.4. The product:
37
+
38
+ .. math::
39
+
40
+ \prod_{m \leq i < n} f(i)
41
+
42
+ has *the obvious meaning* for `m < n`, namely:
43
+
44
+ .. math::
45
+
46
+ \prod_{m \leq i < n} f(i) = f(m) f(m+1) \cdot \ldots \cdot f(n-2) f(n-1)
47
+
48
+ with the upper limit value `f(n)` excluded. The product over an empty set is
49
+ one if and only if `m = n`:
50
+
51
+ .. math::
52
+
53
+ \prod_{m \leq i < n} f(i) = 1 \quad \mathrm{for} \quad m = n
54
+
55
+ Finally, for all other products over empty sets we assume the following
56
+ definition:
57
+
58
+ .. math::
59
+
60
+ \prod_{m \leq i < n} f(i) = \frac{1}{\prod_{n \leq i < m} f(i)} \quad \mathrm{for} \quad m > n
61
+
62
+ It is important to note that above we define all products with the upper
63
+ limit being exclusive. This is in contrast to the usual mathematical notation,
64
+ but does not affect the product convention. Indeed we have:
65
+
66
+ .. math::
67
+
68
+ \prod_{m \leq i < n} f(i) = \prod_{i = m}^{n - 1} f(i)
69
+
70
+ where the difference in notation is intentional to emphasize the meaning,
71
+ with limits typeset on the top being inclusive.
72
+
73
+ Examples
74
+ ========
75
+
76
+ >>> from sympy.abc import a, b, i, k, m, n, x
77
+ >>> from sympy import Product, oo
78
+ >>> Product(k, (k, 1, m))
79
+ Product(k, (k, 1, m))
80
+ >>> Product(k, (k, 1, m)).doit()
81
+ factorial(m)
82
+ >>> Product(k**2,(k, 1, m))
83
+ Product(k**2, (k, 1, m))
84
+ >>> Product(k**2,(k, 1, m)).doit()
85
+ factorial(m)**2
86
+
87
+ Wallis' product for pi:
88
+
89
+ >>> W = Product(2*i/(2*i-1) * 2*i/(2*i+1), (i, 1, oo))
90
+ >>> W
91
+ Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
92
+
93
+ Direct computation currently fails:
94
+
95
+ >>> W.doit()
96
+ Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
97
+
98
+ But we can approach the infinite product by a limit of finite products:
99
+
100
+ >>> from sympy import limit
101
+ >>> W2 = Product(2*i/(2*i-1)*2*i/(2*i+1), (i, 1, n))
102
+ >>> W2
103
+ Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, n))
104
+ >>> W2e = W2.doit()
105
+ >>> W2e
106
+ 4**n*factorial(n)**2/(2**(2*n)*RisingFactorial(1/2, n)*RisingFactorial(3/2, n))
107
+ >>> limit(W2e, n, oo)
108
+ pi/2
109
+
110
+ By the same formula we can compute sin(pi/2):
111
+
112
+ >>> from sympy import combsimp, pi, gamma, simplify
113
+ >>> P = pi * x * Product(1 - x**2/k**2, (k, 1, n))
114
+ >>> P = P.subs(x, pi/2)
115
+ >>> P
116
+ pi**2*Product(1 - pi**2/(4*k**2), (k, 1, n))/2
117
+ >>> Pe = P.doit()
118
+ >>> Pe
119
+ pi**2*RisingFactorial(1 - pi/2, n)*RisingFactorial(1 + pi/2, n)/(2*factorial(n)**2)
120
+ >>> limit(Pe, n, oo).gammasimp()
121
+ sin(pi**2/2)
122
+ >>> Pe.rewrite(gamma)
123
+ (-1)**n*pi**2*gamma(pi/2)*gamma(n + 1 + pi/2)/(2*gamma(1 + pi/2)*gamma(-n + pi/2)*gamma(n + 1)**2)
124
+
125
+ Products with the lower limit being larger than the upper one:
126
+
127
+ >>> Product(1/i, (i, 6, 1)).doit()
128
+ 120
129
+ >>> Product(i, (i, 2, 5)).doit()
130
+ 120
131
+
132
+ The empty product:
133
+
134
+ >>> Product(i, (i, n, n-1)).doit()
135
+ 1
136
+
137
+ An example showing that the symbolic result of a product is still
138
+ valid for seemingly nonsensical values of the limits. Then the Karr
139
+ convention allows us to give a perfectly valid interpretation to
140
+ those products by interchanging the limits according to the above rules:
141
+
142
+ >>> P = Product(2, (i, 10, n)).doit()
143
+ >>> P
144
+ 2**(n - 9)
145
+ >>> P.subs(n, 5)
146
+ 1/16
147
+ >>> Product(2, (i, 10, 5)).doit()
148
+ 1/16
149
+ >>> 1/Product(2, (i, 6, 9)).doit()
150
+ 1/16
151
+
152
+ An explicit example of the Karr summation convention applied to products:
153
+
154
+ >>> P1 = Product(x, (i, a, b)).doit()
155
+ >>> P1
156
+ x**(-a + b + 1)
157
+ >>> P2 = Product(x, (i, b+1, a-1)).doit()
158
+ >>> P2
159
+ x**(a - b - 1)
160
+ >>> simplify(P1 * P2)
161
+ 1
162
+
163
+ And another one:
164
+
165
+ >>> P1 = Product(i, (i, b, a)).doit()
166
+ >>> P1
167
+ RisingFactorial(b, a - b + 1)
168
+ >>> P2 = Product(i, (i, a+1, b-1)).doit()
169
+ >>> P2
170
+ RisingFactorial(a + 1, -a + b - 1)
171
+ >>> P1 * P2
172
+ RisingFactorial(b, a - b + 1)*RisingFactorial(a + 1, -a + b - 1)
173
+ >>> combsimp(P1 * P2)
174
+ 1
175
+
176
+ See Also
177
+ ========
178
+
179
+ Sum, summation
180
+ product
181
+
182
+ References
183
+ ==========
184
+
185
+ .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
186
+ Volume 28 Issue 2, April 1981, Pages 305-350
187
+ https://dl.acm.org/doi/10.1145/322248.322255
188
+ .. [2] https://en.wikipedia.org/wiki/Multiplication#Capital_Pi_notation
189
+ .. [3] https://en.wikipedia.org/wiki/Empty_product
190
+ """
191
+
192
+ __slots__ = ()
193
+
194
+ limits: tTuple[tTuple[Symbol, Expr, Expr]]
195
+
196
+ def __new__(cls, function, *symbols, **assumptions):
197
+ obj = ExprWithIntLimits.__new__(cls, function, *symbols, **assumptions)
198
+ return obj
199
+
200
+ def _eval_rewrite_as_Sum(self, *args, **kwargs):
201
+ return exp(Sum(log(self.function), *self.limits))
202
+
203
+ @property
204
+ def term(self):
205
+ return self._args[0]
206
+ function = term
207
+
208
+ def _eval_is_zero(self):
209
+ if self.has_empty_sequence:
210
+ return False
211
+
212
+ z = self.term.is_zero
213
+ if z is True:
214
+ return True
215
+ if self.has_finite_limits:
216
+ # A Product is zero only if its term is zero assuming finite limits.
217
+ return z
218
+
219
+ def _eval_is_extended_real(self):
220
+ if self.has_empty_sequence:
221
+ return True
222
+
223
+ return self.function.is_extended_real
224
+
225
+ def _eval_is_positive(self):
226
+ if self.has_empty_sequence:
227
+ return True
228
+ if self.function.is_positive and self.has_finite_limits:
229
+ return True
230
+
231
+ def _eval_is_nonnegative(self):
232
+ if self.has_empty_sequence:
233
+ return True
234
+ if self.function.is_nonnegative and self.has_finite_limits:
235
+ return True
236
+
237
+ def _eval_is_extended_nonnegative(self):
238
+ if self.has_empty_sequence:
239
+ return True
240
+ if self.function.is_extended_nonnegative:
241
+ return True
242
+
243
+ def _eval_is_extended_nonpositive(self):
244
+ if self.has_empty_sequence:
245
+ return True
246
+
247
+ def _eval_is_finite(self):
248
+ if self.has_finite_limits and self.function.is_finite:
249
+ return True
250
+
251
+ def doit(self, **hints):
252
+ # first make sure any definite limits have product
253
+ # variables with matching assumptions
254
+ reps = {}
255
+ for xab in self.limits:
256
+ d = _dummy_with_inherited_properties_concrete(xab)
257
+ if d:
258
+ reps[xab[0]] = d
259
+ if reps:
260
+ undo = {v: k for k, v in reps.items()}
261
+ did = self.xreplace(reps).doit(**hints)
262
+ if isinstance(did, tuple): # when separate=True
263
+ did = tuple([i.xreplace(undo) for i in did])
264
+ else:
265
+ did = did.xreplace(undo)
266
+ return did
267
+
268
+ from sympy.simplify.powsimp import powsimp
269
+ f = self.function
270
+ for index, limit in enumerate(self.limits):
271
+ i, a, b = limit
272
+ dif = b - a
273
+ if dif.is_integer and dif.is_negative:
274
+ a, b = b + 1, a - 1
275
+ f = 1 / f
276
+
277
+ g = self._eval_product(f, (i, a, b))
278
+ if g in (None, S.NaN):
279
+ return self.func(powsimp(f), *self.limits[index:])
280
+ else:
281
+ f = g
282
+
283
+ if hints.get('deep', True):
284
+ return f.doit(**hints)
285
+ else:
286
+ return powsimp(f)
287
+
288
+ def _eval_adjoint(self):
289
+ if self.is_commutative:
290
+ return self.func(self.function.adjoint(), *self.limits)
291
+ return None
292
+
293
+ def _eval_conjugate(self):
294
+ return self.func(self.function.conjugate(), *self.limits)
295
+
296
+ def _eval_product(self, term, limits):
297
+
298
+ (k, a, n) = limits
299
+
300
+ if k not in term.free_symbols:
301
+ if (term - 1).is_zero:
302
+ return S.One
303
+ return term**(n - a + 1)
304
+
305
+ if a == n:
306
+ return term.subs(k, a)
307
+
308
+ from .delta import deltaproduct, _has_simple_delta
309
+ if term.has(KroneckerDelta) and _has_simple_delta(term, limits[0]):
310
+ return deltaproduct(term, limits)
311
+
312
+ dif = n - a
313
+ definite = dif.is_Integer
314
+ if definite and (dif < 100):
315
+ return self._eval_product_direct(term, limits)
316
+
317
+ elif term.is_polynomial(k):
318
+ poly = term.as_poly(k)
319
+
320
+ A = B = Q = S.One
321
+
322
+ all_roots = roots(poly)
323
+
324
+ M = 0
325
+ for r, m in all_roots.items():
326
+ M += m
327
+ A *= RisingFactorial(a - r, n - a + 1)**m
328
+ Q *= (n - r)**m
329
+
330
+ if M < poly.degree():
331
+ arg = quo(poly, Q.as_poly(k))
332
+ B = self.func(arg, (k, a, n)).doit()
333
+
334
+ return poly.LC()**(n - a + 1) * A * B
335
+
336
+ elif term.is_Add:
337
+ factored = factor_terms(term, fraction=True)
338
+ if factored.is_Mul:
339
+ return self._eval_product(factored, (k, a, n))
340
+
341
+ elif term.is_Mul:
342
+ # Factor in part without the summation variable and part with
343
+ without_k, with_k = term.as_coeff_mul(k)
344
+
345
+ if len(with_k) >= 2:
346
+ # More than one term including k, so still a multiplication
347
+ exclude, include = [], []
348
+ for t in with_k:
349
+ p = self._eval_product(t, (k, a, n))
350
+
351
+ if p is not None:
352
+ exclude.append(p)
353
+ else:
354
+ include.append(t)
355
+
356
+ if not exclude:
357
+ return None
358
+ else:
359
+ arg = term._new_rawargs(*include)
360
+ A = Mul(*exclude)
361
+ B = self.func(arg, (k, a, n)).doit()
362
+ return without_k**(n - a + 1)*A * B
363
+ else:
364
+ # Just a single term
365
+ p = self._eval_product(with_k[0], (k, a, n))
366
+ if p is None:
367
+ p = self.func(with_k[0], (k, a, n)).doit()
368
+ return without_k**(n - a + 1)*p
369
+
370
+
371
+ elif term.is_Pow:
372
+ if not term.base.has(k):
373
+ s = summation(term.exp, (k, a, n))
374
+
375
+ return term.base**s
376
+ elif not term.exp.has(k):
377
+ p = self._eval_product(term.base, (k, a, n))
378
+
379
+ if p is not None:
380
+ return p**term.exp
381
+
382
+ elif isinstance(term, Product):
383
+ evaluated = term.doit()
384
+ f = self._eval_product(evaluated, limits)
385
+ if f is None:
386
+ return self.func(evaluated, limits)
387
+ else:
388
+ return f
389
+
390
+ if definite:
391
+ return self._eval_product_direct(term, limits)
392
+
393
+ def _eval_simplify(self, **kwargs):
394
+ from sympy.simplify.simplify import product_simplify
395
+ rv = product_simplify(self, **kwargs)
396
+ return rv.doit() if kwargs['doit'] else rv
397
+
398
+ def _eval_transpose(self):
399
+ if self.is_commutative:
400
+ return self.func(self.function.transpose(), *self.limits)
401
+ return None
402
+
403
+ def _eval_product_direct(self, term, limits):
404
+ (k, a, n) = limits
405
+ return Mul(*[term.subs(k, a + i) for i in range(n - a + 1)])
406
+
407
+ def _eval_derivative(self, x):
408
+ if isinstance(x, Symbol) and x not in self.free_symbols:
409
+ return S.Zero
410
+ f, limits = self.function, list(self.limits)
411
+ limit = limits.pop(-1)
412
+ if limits:
413
+ f = self.func(f, *limits)
414
+ i, a, b = limit
415
+ if x in a.free_symbols or x in b.free_symbols:
416
+ return None
417
+ h = Dummy()
418
+ rv = Sum( Product(f, (i, a, h - 1)) * Product(f, (i, h + 1, b)) * Derivative(f, x, evaluate=True).subs(i, h), (h, a, b))
419
+ return rv
420
+
421
+ def is_convergent(self):
422
+ r"""
423
+ See docs of :obj:`.Sum.is_convergent()` for explanation of convergence
424
+ in SymPy.
425
+
426
+ Explanation
427
+ ===========
428
+
429
+ The infinite product:
430
+
431
+ .. math::
432
+
433
+ \prod_{1 \leq i < \infty} f(i)
434
+
435
+ is defined by the sequence of partial products:
436
+
437
+ .. math::
438
+
439
+ \prod_{i=1}^{n} f(i) = f(1) f(2) \cdots f(n)
440
+
441
+ as n increases without bound. The product converges to a non-zero
442
+ value if and only if the sum:
443
+
444
+ .. math::
445
+
446
+ \sum_{1 \leq i < \infty} \log{f(n)}
447
+
448
+ converges.
449
+
450
+ Examples
451
+ ========
452
+
453
+ >>> from sympy import Product, Symbol, cos, pi, exp, oo
454
+ >>> n = Symbol('n', integer=True)
455
+ >>> Product(n/(n + 1), (n, 1, oo)).is_convergent()
456
+ False
457
+ >>> Product(1/n**2, (n, 1, oo)).is_convergent()
458
+ False
459
+ >>> Product(cos(pi/n), (n, 1, oo)).is_convergent()
460
+ True
461
+ >>> Product(exp(-n**2), (n, 1, oo)).is_convergent()
462
+ False
463
+
464
+ References
465
+ ==========
466
+
467
+ .. [1] https://en.wikipedia.org/wiki/Infinite_product
468
+ """
469
+ sequence_term = self.function
470
+ log_sum = log(sequence_term)
471
+ lim = self.limits
472
+ try:
473
+ is_conv = Sum(log_sum, *lim).is_convergent()
474
+ except NotImplementedError:
475
+ if Sum(sequence_term - 1, *lim).is_absolutely_convergent() is S.true:
476
+ return S.true
477
+ raise NotImplementedError("The algorithm to find the product convergence of %s "
478
+ "is not yet implemented" % (sequence_term))
479
+ return is_conv
480
+
481
+ def reverse_order(expr, *indices):
482
+ """
483
+ Reverse the order of a limit in a Product.
484
+
485
+ Explanation
486
+ ===========
487
+
488
+ ``reverse_order(expr, *indices)`` reverses some limits in the expression
489
+ ``expr`` which can be either a ``Sum`` or a ``Product``. The selectors in
490
+ the argument ``indices`` specify some indices whose limits get reversed.
491
+ These selectors are either variable names or numerical indices counted
492
+ starting from the inner-most limit tuple.
493
+
494
+ Examples
495
+ ========
496
+
497
+ >>> from sympy import gamma, Product, simplify, Sum
498
+ >>> from sympy.abc import x, y, a, b, c, d
499
+ >>> P = Product(x, (x, a, b))
500
+ >>> Pr = P.reverse_order(x)
501
+ >>> Pr
502
+ Product(1/x, (x, b + 1, a - 1))
503
+ >>> Pr = Pr.doit()
504
+ >>> Pr
505
+ 1/RisingFactorial(b + 1, a - b - 1)
506
+ >>> simplify(Pr.rewrite(gamma))
507
+ Piecewise((gamma(b + 1)/gamma(a), b > -1), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
508
+ >>> P = P.doit()
509
+ >>> P
510
+ RisingFactorial(a, -a + b + 1)
511
+ >>> simplify(P.rewrite(gamma))
512
+ Piecewise((gamma(b + 1)/gamma(a), a > 0), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
513
+
514
+ While one should prefer variable names when specifying which limits
515
+ to reverse, the index counting notation comes in handy in case there
516
+ are several symbols with the same name.
517
+
518
+ >>> S = Sum(x*y, (x, a, b), (y, c, d))
519
+ >>> S
520
+ Sum(x*y, (x, a, b), (y, c, d))
521
+ >>> S0 = S.reverse_order(0)
522
+ >>> S0
523
+ Sum(-x*y, (x, b + 1, a - 1), (y, c, d))
524
+ >>> S1 = S0.reverse_order(1)
525
+ >>> S1
526
+ Sum(x*y, (x, b + 1, a - 1), (y, d + 1, c - 1))
527
+
528
+ Of course we can mix both notations:
529
+
530
+ >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
531
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
532
+ >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
533
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
534
+
535
+ See Also
536
+ ========
537
+
538
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index,
539
+ reorder_limit,
540
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
541
+
542
+ References
543
+ ==========
544
+
545
+ .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
546
+ Volume 28 Issue 2, April 1981, Pages 305-350
547
+ https://dl.acm.org/doi/10.1145/322248.322255
548
+
549
+ """
550
+ l_indices = list(indices)
551
+
552
+ for i, indx in enumerate(l_indices):
553
+ if not isinstance(indx, int):
554
+ l_indices[i] = expr.index(indx)
555
+
556
+ e = 1
557
+ limits = []
558
+ for i, limit in enumerate(expr.limits):
559
+ l = limit
560
+ if i in l_indices:
561
+ e = -e
562
+ l = (limit[0], limit[2] + 1, limit[1] - 1)
563
+ limits.append(l)
564
+
565
+ return Product(expr.function ** e, *limits)
566
+
567
+
568
+ def product(*args, **kwargs):
569
+ r"""
570
+ Compute the product.
571
+
572
+ Explanation
573
+ ===========
574
+
575
+ The notation for symbols is similar to the notation used in Sum or
576
+ Integral. product(f, (i, a, b)) computes the product of f with
577
+ respect to i from a to b, i.e.,
578
+
579
+ ::
580
+
581
+ b
582
+ _____
583
+ product(f(n), (i, a, b)) = | | f(n)
584
+ | |
585
+ i = a
586
+
587
+ If it cannot compute the product, it returns an unevaluated Product object.
588
+ Repeated products can be computed by introducing additional symbols tuples::
589
+
590
+ Examples
591
+ ========
592
+
593
+ >>> from sympy import product, symbols
594
+ >>> i, n, m, k = symbols('i n m k', integer=True)
595
+
596
+ >>> product(i, (i, 1, k))
597
+ factorial(k)
598
+ >>> product(m, (i, 1, k))
599
+ m**k
600
+ >>> product(i, (i, 1, k), (k, 1, n))
601
+ Product(factorial(k), (k, 1, n))
602
+
603
+ """
604
+
605
+ prod = Product(*args, **kwargs)
606
+
607
+ if isinstance(prod, Product):
608
+ return prod.doit(deep=False)
609
+ else:
610
+ return prod
venv/lib/python3.10/site-packages/sympy/concrete/summations.py ADDED
@@ -0,0 +1,1646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+
3
+ from sympy.calculus.singularities import is_decreasing
4
+ from sympy.calculus.accumulationbounds import AccumulationBounds
5
+ from .expr_with_intlimits import ExprWithIntLimits
6
+ from .expr_with_limits import AddWithLimits
7
+ from .gosper import gosper_sum
8
+ from sympy.core.expr import Expr
9
+ from sympy.core.add import Add
10
+ from sympy.core.containers import Tuple
11
+ from sympy.core.function import Derivative, expand
12
+ from sympy.core.mul import Mul
13
+ from sympy.core.numbers import Float, _illegal
14
+ from sympy.core.relational import Eq
15
+ from sympy.core.singleton import S
16
+ from sympy.core.sorting import ordered
17
+ from sympy.core.symbol import Dummy, Wild, Symbol, symbols
18
+ from sympy.functions.combinatorial.factorials import factorial
19
+ from sympy.functions.combinatorial.numbers import bernoulli, harmonic
20
+ from sympy.functions.elementary.exponential import exp, log
21
+ from sympy.functions.elementary.piecewise import Piecewise
22
+ from sympy.functions.elementary.trigonometric import cot, csc
23
+ from sympy.functions.special.hyper import hyper
24
+ from sympy.functions.special.tensor_functions import KroneckerDelta
25
+ from sympy.functions.special.zeta_functions import zeta
26
+ from sympy.integrals.integrals import Integral
27
+ from sympy.logic.boolalg import And
28
+ from sympy.polys.partfrac import apart
29
+ from sympy.polys.polyerrors import PolynomialError, PolificationFailed
30
+ from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor
31
+ from sympy.polys.rationaltools import together
32
+ from sympy.series.limitseq import limit_seq
33
+ from sympy.series.order import O
34
+ from sympy.series.residues import residue
35
+ from sympy.sets.sets import FiniteSet, Interval
36
+ from sympy.utilities.iterables import sift
37
+ import itertools
38
+
39
+
40
+ class Sum(AddWithLimits, ExprWithIntLimits):
41
+ r"""
42
+ Represents unevaluated summation.
43
+
44
+ Explanation
45
+ ===========
46
+
47
+ ``Sum`` represents a finite or infinite series, with the first argument
48
+ being the general form of terms in the series, and the second argument
49
+ being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking
50
+ all integer values from ``start`` through ``end``. In accordance with
51
+ long-standing mathematical convention, the end term is included in the
52
+ summation.
53
+
54
+ Finite sums
55
+ ===========
56
+
57
+ For finite sums (and sums with symbolic limits assumed to be finite) we
58
+ follow the summation convention described by Karr [1], especially
59
+ definition 3 of section 1.4. The sum:
60
+
61
+ .. math::
62
+
63
+ \sum_{m \leq i < n} f(i)
64
+
65
+ has *the obvious meaning* for `m < n`, namely:
66
+
67
+ .. math::
68
+
69
+ \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)
70
+
71
+ with the upper limit value `f(n)` excluded. The sum over an empty set is
72
+ zero if and only if `m = n`:
73
+
74
+ .. math::
75
+
76
+ \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n
77
+
78
+ Finally, for all other sums over empty sets we assume the following
79
+ definition:
80
+
81
+ .. math::
82
+
83
+ \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n
84
+
85
+ It is important to note that Karr defines all sums with the upper
86
+ limit being exclusive. This is in contrast to the usual mathematical notation,
87
+ but does not affect the summation convention. Indeed we have:
88
+
89
+ .. math::
90
+
91
+ \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i)
92
+
93
+ where the difference in notation is intentional to emphasize the meaning,
94
+ with limits typeset on the top being inclusive.
95
+
96
+ Examples
97
+ ========
98
+
99
+ >>> from sympy.abc import i, k, m, n, x
100
+ >>> from sympy import Sum, factorial, oo, IndexedBase, Function
101
+ >>> Sum(k, (k, 1, m))
102
+ Sum(k, (k, 1, m))
103
+ >>> Sum(k, (k, 1, m)).doit()
104
+ m**2/2 + m/2
105
+ >>> Sum(k**2, (k, 1, m))
106
+ Sum(k**2, (k, 1, m))
107
+ >>> Sum(k**2, (k, 1, m)).doit()
108
+ m**3/3 + m**2/2 + m/6
109
+ >>> Sum(x**k, (k, 0, oo))
110
+ Sum(x**k, (k, 0, oo))
111
+ >>> Sum(x**k, (k, 0, oo)).doit()
112
+ Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
113
+ >>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
114
+ exp(x)
115
+
116
+ Here are examples to do summation with symbolic indices. You
117
+ can use either Function of IndexedBase classes:
118
+
119
+ >>> f = Function('f')
120
+ >>> Sum(f(n), (n, 0, 3)).doit()
121
+ f(0) + f(1) + f(2) + f(3)
122
+ >>> Sum(f(n), (n, 0, oo)).doit()
123
+ Sum(f(n), (n, 0, oo))
124
+ >>> f = IndexedBase('f')
125
+ >>> Sum(f[n]**2, (n, 0, 3)).doit()
126
+ f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2
127
+
128
+ An example showing that the symbolic result of a summation is still
129
+ valid for seemingly nonsensical values of the limits. Then the Karr
130
+ convention allows us to give a perfectly valid interpretation to
131
+ those sums by interchanging the limits according to the above rules:
132
+
133
+ >>> S = Sum(i, (i, 1, n)).doit()
134
+ >>> S
135
+ n**2/2 + n/2
136
+ >>> S.subs(n, -4)
137
+ 6
138
+ >>> Sum(i, (i, 1, -4)).doit()
139
+ 6
140
+ >>> Sum(-i, (i, -3, 0)).doit()
141
+ 6
142
+
143
+ An explicit example of the Karr summation convention:
144
+
145
+ >>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
146
+ >>> S1
147
+ m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
148
+ >>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
149
+ >>> S2
150
+ -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
151
+ >>> S1 + S2
152
+ 0
153
+ >>> S3 = Sum(i, (i, m, m-1)).doit()
154
+ >>> S3
155
+ 0
156
+
157
+ See Also
158
+ ========
159
+
160
+ summation
161
+ Product, sympy.concrete.products.product
162
+
163
+ References
164
+ ==========
165
+
166
+ .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
167
+ Volume 28 Issue 2, April 1981, Pages 305-350
168
+ https://dl.acm.org/doi/10.1145/322248.322255
169
+ .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation
170
+ .. [3] https://en.wikipedia.org/wiki/Empty_sum
171
+ """
172
+
173
+ __slots__ = ()
174
+
175
+ limits: tTuple[tTuple[Symbol, Expr, Expr]]
176
+
177
+ def __new__(cls, function, *symbols, **assumptions):
178
+ obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
179
+ if not hasattr(obj, 'limits'):
180
+ return obj
181
+ if any(len(l) != 3 or None in l for l in obj.limits):
182
+ raise ValueError('Sum requires values for lower and upper bounds.')
183
+
184
+ return obj
185
+
186
+ def _eval_is_zero(self):
187
+ # a Sum is only zero if its function is zero or if all terms
188
+ # cancel out. This only answers whether the summand is zero; if
189
+ # not then None is returned since we don't analyze whether all
190
+ # terms cancel out.
191
+ if self.function.is_zero or self.has_empty_sequence:
192
+ return True
193
+
194
+ def _eval_is_extended_real(self):
195
+ if self.has_empty_sequence:
196
+ return True
197
+ return self.function.is_extended_real
198
+
199
+ def _eval_is_positive(self):
200
+ if self.has_finite_limits and self.has_reversed_limits is False:
201
+ return self.function.is_positive
202
+
203
+ def _eval_is_negative(self):
204
+ if self.has_finite_limits and self.has_reversed_limits is False:
205
+ return self.function.is_negative
206
+
207
+ def _eval_is_finite(self):
208
+ if self.has_finite_limits and self.function.is_finite:
209
+ return True
210
+
211
+ def doit(self, **hints):
212
+ if hints.get('deep', True):
213
+ f = self.function.doit(**hints)
214
+ else:
215
+ f = self.function
216
+
217
+ # first make sure any definite limits have summation
218
+ # variables with matching assumptions
219
+ reps = {}
220
+ for xab in self.limits:
221
+ d = _dummy_with_inherited_properties_concrete(xab)
222
+ if d:
223
+ reps[xab[0]] = d
224
+ if reps:
225
+ undo = {v: k for k, v in reps.items()}
226
+ did = self.xreplace(reps).doit(**hints)
227
+ if isinstance(did, tuple): # when separate=True
228
+ did = tuple([i.xreplace(undo) for i in did])
229
+ elif did is not None:
230
+ did = did.xreplace(undo)
231
+ else:
232
+ did = self
233
+ return did
234
+
235
+
236
+ if self.function.is_Matrix:
237
+ expanded = self.expand()
238
+ if self != expanded:
239
+ return expanded.doit()
240
+ return _eval_matrix_sum(self)
241
+
242
+ for n, limit in enumerate(self.limits):
243
+ i, a, b = limit
244
+ dif = b - a
245
+ if dif == -1:
246
+ # Any summation over an empty set is zero
247
+ return S.Zero
248
+ if dif.is_integer and dif.is_negative:
249
+ a, b = b + 1, a - 1
250
+ f = -f
251
+
252
+ newf = eval_sum(f, (i, a, b))
253
+ if newf is None:
254
+ if f == self.function:
255
+ zeta_function = self.eval_zeta_function(f, (i, a, b))
256
+ if zeta_function is not None:
257
+ return zeta_function
258
+ return self
259
+ else:
260
+ return self.func(f, *self.limits[n:])
261
+ f = newf
262
+
263
+ if hints.get('deep', True):
264
+ # eval_sum could return partially unevaluated
265
+ # result with Piecewise. In this case we won't
266
+ # doit() recursively.
267
+ if not isinstance(f, Piecewise):
268
+ return f.doit(**hints)
269
+
270
+ return f
271
+
272
+ def eval_zeta_function(self, f, limits):
273
+ """
274
+ Check whether the function matches with the zeta function.
275
+
276
+ If it matches, then return a `Piecewise` expression because
277
+ zeta function does not converge unless `s > 1` and `q > 0`
278
+ """
279
+ i, a, b = limits
280
+ w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
281
+ result = f.match((w * i + y) ** (-z))
282
+ if result is not None and b is S.Infinity:
283
+ coeff = 1 / result[w] ** result[z]
284
+ s = result[z]
285
+ q = result[y] / result[w] + a
286
+ return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
287
+
288
+ def _eval_derivative(self, x):
289
+ """
290
+ Differentiate wrt x as long as x is not in the free symbols of any of
291
+ the upper or lower limits.
292
+
293
+ Explanation
294
+ ===========
295
+
296
+ Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
297
+ since the value of the sum is discontinuous in `a`. In a case
298
+ involving a limit variable, the unevaluated derivative is returned.
299
+ """
300
+
301
+ # diff already confirmed that x is in the free symbols of self, but we
302
+ # don't want to differentiate wrt any free symbol in the upper or lower
303
+ # limits
304
+ # XXX remove this test for free_symbols when the default _eval_derivative is in
305
+ if isinstance(x, Symbol) and x not in self.free_symbols:
306
+ return S.Zero
307
+
308
+ # get limits and the function
309
+ f, limits = self.function, list(self.limits)
310
+
311
+ limit = limits.pop(-1)
312
+
313
+ if limits: # f is the argument to a Sum
314
+ f = self.func(f, *limits)
315
+
316
+ _, a, b = limit
317
+ if x in a.free_symbols or x in b.free_symbols:
318
+ return None
319
+ df = Derivative(f, x, evaluate=True)
320
+ rv = self.func(df, limit)
321
+ return rv
322
+
323
+ def _eval_difference_delta(self, n, step):
324
+ k, _, upper = self.args[-1]
325
+ new_upper = upper.subs(n, n + step)
326
+
327
+ if len(self.args) == 2:
328
+ f = self.args[0]
329
+ else:
330
+ f = self.func(*self.args[:-1])
331
+
332
+ return Sum(f, (k, upper + 1, new_upper)).doit()
333
+
334
+ def _eval_simplify(self, **kwargs):
335
+
336
+ function = self.function
337
+
338
+ if kwargs.get('deep', True):
339
+ function = function.simplify(**kwargs)
340
+
341
+ # split the function into adds
342
+ terms = Add.make_args(expand(function))
343
+ s_t = [] # Sum Terms
344
+ o_t = [] # Other Terms
345
+
346
+ for term in terms:
347
+ if term.has(Sum):
348
+ # if there is an embedded sum here
349
+ # it is of the form x * (Sum(whatever))
350
+ # hence we make a Mul out of it, and simplify all interior sum terms
351
+ subterms = Mul.make_args(expand(term))
352
+ out_terms = []
353
+ for subterm in subterms:
354
+ # go through each term
355
+ if isinstance(subterm, Sum):
356
+ # if it's a sum, simplify it
357
+ out_terms.append(subterm._eval_simplify(**kwargs))
358
+ else:
359
+ # otherwise, add it as is
360
+ out_terms.append(subterm)
361
+
362
+ # turn it back into a Mul
363
+ s_t.append(Mul(*out_terms))
364
+ else:
365
+ o_t.append(term)
366
+
367
+ # next try to combine any interior sums for further simplification
368
+ from sympy.simplify.simplify import factor_sum, sum_combine
369
+ result = Add(sum_combine(s_t), *o_t)
370
+
371
+ return factor_sum(result, limits=self.limits)
372
+
373
+ def is_convergent(self):
374
+ r"""
375
+ Checks for the convergence of a Sum.
376
+
377
+ Explanation
378
+ ===========
379
+
380
+ We divide the study of convergence of infinite sums and products in
381
+ two parts.
382
+
383
+ First Part:
384
+ One part is the question whether all the terms are well defined, i.e.,
385
+ they are finite in a sum and also non-zero in a product. Zero
386
+ is the analogy of (minus) infinity in products as
387
+ :math:`e^{-\infty} = 0`.
388
+
389
+ Second Part:
390
+ The second part is the question of convergence after infinities,
391
+ and zeros in products, have been omitted assuming that their number
392
+ is finite. This means that we only consider the tail of the sum or
393
+ product, starting from some point after which all terms are well
394
+ defined.
395
+
396
+ For example, in a sum of the form:
397
+
398
+ .. math::
399
+
400
+ \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}
401
+
402
+ where a and b are numbers. The routine will return true, even if there
403
+ are infinities in the term sequence (at most two). An analogous
404
+ product would be:
405
+
406
+ .. math::
407
+
408
+ \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}
409
+
410
+ This is how convergence is interpreted. It is concerned with what
411
+ happens at the limit. Finding the bad terms is another independent
412
+ matter.
413
+
414
+ Note: It is responsibility of user to see that the sum or product
415
+ is well defined.
416
+
417
+ There are various tests employed to check the convergence like
418
+ divergence test, root test, integral test, alternating series test,
419
+ comparison tests, Dirichlet tests. It returns true if Sum is convergent
420
+ and false if divergent and NotImplementedError if it cannot be checked.
421
+
422
+ References
423
+ ==========
424
+
425
+ .. [1] https://en.wikipedia.org/wiki/Convergence_tests
426
+
427
+ Examples
428
+ ========
429
+
430
+ >>> from sympy import factorial, S, Sum, Symbol, oo
431
+ >>> n = Symbol('n', integer=True)
432
+ >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
433
+ True
434
+ >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
435
+ False
436
+ >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
437
+ False
438
+ >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
439
+ True
440
+
441
+ See Also
442
+ ========
443
+
444
+ Sum.is_absolutely_convergent
445
+ sympy.concrete.products.Product.is_convergent
446
+ """
447
+ p, q, r = symbols('p q r', cls=Wild)
448
+
449
+ sym = self.limits[0][0]
450
+ lower_limit = self.limits[0][1]
451
+ upper_limit = self.limits[0][2]
452
+ sequence_term = self.function.simplify()
453
+
454
+ if len(sequence_term.free_symbols) > 1:
455
+ raise NotImplementedError("convergence checking for more than one symbol "
456
+ "containing series is not handled")
457
+
458
+ if lower_limit.is_finite and upper_limit.is_finite:
459
+ return S.true
460
+
461
+ # transform sym -> -sym and swap the upper_limit = S.Infinity
462
+ # and lower_limit = - upper_limit
463
+ if lower_limit is S.NegativeInfinity:
464
+ if upper_limit is S.Infinity:
465
+ return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
466
+ Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
467
+ from sympy.simplify.simplify import simplify
468
+ sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
469
+ lower_limit = -upper_limit
470
+ upper_limit = S.Infinity
471
+
472
+ sym_ = Dummy(sym.name, integer=True, positive=True)
473
+ sequence_term = sequence_term.xreplace({sym: sym_})
474
+ sym = sym_
475
+
476
+ interval = Interval(lower_limit, upper_limit)
477
+
478
+ # Piecewise function handle
479
+ if sequence_term.is_Piecewise:
480
+ for func, cond in sequence_term.args:
481
+ # see if it represents something going to oo
482
+ if cond == True or cond.as_set().sup is S.Infinity:
483
+ s = Sum(func, (sym, lower_limit, upper_limit))
484
+ return s.is_convergent()
485
+ return S.true
486
+
487
+ ### -------- Divergence test ----------- ###
488
+ try:
489
+ lim_val = limit_seq(sequence_term, sym)
490
+ if lim_val is not None and lim_val.is_zero is False:
491
+ return S.false
492
+ except NotImplementedError:
493
+ pass
494
+
495
+ try:
496
+ lim_val_abs = limit_seq(abs(sequence_term), sym)
497
+ if lim_val_abs is not None and lim_val_abs.is_zero is False:
498
+ return S.false
499
+ except NotImplementedError:
500
+ pass
501
+
502
+ order = O(sequence_term, (sym, S.Infinity))
503
+
504
+ ### --------- p-series test (1/n**p) ---------- ###
505
+ p_series_test = order.expr.match(sym**p)
506
+ if p_series_test is not None:
507
+ if p_series_test[p] < -1:
508
+ return S.true
509
+ if p_series_test[p] >= -1:
510
+ return S.false
511
+
512
+ ### ------------- comparison test ------------- ###
513
+ # 1/(n**p*log(n)**q*log(log(n))**r) comparison
514
+ n_log_test = (order.expr.match(1/(sym**p*log(1/sym)**q*log(-log(1/sym))**r)) or
515
+ order.expr.match(1/(sym**p*(-log(1/sym))**q*log(-log(1/sym))**r)))
516
+ if n_log_test is not None:
517
+ if (n_log_test[p] > 1 or
518
+ (n_log_test[p] == 1 and n_log_test[q] > 1) or
519
+ (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
520
+ return S.true
521
+ return S.false
522
+
523
+ ### ------------- Limit comparison test -----------###
524
+ # (1/n) comparison
525
+ try:
526
+ lim_comp = limit_seq(sym*sequence_term, sym)
527
+ if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
528
+ return S.false
529
+ except NotImplementedError:
530
+ pass
531
+
532
+ ### ----------- ratio test ---------------- ###
533
+ next_sequence_term = sequence_term.xreplace({sym: sym + 1})
534
+ from sympy.simplify.combsimp import combsimp
535
+ from sympy.simplify.powsimp import powsimp
536
+ ratio = combsimp(powsimp(next_sequence_term/sequence_term))
537
+ try:
538
+ lim_ratio = limit_seq(ratio, sym)
539
+ if lim_ratio is not None and lim_ratio.is_number:
540
+ if abs(lim_ratio) > 1:
541
+ return S.false
542
+ if abs(lim_ratio) < 1:
543
+ return S.true
544
+ except NotImplementedError:
545
+ lim_ratio = None
546
+
547
+ ### ---------- Raabe's test -------------- ###
548
+ if lim_ratio == 1: # ratio test inconclusive
549
+ test_val = sym*(sequence_term/
550
+ sequence_term.subs(sym, sym + 1) - 1)
551
+ test_val = test_val.gammasimp()
552
+ try:
553
+ lim_val = limit_seq(test_val, sym)
554
+ if lim_val is not None and lim_val.is_number:
555
+ if lim_val > 1:
556
+ return S.true
557
+ if lim_val < 1:
558
+ return S.false
559
+ except NotImplementedError:
560
+ pass
561
+
562
+ ### ----------- root test ---------------- ###
563
+ # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
564
+ try:
565
+ lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
566
+ if lim_evaluated is not None and lim_evaluated.is_number:
567
+ if lim_evaluated < 1:
568
+ return S.true
569
+ if lim_evaluated > 1:
570
+ return S.false
571
+ except NotImplementedError:
572
+ pass
573
+
574
+ ### ------------- alternating series test ----------- ###
575
+ dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q)
576
+ if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
577
+ return S.true
578
+
579
+ ### ------------- integral test -------------- ###
580
+ check_interval = None
581
+ from sympy.solvers.solveset import solveset
582
+ maxima = solveset(sequence_term.diff(sym), sym, interval)
583
+ if not maxima:
584
+ check_interval = interval
585
+ elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
586
+ check_interval = Interval(maxima.sup, interval.sup)
587
+ if (check_interval is not None and
588
+ (is_decreasing(sequence_term, check_interval) or
589
+ is_decreasing(-sequence_term, check_interval))):
590
+ integral_val = Integral(
591
+ sequence_term, (sym, lower_limit, upper_limit))
592
+ try:
593
+ integral_val_evaluated = integral_val.doit()
594
+ if integral_val_evaluated.is_number:
595
+ return S(integral_val_evaluated.is_finite)
596
+ except NotImplementedError:
597
+ pass
598
+
599
+ ### ----- Dirichlet and bounded times convergent tests ----- ###
600
+ # TODO
601
+ #
602
+ # Dirichlet_test
603
+ # https://en.wikipedia.org/wiki/Dirichlet%27s_test
604
+ #
605
+ # Bounded times convergent test
606
+ # It is based on comparison theorems for series.
607
+ # In particular, if the general term of a series can
608
+ # be written as a product of two terms a_n and b_n
609
+ # and if a_n is bounded and if Sum(b_n) is absolutely
610
+ # convergent, then the original series Sum(a_n * b_n)
611
+ # is absolutely convergent and so convergent.
612
+ #
613
+ # The following code can grows like 2**n where n is the
614
+ # number of args in order.expr
615
+ # Possibly combined with the potentially slow checks
616
+ # inside the loop, could make this test extremely slow
617
+ # for larger summation expressions.
618
+
619
+ if order.expr.is_Mul:
620
+ args = order.expr.args
621
+ argset = set(args)
622
+
623
+ ### -------------- Dirichlet tests -------------- ###
624
+ m = Dummy('m', integer=True)
625
+ def _dirichlet_test(g_n):
626
+ try:
627
+ ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
628
+ if ing_val is not None and ing_val.is_finite:
629
+ return S.true
630
+ except NotImplementedError:
631
+ pass
632
+
633
+ ### -------- bounded times convergent test ---------###
634
+ def _bounded_convergent_test(g1_n, g2_n):
635
+ try:
636
+ lim_val = limit_seq(g1_n, sym)
637
+ if lim_val is not None and (lim_val.is_finite or (
638
+ isinstance(lim_val, AccumulationBounds)
639
+ and (lim_val.max - lim_val.min).is_finite)):
640
+ if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
641
+ return S.true
642
+ except NotImplementedError:
643
+ pass
644
+
645
+ for n in range(1, len(argset)):
646
+ for a_tuple in itertools.combinations(args, n):
647
+ b_set = argset - set(a_tuple)
648
+ a_n = Mul(*a_tuple)
649
+ b_n = Mul(*b_set)
650
+
651
+ if is_decreasing(a_n, interval):
652
+ dirich = _dirichlet_test(b_n)
653
+ if dirich is not None:
654
+ return dirich
655
+
656
+ bc_test = _bounded_convergent_test(a_n, b_n)
657
+ if bc_test is not None:
658
+ return bc_test
659
+
660
+ _sym = self.limits[0][0]
661
+ sequence_term = sequence_term.xreplace({sym: _sym})
662
+ raise NotImplementedError("The algorithm to find the Sum convergence of %s "
663
+ "is not yet implemented" % (sequence_term))
664
+
665
+ def is_absolutely_convergent(self):
666
+ """
667
+ Checks for the absolute convergence of an infinite series.
668
+
669
+ Same as checking convergence of absolute value of sequence_term of
670
+ an infinite series.
671
+
672
+ References
673
+ ==========
674
+
675
+ .. [1] https://en.wikipedia.org/wiki/Absolute_convergence
676
+
677
+ Examples
678
+ ========
679
+
680
+ >>> from sympy import Sum, Symbol, oo
681
+ >>> n = Symbol('n', integer=True)
682
+ >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
683
+ False
684
+ >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
685
+ True
686
+
687
+ See Also
688
+ ========
689
+
690
+ Sum.is_convergent
691
+ """
692
+ return Sum(abs(self.function), self.limits).is_convergent()
693
+
694
+ def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True):
695
+ """
696
+ Return an Euler-Maclaurin approximation of self, where m is the
697
+ number of leading terms to sum directly and n is the number of
698
+ terms in the tail.
699
+
700
+ With m = n = 0, this is simply the corresponding integral
701
+ plus a first-order endpoint correction.
702
+
703
+ Returns (s, e) where s is the Euler-Maclaurin approximation
704
+ and e is the estimated error (taken to be the magnitude of
705
+ the first omitted term in the tail):
706
+
707
+ >>> from sympy.abc import k, a, b
708
+ >>> from sympy import Sum
709
+ >>> Sum(1/k, (k, 2, 5)).doit().evalf()
710
+ 1.28333333333333
711
+ >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
712
+ >>> s
713
+ -log(2) + 7/20 + log(5)
714
+ >>> from sympy import sstr
715
+ >>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
716
+ (1.26629073187415, 0.0175000000000000)
717
+
718
+ The endpoints may be symbolic:
719
+
720
+ >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
721
+ >>> s
722
+ -log(a) + log(b) + 1/(2*b) + 1/(2*a)
723
+ >>> e
724
+ Abs(1/(12*b**2) - 1/(12*a**2))
725
+
726
+ If the function is a polynomial of degree at most 2n+1, the
727
+ Euler-Maclaurin formula becomes exact (and e = 0 is returned):
728
+
729
+ >>> Sum(k, (k, 2, b)).euler_maclaurin()
730
+ (b**2/2 + b/2 - 1, 0)
731
+ >>> Sum(k, (k, 2, b)).doit()
732
+ b**2/2 + b/2 - 1
733
+
734
+ With a nonzero eps specified, the summation is ended
735
+ as soon as the remainder term is less than the epsilon.
736
+ """
737
+ m = int(m)
738
+ n = int(n)
739
+ f = self.function
740
+ if len(self.limits) != 1:
741
+ raise ValueError("More than 1 limit")
742
+ i, a, b = self.limits[0]
743
+ if (a > b) == True:
744
+ if a - b == 1:
745
+ return S.Zero, S.Zero
746
+ a, b = b + 1, a - 1
747
+ f = -f
748
+ s = S.Zero
749
+ if m:
750
+ if b.is_Integer and a.is_Integer:
751
+ m = min(m, b - a + 1)
752
+ if not eps or f.is_polynomial(i):
753
+ s = Add(*[f.subs(i, a + k) for k in range(m)])
754
+ else:
755
+ term = f.subs(i, a)
756
+ if term:
757
+ test = abs(term.evalf(3)) < eps
758
+ if test == True:
759
+ return s, abs(term)
760
+ elif not (test == False):
761
+ # a symbolic Relational class, can't go further
762
+ return term, S.Zero
763
+ s = term
764
+ for k in range(1, m):
765
+ term = f.subs(i, a + k)
766
+ if abs(term.evalf(3)) < eps and term != 0:
767
+ return s, abs(term)
768
+ s += term
769
+ if b - a + 1 == m:
770
+ return s, S.Zero
771
+ a += m
772
+ x = Dummy('x')
773
+ I = Integral(f.subs(i, x), (x, a, b))
774
+ if eval_integral:
775
+ I = I.doit()
776
+ s += I
777
+
778
+ def fpoint(expr):
779
+ if b is S.Infinity:
780
+ return expr.subs(i, a), 0
781
+ return expr.subs(i, a), expr.subs(i, b)
782
+ fa, fb = fpoint(f)
783
+ iterm = (fa + fb)/2
784
+ g = f.diff(i)
785
+ for k in range(1, n + 2):
786
+ ga, gb = fpoint(g)
787
+ term = bernoulli(2*k)/factorial(2*k)*(gb - ga)
788
+ if k > n:
789
+ break
790
+ if eps and term:
791
+ term_evalf = term.evalf(3)
792
+ if term_evalf is S.NaN:
793
+ return S.NaN, S.NaN
794
+ if abs(term_evalf) < eps:
795
+ break
796
+ s += term
797
+ g = g.diff(i, 2, simplify=False)
798
+ return s + iterm, abs(term)
799
+
800
+
801
+ def reverse_order(self, *indices):
802
+ """
803
+ Reverse the order of a limit in a Sum.
804
+
805
+ Explanation
806
+ ===========
807
+
808
+ ``reverse_order(self, *indices)`` reverses some limits in the expression
809
+ ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in
810
+ the argument ``indices`` specify some indices whose limits get reversed.
811
+ These selectors are either variable names or numerical indices counted
812
+ starting from the inner-most limit tuple.
813
+
814
+ Examples
815
+ ========
816
+
817
+ >>> from sympy import Sum
818
+ >>> from sympy.abc import x, y, a, b, c, d
819
+
820
+ >>> Sum(x, (x, 0, 3)).reverse_order(x)
821
+ Sum(-x, (x, 4, -1))
822
+ >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
823
+ Sum(x*y, (x, 6, 0), (y, 7, -1))
824
+ >>> Sum(x, (x, a, b)).reverse_order(x)
825
+ Sum(-x, (x, b + 1, a - 1))
826
+ >>> Sum(x, (x, a, b)).reverse_order(0)
827
+ Sum(-x, (x, b + 1, a - 1))
828
+
829
+ While one should prefer variable names when specifying which limits
830
+ to reverse, the index counting notation comes in handy in case there
831
+ are several symbols with the same name.
832
+
833
+ >>> S = Sum(x**2, (x, a, b), (x, c, d))
834
+ >>> S
835
+ Sum(x**2, (x, a, b), (x, c, d))
836
+ >>> S0 = S.reverse_order(0)
837
+ >>> S0
838
+ Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
839
+ >>> S1 = S0.reverse_order(1)
840
+ >>> S1
841
+ Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1))
842
+
843
+ Of course we can mix both notations:
844
+
845
+ >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
846
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
847
+ >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
848
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
849
+
850
+ See Also
851
+ ========
852
+
853
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit,
854
+ sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
855
+
856
+ References
857
+ ==========
858
+
859
+ .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
860
+ Volume 28 Issue 2, April 1981, Pages 305-350
861
+ https://dl.acm.org/doi/10.1145/322248.322255
862
+ """
863
+ l_indices = list(indices)
864
+
865
+ for i, indx in enumerate(l_indices):
866
+ if not isinstance(indx, int):
867
+ l_indices[i] = self.index(indx)
868
+
869
+ e = 1
870
+ limits = []
871
+ for i, limit in enumerate(self.limits):
872
+ l = limit
873
+ if i in l_indices:
874
+ e = -e
875
+ l = (limit[0], limit[2] + 1, limit[1] - 1)
876
+ limits.append(l)
877
+
878
+ return Sum(e * self.function, *limits)
879
+
880
+ def _eval_rewrite_as_Product(self, *args, **kwargs):
881
+ from sympy.concrete.products import Product
882
+ if self.function.is_extended_real:
883
+ return log(Product(exp(self.function), *self.limits))
884
+
885
+
886
+ def summation(f, *symbols, **kwargs):
887
+ r"""
888
+ Compute the summation of f with respect to symbols.
889
+
890
+ Explanation
891
+ ===========
892
+
893
+ The notation for symbols is similar to the notation used in Integral.
894
+ summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
895
+ i.e.,
896
+
897
+ ::
898
+
899
+ b
900
+ ____
901
+ \ `
902
+ summation(f, (i, a, b)) = ) f
903
+ /___,
904
+ i = a
905
+
906
+ If it cannot compute the sum, it returns an unevaluated Sum object.
907
+ Repeated sums can be computed by introducing additional symbols tuples::
908
+
909
+ Examples
910
+ ========
911
+
912
+ >>> from sympy import summation, oo, symbols, log
913
+ >>> i, n, m = symbols('i n m', integer=True)
914
+
915
+ >>> summation(2*i - 1, (i, 1, n))
916
+ n**2
917
+ >>> summation(1/2**i, (i, 0, oo))
918
+ 2
919
+ >>> summation(1/log(n)**n, (n, 2, oo))
920
+ Sum(log(n)**(-n), (n, 2, oo))
921
+ >>> summation(i, (i, 0, n), (n, 0, m))
922
+ m**3/6 + m**2/2 + m/3
923
+
924
+ >>> from sympy.abc import x
925
+ >>> from sympy import factorial
926
+ >>> summation(x**n/factorial(n), (n, 0, oo))
927
+ exp(x)
928
+
929
+ See Also
930
+ ========
931
+
932
+ Sum
933
+ Product, sympy.concrete.products.product
934
+
935
+ """
936
+ return Sum(f, *symbols, **kwargs).doit(deep=False)
937
+
938
+
939
+ def telescopic_direct(L, R, n, limits):
940
+ """
941
+ Returns the direct summation of the terms of a telescopic sum
942
+
943
+ Explanation
944
+ ===========
945
+
946
+ L is the term with lower index
947
+ R is the term with higher index
948
+ n difference between the indexes of L and R
949
+
950
+ Examples
951
+ ========
952
+
953
+ >>> from sympy.concrete.summations import telescopic_direct
954
+ >>> from sympy.abc import k, a, b
955
+ >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
956
+ -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a
957
+
958
+ """
959
+ (i, a, b) = limits
960
+ return Add(*[L.subs(i, a + m) + R.subs(i, b - m) for m in range(n)])
961
+
962
+
963
+ def telescopic(L, R, limits):
964
+ '''
965
+ Tries to perform the summation using the telescopic property.
966
+
967
+ Return None if not possible.
968
+ '''
969
+ (i, a, b) = limits
970
+ if L.is_Add or R.is_Add:
971
+ return None
972
+
973
+ # We want to solve(L.subs(i, i + m) + R, m)
974
+ # First we try a simple match since this does things that
975
+ # solve doesn't do, e.g. solve(cos(k+m)-cos(k), m) gives
976
+ # a more complicated solution than m == 0.
977
+
978
+ k = Wild("k")
979
+ sol = (-R).match(L.subs(i, i + k))
980
+ s = None
981
+ if sol and k in sol:
982
+ s = sol[k]
983
+ if not (s.is_Integer and L.subs(i, i + s) + R == 0):
984
+ # invalid match or match didn't work
985
+ s = None
986
+
987
+ # But there are things that match doesn't do that solve
988
+ # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1
989
+
990
+ if s is None:
991
+ m = Dummy('m')
992
+ try:
993
+ from sympy.solvers.solvers import solve
994
+ sol = solve(L.subs(i, i + m) + R, m) or []
995
+ except NotImplementedError:
996
+ return None
997
+ sol = [si for si in sol if si.is_Integer and
998
+ (L.subs(i, i + si) + R).expand().is_zero]
999
+ if len(sol) != 1:
1000
+ return None
1001
+ s = sol[0]
1002
+
1003
+ if s < 0:
1004
+ return telescopic_direct(R, L, abs(s), (i, a, b))
1005
+ elif s > 0:
1006
+ return telescopic_direct(L, R, s, (i, a, b))
1007
+
1008
+
1009
+ def eval_sum(f, limits):
1010
+ (i, a, b) = limits
1011
+ if f.is_zero:
1012
+ return S.Zero
1013
+ if i not in f.free_symbols:
1014
+ return f*(b - a + 1)
1015
+ if a == b:
1016
+ return f.subs(i, a)
1017
+ if isinstance(f, Piecewise):
1018
+ if not any(i in arg.args[1].free_symbols for arg in f.args):
1019
+ # Piecewise conditions do not depend on the dummy summation variable,
1020
+ # therefore we can fold: Sum(Piecewise((e, c), ...), limits)
1021
+ # --> Piecewise((Sum(e, limits), c), ...)
1022
+ newargs = []
1023
+ for arg in f.args:
1024
+ newexpr = eval_sum(arg.expr, limits)
1025
+ if newexpr is None:
1026
+ return None
1027
+ newargs.append((newexpr, arg.cond))
1028
+ return f.func(*newargs)
1029
+
1030
+ if f.has(KroneckerDelta):
1031
+ from .delta import deltasummation, _has_simple_delta
1032
+ f = f.replace(
1033
+ lambda x: isinstance(x, Sum),
1034
+ lambda x: x.factor()
1035
+ )
1036
+ if _has_simple_delta(f, limits[0]):
1037
+ return deltasummation(f, limits)
1038
+
1039
+ dif = b - a
1040
+ definite = dif.is_Integer
1041
+ # Doing it directly may be faster if there are very few terms.
1042
+ if definite and (dif < 100):
1043
+ return eval_sum_direct(f, (i, a, b))
1044
+ if isinstance(f, Piecewise):
1045
+ return None
1046
+ # Try to do it symbolically. Even when the number of terms is
1047
+ # known, this can save time when b-a is big.
1048
+ value = eval_sum_symbolic(f.expand(), (i, a, b))
1049
+ if value is not None:
1050
+ return value
1051
+ # Do it directly
1052
+ if definite:
1053
+ return eval_sum_direct(f, (i, a, b))
1054
+
1055
+
1056
+ def eval_sum_direct(expr, limits):
1057
+ """
1058
+ Evaluate expression directly, but perform some simple checks first
1059
+ to possibly result in a smaller expression and faster execution.
1060
+ """
1061
+ (i, a, b) = limits
1062
+
1063
+ dif = b - a
1064
+ # Linearity
1065
+ if expr.is_Mul:
1066
+ # Try factor out everything not including i
1067
+ without_i, with_i = expr.as_independent(i)
1068
+ if without_i != 1:
1069
+ s = eval_sum_direct(with_i, (i, a, b))
1070
+ if s:
1071
+ r = without_i*s
1072
+ if r is not S.NaN:
1073
+ return r
1074
+ else:
1075
+ # Try term by term
1076
+ L, R = expr.as_two_terms()
1077
+
1078
+ if not L.has(i):
1079
+ sR = eval_sum_direct(R, (i, a, b))
1080
+ if sR:
1081
+ return L*sR
1082
+
1083
+ if not R.has(i):
1084
+ sL = eval_sum_direct(L, (i, a, b))
1085
+ if sL:
1086
+ return sL*R
1087
+
1088
+ # do this whether its an Add or Mul
1089
+ # e.g. apart(1/(25*i**2 + 45*i + 14)) and
1090
+ # apart(1/((5*i + 2)*(5*i + 7))) ->
1091
+ # -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
1092
+ try:
1093
+ expr = apart(expr, i) # see if it becomes an Add
1094
+ except PolynomialError:
1095
+ pass
1096
+
1097
+ if expr.is_Add:
1098
+ # Try factor out everything not including i
1099
+ without_i, with_i = expr.as_independent(i)
1100
+ if without_i != 0:
1101
+ s = eval_sum_direct(with_i, (i, a, b))
1102
+ if s:
1103
+ r = without_i*(dif + 1) + s
1104
+ if r is not S.NaN:
1105
+ return r
1106
+ else:
1107
+ # Try term by term
1108
+ L, R = expr.as_two_terms()
1109
+ lsum = eval_sum_direct(L, (i, a, b))
1110
+ rsum = eval_sum_direct(R, (i, a, b))
1111
+
1112
+ if None not in (lsum, rsum):
1113
+ r = lsum + rsum
1114
+ if r is not S.NaN:
1115
+ return r
1116
+
1117
+ return Add(*[expr.subs(i, a + j) for j in range(dif + 1)])
1118
+
1119
+
1120
+ def eval_sum_symbolic(f, limits):
1121
+ f_orig = f
1122
+ (i, a, b) = limits
1123
+ if not f.has(i):
1124
+ return f*(b - a + 1)
1125
+
1126
+ # Linearity
1127
+ if f.is_Mul:
1128
+ # Try factor out everything not including i
1129
+ without_i, with_i = f.as_independent(i)
1130
+ if without_i != 1:
1131
+ s = eval_sum_symbolic(with_i, (i, a, b))
1132
+ if s:
1133
+ r = without_i*s
1134
+ if r is not S.NaN:
1135
+ return r
1136
+ else:
1137
+ # Try term by term
1138
+ L, R = f.as_two_terms()
1139
+
1140
+ if not L.has(i):
1141
+ sR = eval_sum_symbolic(R, (i, a, b))
1142
+ if sR:
1143
+ return L*sR
1144
+
1145
+ if not R.has(i):
1146
+ sL = eval_sum_symbolic(L, (i, a, b))
1147
+ if sL:
1148
+ return sL*R
1149
+
1150
+ # do this whether its an Add or Mul
1151
+ # e.g. apart(1/(25*i**2 + 45*i + 14)) and
1152
+ # apart(1/((5*i + 2)*(5*i + 7))) ->
1153
+ # -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
1154
+ try:
1155
+ f = apart(f, i)
1156
+ except PolynomialError:
1157
+ pass
1158
+
1159
+ if f.is_Add:
1160
+ L, R = f.as_two_terms()
1161
+ lrsum = telescopic(L, R, (i, a, b))
1162
+
1163
+ if lrsum:
1164
+ return lrsum
1165
+
1166
+ # Try factor out everything not including i
1167
+ without_i, with_i = f.as_independent(i)
1168
+ if without_i != 0:
1169
+ s = eval_sum_symbolic(with_i, (i, a, b))
1170
+ if s:
1171
+ r = without_i*(b - a + 1) + s
1172
+ if r is not S.NaN:
1173
+ return r
1174
+ else:
1175
+ # Try term by term
1176
+ lsum = eval_sum_symbolic(L, (i, a, b))
1177
+ rsum = eval_sum_symbolic(R, (i, a, b))
1178
+
1179
+ if None not in (lsum, rsum):
1180
+ r = lsum + rsum
1181
+ if r is not S.NaN:
1182
+ return r
1183
+
1184
+
1185
+ # Polynomial terms with Faulhaber's formula
1186
+ n = Wild('n')
1187
+ result = f.match(i**n)
1188
+
1189
+ if result is not None:
1190
+ n = result[n]
1191
+
1192
+ if n.is_Integer:
1193
+ if n >= 0:
1194
+ if (b is S.Infinity and a is not S.NegativeInfinity) or \
1195
+ (a is S.NegativeInfinity and b is not S.Infinity):
1196
+ return S.Infinity
1197
+ return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand()
1198
+ elif a.is_Integer and a >= 1:
1199
+ if n == -1:
1200
+ return harmonic(b) - harmonic(a - 1)
1201
+ else:
1202
+ return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))
1203
+
1204
+ if not (a.has(S.Infinity, S.NegativeInfinity) or
1205
+ b.has(S.Infinity, S.NegativeInfinity)):
1206
+ # Geometric terms
1207
+ c1 = Wild('c1', exclude=[i])
1208
+ c2 = Wild('c2', exclude=[i])
1209
+ c3 = Wild('c3', exclude=[i])
1210
+ wexp = Wild('wexp')
1211
+
1212
+ # Here we first attempt powsimp on f for easier matching with the
1213
+ # exponential pattern, and attempt expansion on the exponent for easier
1214
+ # matching with the linear pattern.
1215
+ e = f.powsimp().match(c1 ** wexp)
1216
+ if e is not None:
1217
+ e_exp = e.pop(wexp).expand().match(c2*i + c3)
1218
+ if e_exp is not None:
1219
+ e.update(e_exp)
1220
+
1221
+ p = (c1**c3).subs(e)
1222
+ q = (c1**c2).subs(e)
1223
+ r = p*(q**a - q**(b + 1))/(1 - q)
1224
+ l = p*(b - a + 1)
1225
+ return Piecewise((l, Eq(q, S.One)), (r, True))
1226
+
1227
+ r = gosper_sum(f, (i, a, b))
1228
+
1229
+ if isinstance(r, (Mul,Add)):
1230
+ from sympy.simplify.radsimp import denom
1231
+ from sympy.solvers.solvers import solve
1232
+ non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
1233
+ den = denom(together(r))
1234
+ den_sym = non_limit & den.free_symbols
1235
+ args = []
1236
+ for v in ordered(den_sym):
1237
+ try:
1238
+ s = solve(den, v)
1239
+ m = Eq(v, s[0]) if s else S.false
1240
+ if m != False:
1241
+ args.append((Sum(f_orig.subs(*m.args), limits).doit(), m))
1242
+ break
1243
+ except NotImplementedError:
1244
+ continue
1245
+
1246
+ args.append((r, True))
1247
+ return Piecewise(*args)
1248
+
1249
+ if r not in (None, S.NaN):
1250
+ return r
1251
+
1252
+ h = eval_sum_hyper(f_orig, (i, a, b))
1253
+ if h is not None:
1254
+ return h
1255
+
1256
+ r = eval_sum_residue(f_orig, (i, a, b))
1257
+ if r is not None:
1258
+ return r
1259
+
1260
+ factored = f_orig.factor()
1261
+ if factored != f_orig:
1262
+ return eval_sum_symbolic(factored, (i, a, b))
1263
+
1264
+
1265
+ def _eval_sum_hyper(f, i, a):
1266
+ """ Returns (res, cond). Sums from a to oo. """
1267
+ if a != 0:
1268
+ return _eval_sum_hyper(f.subs(i, i + a), i, 0)
1269
+
1270
+ if f.subs(i, 0) == 0:
1271
+ from sympy.simplify.simplify import simplify
1272
+ if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0:
1273
+ return S.Zero, True
1274
+ return _eval_sum_hyper(f.subs(i, i + 1), i, 0)
1275
+
1276
+ from sympy.simplify.simplify import hypersimp
1277
+ hs = hypersimp(f, i)
1278
+ if hs is None:
1279
+ return None
1280
+
1281
+ if isinstance(hs, Float):
1282
+ from sympy.simplify.simplify import nsimplify
1283
+ hs = nsimplify(hs)
1284
+
1285
+ from sympy.simplify.combsimp import combsimp
1286
+ from sympy.simplify.hyperexpand import hyperexpand
1287
+ from sympy.simplify.radsimp import fraction
1288
+ numer, denom = fraction(factor(hs))
1289
+ top, topl = numer.as_coeff_mul(i)
1290
+ bot, botl = denom.as_coeff_mul(i)
1291
+ ab = [top, bot]
1292
+ factors = [topl, botl]
1293
+ params = [[], []]
1294
+ for k in range(2):
1295
+ for fac in factors[k]:
1296
+ mul = 1
1297
+ if fac.is_Pow:
1298
+ mul = fac.exp
1299
+ fac = fac.base
1300
+ if not mul.is_Integer:
1301
+ return None
1302
+ p = Poly(fac, i)
1303
+ if p.degree() != 1:
1304
+ return None
1305
+ m, n = p.all_coeffs()
1306
+ ab[k] *= m**mul
1307
+ params[k] += [n/m]*mul
1308
+
1309
+ # Add "1" to numerator parameters, to account for implicit n! in
1310
+ # hypergeometric series.
1311
+ ap = params[0] + [1]
1312
+ bq = params[1]
1313
+ x = ab[0]/ab[1]
1314
+ h = hyper(ap, bq, x)
1315
+ f = combsimp(f)
1316
+ return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
1317
+
1318
+
1319
+ def eval_sum_hyper(f, i_a_b):
1320
+ i, a, b = i_a_b
1321
+
1322
+ if f.is_hypergeometric(i) is False:
1323
+ return
1324
+
1325
+ if (b - a).is_Integer:
1326
+ # We are never going to do better than doing the sum in the obvious way
1327
+ return None
1328
+
1329
+ old_sum = Sum(f, (i, a, b))
1330
+
1331
+ if b != S.Infinity:
1332
+ if a is S.NegativeInfinity:
1333
+ res = _eval_sum_hyper(f.subs(i, -i), i, -b)
1334
+ if res is not None:
1335
+ return Piecewise(res, (old_sum, True))
1336
+ else:
1337
+ n_illegal = lambda x: sum(x.count(_) for _ in _illegal)
1338
+ had = n_illegal(f)
1339
+ # check that no extra illegals are introduced
1340
+ res1 = _eval_sum_hyper(f, i, a)
1341
+ if res1 is None or n_illegal(res1) > had:
1342
+ return
1343
+ res2 = _eval_sum_hyper(f, i, b + 1)
1344
+ if res2 is None or n_illegal(res2) > had:
1345
+ return
1346
+ (res1, cond1), (res2, cond2) = res1, res2
1347
+ cond = And(cond1, cond2)
1348
+ if cond == False:
1349
+ return None
1350
+ return Piecewise((res1 - res2, cond), (old_sum, True))
1351
+
1352
+ if a is S.NegativeInfinity:
1353
+ res1 = _eval_sum_hyper(f.subs(i, -i), i, 1)
1354
+ res2 = _eval_sum_hyper(f, i, 0)
1355
+ if res1 is None or res2 is None:
1356
+ return None
1357
+ res1, cond1 = res1
1358
+ res2, cond2 = res2
1359
+ cond = And(cond1, cond2)
1360
+ if cond == False or cond.as_set() == S.EmptySet:
1361
+ return None
1362
+ return Piecewise((res1 + res2, cond), (old_sum, True))
1363
+
1364
+ # Now b == oo, a != -oo
1365
+ res = _eval_sum_hyper(f, i, a)
1366
+ if res is not None:
1367
+ r, c = res
1368
+ if c == False:
1369
+ if r.is_number:
1370
+ f = f.subs(i, Dummy('i', integer=True, positive=True) + a)
1371
+ if f.is_positive or f.is_zero:
1372
+ return S.Infinity
1373
+ elif f.is_negative:
1374
+ return S.NegativeInfinity
1375
+ return None
1376
+ return Piecewise(res, (old_sum, True))
1377
+
1378
+
1379
+ def eval_sum_residue(f, i_a_b):
1380
+ r"""Compute the infinite summation with residues
1381
+
1382
+ Notes
1383
+ =====
1384
+
1385
+ If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
1386
+ some infinite summations can be computed by the following residue
1387
+ evaluations.
1388
+
1389
+ .. math::
1390
+ \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
1391
+ -\pi \sum_{\alpha|g(\alpha)=0}
1392
+ \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)
1393
+
1394
+ .. math::
1395
+ \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
1396
+ -\pi \sum_{\alpha|g(\alpha)=0}
1397
+ \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)
1398
+
1399
+ Examples
1400
+ ========
1401
+
1402
+ >>> from sympy import Sum, oo, Symbol
1403
+ >>> x = Symbol('x')
1404
+
1405
+ Doubly infinite series of rational functions.
1406
+
1407
+ >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
1408
+ pi/tanh(pi)
1409
+
1410
+ Doubly infinite alternating series of rational functions.
1411
+
1412
+ >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
1413
+ pi/sinh(pi)
1414
+
1415
+ Infinite series of even rational functions.
1416
+
1417
+ >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
1418
+ 1/2 + pi/(2*tanh(pi))
1419
+
1420
+ Infinite series of alternating even rational functions.
1421
+
1422
+ >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
1423
+ pi/(2*sinh(pi)) + 1/2
1424
+
1425
+ This also have heuristics to transform arbitrarily shifted summand or
1426
+ arbitrarily shifted summation range to the canonical problem the
1427
+ formula can handle.
1428
+
1429
+ >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
1430
+ 1/2 + pi/(2*tanh(pi))
1431
+ >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
1432
+ 1/2 + pi/(2*tanh(pi))
1433
+ >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
1434
+ -1/2 + pi/(2*tanh(pi))
1435
+ >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
1436
+ -1 + pi/(2*tanh(pi))
1437
+
1438
+ References
1439
+ ==========
1440
+
1441
+ .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf
1442
+
1443
+ .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
1444
+ In: Complex Analysis with Applications.
1445
+ Undergraduate Texts in Mathematics. Springer, Cham.
1446
+ https://doi.org/10.1007/978-3-319-94063-2_5
1447
+ """
1448
+ i, a, b = i_a_b
1449
+
1450
+ def is_even_function(numer, denom):
1451
+ """Test if the rational function is an even function"""
1452
+ numer_even = all(i % 2 == 0 for (i,) in numer.monoms())
1453
+ denom_even = all(i % 2 == 0 for (i,) in denom.monoms())
1454
+ numer_odd = all(i % 2 == 1 for (i,) in numer.monoms())
1455
+ denom_odd = all(i % 2 == 1 for (i,) in denom.monoms())
1456
+ return (numer_even and denom_even) or (numer_odd and denom_odd)
1457
+
1458
+ def match_rational(f, i):
1459
+ numer, denom = f.as_numer_denom()
1460
+ try:
1461
+ (numer, denom), opt = parallel_poly_from_expr((numer, denom), i)
1462
+ except (PolificationFailed, PolynomialError):
1463
+ return None
1464
+ return numer, denom
1465
+
1466
+ def get_poles(denom):
1467
+ roots = denom.sqf_part().all_roots()
1468
+ roots = sift(roots, lambda x: x.is_integer)
1469
+ if None in roots:
1470
+ return None
1471
+ int_roots, nonint_roots = roots[True], roots[False]
1472
+ return int_roots, nonint_roots
1473
+
1474
+ def get_shift(denom):
1475
+ n = denom.degree(i)
1476
+ a = denom.coeff_monomial(i**n)
1477
+ b = denom.coeff_monomial(i**(n-1))
1478
+ shift = - b / a / n
1479
+ return shift
1480
+
1481
+ #Need a dummy symbol with no assumptions set for get_residue_factor
1482
+ z = Dummy('z')
1483
+
1484
+ def get_residue_factor(numer, denom, alternating):
1485
+ residue_factor = (numer.as_expr() / denom.as_expr()).subs(i, z)
1486
+ if not alternating:
1487
+ residue_factor *= cot(S.Pi * z)
1488
+ else:
1489
+ residue_factor *= csc(S.Pi * z)
1490
+ return residue_factor
1491
+
1492
+ # We don't know how to deal with symbolic constants in summand
1493
+ if f.free_symbols - {i}:
1494
+ return None
1495
+
1496
+ if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)):
1497
+ return None
1498
+ if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)):
1499
+ return None
1500
+
1501
+ # Quick exit heuristic for the sums which doesn't have infinite range
1502
+ if a != S.NegativeInfinity and b != S.Infinity:
1503
+ return None
1504
+
1505
+ match = match_rational(f, i)
1506
+ if match:
1507
+ alternating = False
1508
+ numer, denom = match
1509
+ else:
1510
+ match = match_rational(f / S.NegativeOne**i, i)
1511
+ if match:
1512
+ alternating = True
1513
+ numer, denom = match
1514
+ else:
1515
+ return None
1516
+
1517
+ if denom.degree(i) - numer.degree(i) < 2:
1518
+ return None
1519
+
1520
+ if (a, b) == (S.NegativeInfinity, S.Infinity):
1521
+ poles = get_poles(denom)
1522
+ if poles is None:
1523
+ return None
1524
+ int_roots, nonint_roots = poles
1525
+
1526
+ if int_roots:
1527
+ return None
1528
+
1529
+ residue_factor = get_residue_factor(numer, denom, alternating)
1530
+ residues = [residue(residue_factor, z, root) for root in nonint_roots]
1531
+ return -S.Pi * sum(residues)
1532
+
1533
+ if not (a.is_finite and b is S.Infinity):
1534
+ return None
1535
+
1536
+ if not is_even_function(numer, denom):
1537
+ # Try shifting summation and check if the summand can be made
1538
+ # and even function from the origin.
1539
+ # Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s))
1540
+ shift = get_shift(denom)
1541
+
1542
+ if not shift.is_Integer:
1543
+ return None
1544
+ if shift == 0:
1545
+ return None
1546
+
1547
+ numer = numer.shift(shift)
1548
+ denom = denom.shift(shift)
1549
+
1550
+ if not is_even_function(numer, denom):
1551
+ return None
1552
+
1553
+ if alternating:
1554
+ f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr())
1555
+ else:
1556
+ f = numer.as_expr() / denom.as_expr()
1557
+ return eval_sum_residue(f, (i, a-shift, b-shift))
1558
+
1559
+ poles = get_poles(denom)
1560
+ if poles is None:
1561
+ return None
1562
+ int_roots, nonint_roots = poles
1563
+
1564
+ if int_roots:
1565
+ int_roots = [int(root) for root in int_roots]
1566
+ int_roots_max = max(int_roots)
1567
+ int_roots_min = min(int_roots)
1568
+ # Integer valued poles must be next to each other
1569
+ # and also symmetric from origin (Because the function is even)
1570
+ if not len(int_roots) == int_roots_max - int_roots_min + 1:
1571
+ return None
1572
+
1573
+ # Check whether the summation indices contain poles
1574
+ if a <= max(int_roots):
1575
+ return None
1576
+
1577
+ residue_factor = get_residue_factor(numer, denom, alternating)
1578
+ residues = [residue(residue_factor, z, root) for root in int_roots + nonint_roots]
1579
+ full_sum = -S.Pi * sum(residues)
1580
+
1581
+ if not int_roots:
1582
+ # Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation
1583
+ # at the origin.
1584
+ half_sum = (full_sum + f.xreplace({i: 0})) / 2
1585
+
1586
+ # Add and subtract extraneous evaluations
1587
+ extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)]
1588
+ extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))]
1589
+ result = half_sum + sum(extraneous_neg) - sum(extraneous_pos)
1590
+
1591
+ return result
1592
+
1593
+ # Compute Sum(f, (i, min(poles) + 1, oo))
1594
+ half_sum = full_sum / 2
1595
+
1596
+ # Subtract extraneous evaluations
1597
+ extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))]
1598
+ result = half_sum - sum(extraneous)
1599
+
1600
+ return result
1601
+
1602
+
1603
+ def _eval_matrix_sum(expression):
1604
+ f = expression.function
1605
+ for n, limit in enumerate(expression.limits):
1606
+ i, a, b = limit
1607
+ dif = b - a
1608
+ if dif.is_Integer:
1609
+ if (dif < 0) == True:
1610
+ a, b = b + 1, a - 1
1611
+ f = -f
1612
+
1613
+ newf = eval_sum_direct(f, (i, a, b))
1614
+ if newf is not None:
1615
+ return newf.doit()
1616
+
1617
+
1618
+ def _dummy_with_inherited_properties_concrete(limits):
1619
+ """
1620
+ Return a Dummy symbol that inherits as many assumptions as possible
1621
+ from the provided symbol and limits.
1622
+
1623
+ If the symbol already has all True assumption shared by the limits
1624
+ then return None.
1625
+ """
1626
+ x, a, b = limits
1627
+ l = [a, b]
1628
+
1629
+ assumptions_to_consider = ['extended_nonnegative', 'nonnegative',
1630
+ 'extended_nonpositive', 'nonpositive',
1631
+ 'extended_positive', 'positive',
1632
+ 'extended_negative', 'negative',
1633
+ 'integer', 'rational', 'finite',
1634
+ 'zero', 'real', 'extended_real']
1635
+
1636
+ assumptions_to_keep = {}
1637
+ assumptions_to_add = {}
1638
+ for assum in assumptions_to_consider:
1639
+ assum_true = x._assumptions.get(assum, None)
1640
+ if assum_true:
1641
+ assumptions_to_keep[assum] = True
1642
+ elif all(getattr(i, 'is_' + assum) for i in l):
1643
+ assumptions_to_add[assum] = True
1644
+ if assumptions_to_add:
1645
+ assumptions_to_keep.update(assumptions_to_add)
1646
+ return Dummy('d', **assumptions_to_keep)
venv/lib/python3.10/site-packages/sympy/concrete/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_delta.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_gosper.cpython-310.pyc ADDED
Binary file (8.37 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_guess.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_products.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_sums_products.cpython-310.pyc ADDED
Binary file (62.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/concrete/tests/test_delta.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete import Sum
2
+ from sympy.concrete.delta import deltaproduct as dp, deltasummation as ds, _extract_delta
3
+ from sympy.core import Eq, S, symbols, oo
4
+ from sympy.functions import KroneckerDelta as KD, Piecewise, piecewise_fold
5
+ from sympy.logic import And
6
+ from sympy.testing.pytest import raises
7
+
8
+ i, j, k, l, m = symbols("i j k l m", integer=True, finite=True)
9
+ x, y = symbols("x y", commutative=False)
10
+
11
+
12
+ def test_deltaproduct_trivial():
13
+ assert dp(x, (j, 1, 0)) == 1
14
+ assert dp(x, (j, 1, 3)) == x**3
15
+ assert dp(x + y, (j, 1, 3)) == (x + y)**3
16
+ assert dp(x*y, (j, 1, 3)) == (x*y)**3
17
+ assert dp(KD(i, j), (k, 1, 3)) == KD(i, j)
18
+ assert dp(x*KD(i, j), (k, 1, 3)) == x**3*KD(i, j)
19
+ assert dp(x*y*KD(i, j), (k, 1, 3)) == (x*y)**3*KD(i, j)
20
+
21
+
22
+ def test_deltaproduct_basic():
23
+ assert dp(KD(i, j), (j, 1, 3)) == 0
24
+ assert dp(KD(i, j), (j, 1, 1)) == KD(i, 1)
25
+ assert dp(KD(i, j), (j, 2, 2)) == KD(i, 2)
26
+ assert dp(KD(i, j), (j, 3, 3)) == KD(i, 3)
27
+ assert dp(KD(i, j), (j, 1, k)) == KD(i, 1)*KD(k, 1) + KD(k, 0)
28
+ assert dp(KD(i, j), (j, k, 3)) == KD(i, 3)*KD(k, 3) + KD(k, 4)
29
+ assert dp(KD(i, j), (j, k, l)) == KD(i, l)*KD(k, l) + KD(k, l + 1)
30
+
31
+
32
+ def test_deltaproduct_mul_x_kd():
33
+ assert dp(x*KD(i, j), (j, 1, 3)) == 0
34
+ assert dp(x*KD(i, j), (j, 1, 1)) == x*KD(i, 1)
35
+ assert dp(x*KD(i, j), (j, 2, 2)) == x*KD(i, 2)
36
+ assert dp(x*KD(i, j), (j, 3, 3)) == x*KD(i, 3)
37
+ assert dp(x*KD(i, j), (j, 1, k)) == x*KD(i, 1)*KD(k, 1) + KD(k, 0)
38
+ assert dp(x*KD(i, j), (j, k, 3)) == x*KD(i, 3)*KD(k, 3) + KD(k, 4)
39
+ assert dp(x*KD(i, j), (j, k, l)) == x*KD(i, l)*KD(k, l) + KD(k, l + 1)
40
+
41
+
42
+ def test_deltaproduct_mul_add_x_y_kd():
43
+ assert dp((x + y)*KD(i, j), (j, 1, 3)) == 0
44
+ assert dp((x + y)*KD(i, j), (j, 1, 1)) == (x + y)*KD(i, 1)
45
+ assert dp((x + y)*KD(i, j), (j, 2, 2)) == (x + y)*KD(i, 2)
46
+ assert dp((x + y)*KD(i, j), (j, 3, 3)) == (x + y)*KD(i, 3)
47
+ assert dp((x + y)*KD(i, j), (j, 1, k)) == \
48
+ (x + y)*KD(i, 1)*KD(k, 1) + KD(k, 0)
49
+ assert dp((x + y)*KD(i, j), (j, k, 3)) == \
50
+ (x + y)*KD(i, 3)*KD(k, 3) + KD(k, 4)
51
+ assert dp((x + y)*KD(i, j), (j, k, l)) == \
52
+ (x + y)*KD(i, l)*KD(k, l) + KD(k, l + 1)
53
+
54
+
55
+ def test_deltaproduct_add_kd_kd():
56
+ assert dp(KD(i, k) + KD(j, k), (k, 1, 3)) == 0
57
+ assert dp(KD(i, k) + KD(j, k), (k, 1, 1)) == KD(i, 1) + KD(j, 1)
58
+ assert dp(KD(i, k) + KD(j, k), (k, 2, 2)) == KD(i, 2) + KD(j, 2)
59
+ assert dp(KD(i, k) + KD(j, k), (k, 3, 3)) == KD(i, 3) + KD(j, 3)
60
+ assert dp(KD(i, k) + KD(j, k), (k, 1, l)) == KD(l, 0) + \
61
+ KD(i, 1)*KD(l, 1) + KD(j, 1)*KD(l, 1) + \
62
+ KD(i, 1)*KD(j, 2)*KD(l, 2) + KD(j, 1)*KD(i, 2)*KD(l, 2)
63
+ assert dp(KD(i, k) + KD(j, k), (k, l, 3)) == KD(l, 4) + \
64
+ KD(i, 3)*KD(l, 3) + KD(j, 3)*KD(l, 3) + \
65
+ KD(i, 2)*KD(j, 3)*KD(l, 2) + KD(i, 3)*KD(j, 2)*KD(l, 2)
66
+ assert dp(KD(i, k) + KD(j, k), (k, l, m)) == KD(l, m + 1) + \
67
+ KD(i, m)*KD(l, m) + KD(j, m)*KD(l, m) + \
68
+ KD(i, m)*KD(j, m - 1)*KD(l, m - 1) + KD(i, m - 1)*KD(j, m)*KD(l, m - 1)
69
+
70
+
71
+ def test_deltaproduct_mul_x_add_kd_kd():
72
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, 3)) == 0
73
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, 1)) == x*(KD(i, 1) + KD(j, 1))
74
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 2, 2)) == x*(KD(i, 2) + KD(j, 2))
75
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 3, 3)) == x*(KD(i, 3) + KD(j, 3))
76
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, l)) == KD(l, 0) + \
77
+ x*KD(i, 1)*KD(l, 1) + x*KD(j, 1)*KD(l, 1) + \
78
+ x**2*KD(i, 1)*KD(j, 2)*KD(l, 2) + x**2*KD(j, 1)*KD(i, 2)*KD(l, 2)
79
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, l, 3)) == KD(l, 4) + \
80
+ x*KD(i, 3)*KD(l, 3) + x*KD(j, 3)*KD(l, 3) + \
81
+ x**2*KD(i, 2)*KD(j, 3)*KD(l, 2) + x**2*KD(i, 3)*KD(j, 2)*KD(l, 2)
82
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, l, m)) == KD(l, m + 1) + \
83
+ x*KD(i, m)*KD(l, m) + x*KD(j, m)*KD(l, m) + \
84
+ x**2*KD(i, m - 1)*KD(j, m)*KD(l, m - 1) + \
85
+ x**2*KD(i, m)*KD(j, m - 1)*KD(l, m - 1)
86
+
87
+
88
+ def test_deltaproduct_mul_add_x_y_add_kd_kd():
89
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 3)) == 0
90
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 1)) == \
91
+ (x + y)*(KD(i, 1) + KD(j, 1))
92
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 2, 2)) == \
93
+ (x + y)*(KD(i, 2) + KD(j, 2))
94
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 3, 3)) == \
95
+ (x + y)*(KD(i, 3) + KD(j, 3))
96
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, l)) == KD(l, 0) + \
97
+ (x + y)*KD(i, 1)*KD(l, 1) + (x + y)*KD(j, 1)*KD(l, 1) + \
98
+ (x + y)**2*KD(i, 1)*KD(j, 2)*KD(l, 2) + \
99
+ (x + y)**2*KD(j, 1)*KD(i, 2)*KD(l, 2)
100
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, l, 3)) == KD(l, 4) + \
101
+ (x + y)*KD(i, 3)*KD(l, 3) + (x + y)*KD(j, 3)*KD(l, 3) + \
102
+ (x + y)**2*KD(i, 2)*KD(j, 3)*KD(l, 2) + \
103
+ (x + y)**2*KD(i, 3)*KD(j, 2)*KD(l, 2)
104
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, l, m)) == KD(l, m + 1) + \
105
+ (x + y)*KD(i, m)*KD(l, m) + (x + y)*KD(j, m)*KD(l, m) + \
106
+ (x + y)**2*KD(i, m - 1)*KD(j, m)*KD(l, m - 1) + \
107
+ (x + y)**2*KD(i, m)*KD(j, m - 1)*KD(l, m - 1)
108
+
109
+
110
+ def test_deltaproduct_add_mul_x_y_mul_x_kd():
111
+ assert dp(x*y + x*KD(i, j), (j, 1, 3)) == (x*y)**3 + \
112
+ x*(x*y)**2*KD(i, 1) + (x*y)*x*(x*y)*KD(i, 2) + (x*y)**2*x*KD(i, 3)
113
+ assert dp(x*y + x*KD(i, j), (j, 1, 1)) == x*y + x*KD(i, 1)
114
+ assert dp(x*y + x*KD(i, j), (j, 2, 2)) == x*y + x*KD(i, 2)
115
+ assert dp(x*y + x*KD(i, j), (j, 3, 3)) == x*y + x*KD(i, 3)
116
+ assert dp(x*y + x*KD(i, j), (j, 1, k)) == \
117
+ (x*y)**k + Piecewise(
118
+ ((x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
119
+ (0, True)
120
+ )
121
+ assert dp(x*y + x*KD(i, j), (j, k, 3)) == \
122
+ (x*y)**(-k + 4) + Piecewise(
123
+ ((x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
124
+ (0, True)
125
+ )
126
+ assert dp(x*y + x*KD(i, j), (j, k, l)) == \
127
+ (x*y)**(-k + l + 1) + Piecewise(
128
+ ((x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
129
+ (0, True)
130
+ )
131
+
132
+
133
+ def test_deltaproduct_mul_x_add_y_kd():
134
+ assert dp(x*(y + KD(i, j)), (j, 1, 3)) == (x*y)**3 + \
135
+ x*(x*y)**2*KD(i, 1) + (x*y)*x*(x*y)*KD(i, 2) + (x*y)**2*x*KD(i, 3)
136
+ assert dp(x*(y + KD(i, j)), (j, 1, 1)) == x*(y + KD(i, 1))
137
+ assert dp(x*(y + KD(i, j)), (j, 2, 2)) == x*(y + KD(i, 2))
138
+ assert dp(x*(y + KD(i, j)), (j, 3, 3)) == x*(y + KD(i, 3))
139
+ assert dp(x*(y + KD(i, j)), (j, 1, k)) == \
140
+ (x*y)**k + Piecewise(
141
+ ((x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
142
+ (0, True)
143
+ ).expand()
144
+ assert dp(x*(y + KD(i, j)), (j, k, 3)) == \
145
+ ((x*y)**(-k + 4) + Piecewise(
146
+ ((x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
147
+ (0, True)
148
+ )).expand()
149
+ assert dp(x*(y + KD(i, j)), (j, k, l)) == \
150
+ ((x*y)**(-k + l + 1) + Piecewise(
151
+ ((x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
152
+ (0, True)
153
+ )).expand()
154
+
155
+
156
+ def test_deltaproduct_mul_x_add_y_twokd():
157
+ assert dp(x*(y + 2*KD(i, j)), (j, 1, 3)) == (x*y)**3 + \
158
+ 2*x*(x*y)**2*KD(i, 1) + 2*x*y*x*x*y*KD(i, 2) + 2*(x*y)**2*x*KD(i, 3)
159
+ assert dp(x*(y + 2*KD(i, j)), (j, 1, 1)) == x*(y + 2*KD(i, 1))
160
+ assert dp(x*(y + 2*KD(i, j)), (j, 2, 2)) == x*(y + 2*KD(i, 2))
161
+ assert dp(x*(y + 2*KD(i, j)), (j, 3, 3)) == x*(y + 2*KD(i, 3))
162
+ assert dp(x*(y + 2*KD(i, j)), (j, 1, k)) == \
163
+ (x*y)**k + Piecewise(
164
+ (2*(x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
165
+ (0, True)
166
+ ).expand()
167
+ assert dp(x*(y + 2*KD(i, j)), (j, k, 3)) == \
168
+ ((x*y)**(-k + 4) + Piecewise(
169
+ (2*(x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
170
+ (0, True)
171
+ )).expand()
172
+ assert dp(x*(y + 2*KD(i, j)), (j, k, l)) == \
173
+ ((x*y)**(-k + l + 1) + Piecewise(
174
+ (2*(x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
175
+ (0, True)
176
+ )).expand()
177
+
178
+
179
+ def test_deltaproduct_mul_add_x_y_add_y_kd():
180
+ assert dp((x + y)*(y + KD(i, j)), (j, 1, 3)) == ((x + y)*y)**3 + \
181
+ (x + y)*((x + y)*y)**2*KD(i, 1) + \
182
+ (x + y)*y*(x + y)**2*y*KD(i, 2) + \
183
+ ((x + y)*y)**2*(x + y)*KD(i, 3)
184
+ assert dp((x + y)*(y + KD(i, j)), (j, 1, 1)) == (x + y)*(y + KD(i, 1))
185
+ assert dp((x + y)*(y + KD(i, j)), (j, 2, 2)) == (x + y)*(y + KD(i, 2))
186
+ assert dp((x + y)*(y + KD(i, j)), (j, 3, 3)) == (x + y)*(y + KD(i, 3))
187
+ assert dp((x + y)*(y + KD(i, j)), (j, 1, k)) == \
188
+ ((x + y)*y)**k + Piecewise(
189
+ (((x + y)*y)**(-1)*((x + y)*y)**i*(x + y)*((x + y)*y
190
+ )**k*((x + y)*y)**(-i), (i >= 1) & (i <= k)), (0, True))
191
+ assert dp((x + y)*(y + KD(i, j)), (j, k, 3)) == (
192
+ (x + y)*y)**4*((x + y)*y)**(-k) + Piecewise((((x + y)*y)**i*(
193
+ (x + y)*y)**(-k)*(x + y)*((x + y)*y)**3*((x + y)*y)**(-i),
194
+ (i >= k) & (i <= 3)), (0, True))
195
+ assert dp((x + y)*(y + KD(i, j)), (j, k, l)) == \
196
+ (x + y)*y*((x + y)*y)**l*((x + y)*y)**(-k) + Piecewise(
197
+ (((x + y)*y)**i*((x + y)*y)**(-k)*(x + y)*((x + y)*y
198
+ )**l*((x + y)*y)**(-i), (i >= k) & (i <= l)), (0, True))
199
+
200
+
201
+ def test_deltaproduct_mul_add_x_kd_add_y_kd():
202
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == \
203
+ KD(i, 1)*(KD(i, k) + x)*((KD(i, k) + x)*y)**2 + \
204
+ KD(i, 2)*(KD(i, k) + x)*y*(KD(i, k) + x)**2*y + \
205
+ KD(i, 3)*((KD(i, k) + x)*y)**2*(KD(i, k) + x) + \
206
+ ((KD(i, k) + x)*y)**3
207
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == \
208
+ (x + KD(i, k))*(y + KD(i, 1))
209
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == \
210
+ (x + KD(i, k))*(y + KD(i, 2))
211
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == \
212
+ (x + KD(i, k))*(y + KD(i, 3))
213
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == \
214
+ ((KD(i, k) + x)*y)**k + Piecewise(
215
+ (((KD(i, k) + x)*y)**(-1)*((KD(i, k) + x)*y)**i*(KD(i, k) + x
216
+ )*((KD(i, k) + x)*y)**k*((KD(i, k) + x)*y)**(-i), (i >= 1
217
+ ) & (i <= k)), (0, True))
218
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == (
219
+ (KD(i, k) + x)*y)**4*((KD(i, k) + x)*y)**(-k) + Piecewise(
220
+ (((KD(i, k) + x)*y)**i*((KD(i, k) + x)*y)**(-k)*(KD(i, k)
221
+ + x)*((KD(i, k) + x)*y)**3*((KD(i, k) + x)*y)**(-i),
222
+ (i >= k) & (i <= 3)), (0, True))
223
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == (
224
+ KD(i, k) + x)*y*((KD(i, k) + x)*y)**l*((KD(i, k) + x)*y
225
+ )**(-k) + Piecewise((((KD(i, k) + x)*y)**i*((KD(i, k) + x
226
+ )*y)**(-k)*(KD(i, k) + x)*((KD(i, k) + x)*y)**l*((KD(i, k) + x
227
+ )*y)**(-i), (i >= k) & (i <= l)), (0, True))
228
+
229
+
230
+ def test_deltasummation_trivial():
231
+ assert ds(x, (j, 1, 0)) == 0
232
+ assert ds(x, (j, 1, 3)) == 3*x
233
+ assert ds(x + y, (j, 1, 3)) == 3*(x + y)
234
+ assert ds(x*y, (j, 1, 3)) == 3*x*y
235
+ assert ds(KD(i, j), (k, 1, 3)) == 3*KD(i, j)
236
+ assert ds(x*KD(i, j), (k, 1, 3)) == 3*x*KD(i, j)
237
+ assert ds(x*y*KD(i, j), (k, 1, 3)) == 3*x*y*KD(i, j)
238
+
239
+
240
+ def test_deltasummation_basic_numerical():
241
+ n = symbols('n', integer=True, nonzero=True)
242
+ assert ds(KD(n, 0), (n, 1, 3)) == 0
243
+
244
+ # return unevaluated, until it gets implemented
245
+ assert ds(KD(i**2, j**2), (j, -oo, oo)) == \
246
+ Sum(KD(i**2, j**2), (j, -oo, oo))
247
+
248
+ assert Piecewise((KD(i, k), And(1 <= i, i <= 3)), (0, True)) == \
249
+ ds(KD(i, j)*KD(j, k), (j, 1, 3)) == \
250
+ ds(KD(j, k)*KD(i, j), (j, 1, 3))
251
+
252
+ assert ds(KD(i, k), (k, -oo, oo)) == 1
253
+ assert ds(KD(i, k), (k, 0, oo)) == Piecewise((1, S.Zero <= i), (0, True))
254
+ assert ds(KD(i, k), (k, 1, 3)) == \
255
+ Piecewise((1, And(1 <= i, i <= 3)), (0, True))
256
+ assert ds(k*KD(i, j)*KD(j, k), (k, -oo, oo)) == j*KD(i, j)
257
+ assert ds(j*KD(i, j), (j, -oo, oo)) == i
258
+ assert ds(i*KD(i, j), (i, -oo, oo)) == j
259
+ assert ds(x, (i, 1, 3)) == 3*x
260
+ assert ds((i + j)*KD(i, j), (j, -oo, oo)) == 2*i
261
+
262
+
263
+ def test_deltasummation_basic_symbolic():
264
+ assert ds(KD(i, j), (j, 1, 3)) == \
265
+ Piecewise((1, And(1 <= i, i <= 3)), (0, True))
266
+ assert ds(KD(i, j), (j, 1, 1)) == Piecewise((1, Eq(i, 1)), (0, True))
267
+ assert ds(KD(i, j), (j, 2, 2)) == Piecewise((1, Eq(i, 2)), (0, True))
268
+ assert ds(KD(i, j), (j, 3, 3)) == Piecewise((1, Eq(i, 3)), (0, True))
269
+ assert ds(KD(i, j), (j, 1, k)) == \
270
+ Piecewise((1, And(1 <= i, i <= k)), (0, True))
271
+ assert ds(KD(i, j), (j, k, 3)) == \
272
+ Piecewise((1, And(k <= i, i <= 3)), (0, True))
273
+ assert ds(KD(i, j), (j, k, l)) == \
274
+ Piecewise((1, And(k <= i, i <= l)), (0, True))
275
+
276
+
277
+ def test_deltasummation_mul_x_kd():
278
+ assert ds(x*KD(i, j), (j, 1, 3)) == \
279
+ Piecewise((x, And(1 <= i, i <= 3)), (0, True))
280
+ assert ds(x*KD(i, j), (j, 1, 1)) == Piecewise((x, Eq(i, 1)), (0, True))
281
+ assert ds(x*KD(i, j), (j, 2, 2)) == Piecewise((x, Eq(i, 2)), (0, True))
282
+ assert ds(x*KD(i, j), (j, 3, 3)) == Piecewise((x, Eq(i, 3)), (0, True))
283
+ assert ds(x*KD(i, j), (j, 1, k)) == \
284
+ Piecewise((x, And(1 <= i, i <= k)), (0, True))
285
+ assert ds(x*KD(i, j), (j, k, 3)) == \
286
+ Piecewise((x, And(k <= i, i <= 3)), (0, True))
287
+ assert ds(x*KD(i, j), (j, k, l)) == \
288
+ Piecewise((x, And(k <= i, i <= l)), (0, True))
289
+
290
+
291
+ def test_deltasummation_mul_add_x_y_kd():
292
+ assert ds((x + y)*KD(i, j), (j, 1, 3)) == \
293
+ Piecewise((x + y, And(1 <= i, i <= 3)), (0, True))
294
+ assert ds((x + y)*KD(i, j), (j, 1, 1)) == \
295
+ Piecewise((x + y, Eq(i, 1)), (0, True))
296
+ assert ds((x + y)*KD(i, j), (j, 2, 2)) == \
297
+ Piecewise((x + y, Eq(i, 2)), (0, True))
298
+ assert ds((x + y)*KD(i, j), (j, 3, 3)) == \
299
+ Piecewise((x + y, Eq(i, 3)), (0, True))
300
+ assert ds((x + y)*KD(i, j), (j, 1, k)) == \
301
+ Piecewise((x + y, And(1 <= i, i <= k)), (0, True))
302
+ assert ds((x + y)*KD(i, j), (j, k, 3)) == \
303
+ Piecewise((x + y, And(k <= i, i <= 3)), (0, True))
304
+ assert ds((x + y)*KD(i, j), (j, k, l)) == \
305
+ Piecewise((x + y, And(k <= i, i <= l)), (0, True))
306
+
307
+
308
+ def test_deltasummation_add_kd_kd():
309
+ assert ds(KD(i, k) + KD(j, k), (k, 1, 3)) == piecewise_fold(
310
+ Piecewise((1, And(1 <= i, i <= 3)), (0, True)) +
311
+ Piecewise((1, And(1 <= j, j <= 3)), (0, True)))
312
+ assert ds(KD(i, k) + KD(j, k), (k, 1, 1)) == piecewise_fold(
313
+ Piecewise((1, Eq(i, 1)), (0, True)) +
314
+ Piecewise((1, Eq(j, 1)), (0, True)))
315
+ assert ds(KD(i, k) + KD(j, k), (k, 2, 2)) == piecewise_fold(
316
+ Piecewise((1, Eq(i, 2)), (0, True)) +
317
+ Piecewise((1, Eq(j, 2)), (0, True)))
318
+ assert ds(KD(i, k) + KD(j, k), (k, 3, 3)) == piecewise_fold(
319
+ Piecewise((1, Eq(i, 3)), (0, True)) +
320
+ Piecewise((1, Eq(j, 3)), (0, True)))
321
+ assert ds(KD(i, k) + KD(j, k), (k, 1, l)) == piecewise_fold(
322
+ Piecewise((1, And(1 <= i, i <= l)), (0, True)) +
323
+ Piecewise((1, And(1 <= j, j <= l)), (0, True)))
324
+ assert ds(KD(i, k) + KD(j, k), (k, l, 3)) == piecewise_fold(
325
+ Piecewise((1, And(l <= i, i <= 3)), (0, True)) +
326
+ Piecewise((1, And(l <= j, j <= 3)), (0, True)))
327
+ assert ds(KD(i, k) + KD(j, k), (k, l, m)) == piecewise_fold(
328
+ Piecewise((1, And(l <= i, i <= m)), (0, True)) +
329
+ Piecewise((1, And(l <= j, j <= m)), (0, True)))
330
+
331
+
332
+ def test_deltasummation_add_mul_x_kd_kd():
333
+ assert ds(x*KD(i, k) + KD(j, k), (k, 1, 3)) == piecewise_fold(
334
+ Piecewise((x, And(1 <= i, i <= 3)), (0, True)) +
335
+ Piecewise((1, And(1 <= j, j <= 3)), (0, True)))
336
+ assert ds(x*KD(i, k) + KD(j, k), (k, 1, 1)) == piecewise_fold(
337
+ Piecewise((x, Eq(i, 1)), (0, True)) +
338
+ Piecewise((1, Eq(j, 1)), (0, True)))
339
+ assert ds(x*KD(i, k) + KD(j, k), (k, 2, 2)) == piecewise_fold(
340
+ Piecewise((x, Eq(i, 2)), (0, True)) +
341
+ Piecewise((1, Eq(j, 2)), (0, True)))
342
+ assert ds(x*KD(i, k) + KD(j, k), (k, 3, 3)) == piecewise_fold(
343
+ Piecewise((x, Eq(i, 3)), (0, True)) +
344
+ Piecewise((1, Eq(j, 3)), (0, True)))
345
+ assert ds(x*KD(i, k) + KD(j, k), (k, 1, l)) == piecewise_fold(
346
+ Piecewise((x, And(1 <= i, i <= l)), (0, True)) +
347
+ Piecewise((1, And(1 <= j, j <= l)), (0, True)))
348
+ assert ds(x*KD(i, k) + KD(j, k), (k, l, 3)) == piecewise_fold(
349
+ Piecewise((x, And(l <= i, i <= 3)), (0, True)) +
350
+ Piecewise((1, And(l <= j, j <= 3)), (0, True)))
351
+ assert ds(x*KD(i, k) + KD(j, k), (k, l, m)) == piecewise_fold(
352
+ Piecewise((x, And(l <= i, i <= m)), (0, True)) +
353
+ Piecewise((1, And(l <= j, j <= m)), (0, True)))
354
+
355
+
356
+ def test_deltasummation_mul_x_add_kd_kd():
357
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
358
+ Piecewise((x, And(1 <= i, i <= 3)), (0, True)) +
359
+ Piecewise((x, And(1 <= j, j <= 3)), (0, True)))
360
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
361
+ Piecewise((x, Eq(i, 1)), (0, True)) +
362
+ Piecewise((x, Eq(j, 1)), (0, True)))
363
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
364
+ Piecewise((x, Eq(i, 2)), (0, True)) +
365
+ Piecewise((x, Eq(j, 2)), (0, True)))
366
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
367
+ Piecewise((x, Eq(i, 3)), (0, True)) +
368
+ Piecewise((x, Eq(j, 3)), (0, True)))
369
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
370
+ Piecewise((x, And(1 <= i, i <= l)), (0, True)) +
371
+ Piecewise((x, And(1 <= j, j <= l)), (0, True)))
372
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
373
+ Piecewise((x, And(l <= i, i <= 3)), (0, True)) +
374
+ Piecewise((x, And(l <= j, j <= 3)), (0, True)))
375
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
376
+ Piecewise((x, And(l <= i, i <= m)), (0, True)) +
377
+ Piecewise((x, And(l <= j, j <= m)), (0, True)))
378
+
379
+
380
+ def test_deltasummation_mul_add_x_y_add_kd_kd():
381
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
382
+ Piecewise((x + y, And(1 <= i, i <= 3)), (0, True)) +
383
+ Piecewise((x + y, And(1 <= j, j <= 3)), (0, True)))
384
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
385
+ Piecewise((x + y, Eq(i, 1)), (0, True)) +
386
+ Piecewise((x + y, Eq(j, 1)), (0, True)))
387
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
388
+ Piecewise((x + y, Eq(i, 2)), (0, True)) +
389
+ Piecewise((x + y, Eq(j, 2)), (0, True)))
390
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
391
+ Piecewise((x + y, Eq(i, 3)), (0, True)) +
392
+ Piecewise((x + y, Eq(j, 3)), (0, True)))
393
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
394
+ Piecewise((x + y, And(1 <= i, i <= l)), (0, True)) +
395
+ Piecewise((x + y, And(1 <= j, j <= l)), (0, True)))
396
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
397
+ Piecewise((x + y, And(l <= i, i <= 3)), (0, True)) +
398
+ Piecewise((x + y, And(l <= j, j <= 3)), (0, True)))
399
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
400
+ Piecewise((x + y, And(l <= i, i <= m)), (0, True)) +
401
+ Piecewise((x + y, And(l <= j, j <= m)), (0, True)))
402
+
403
+
404
+ def test_deltasummation_add_mul_x_y_mul_x_kd():
405
+ assert ds(x*y + x*KD(i, j), (j, 1, 3)) == \
406
+ Piecewise((3*x*y + x, And(1 <= i, i <= 3)), (3*x*y, True))
407
+ assert ds(x*y + x*KD(i, j), (j, 1, 1)) == \
408
+ Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
409
+ assert ds(x*y + x*KD(i, j), (j, 2, 2)) == \
410
+ Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
411
+ assert ds(x*y + x*KD(i, j), (j, 3, 3)) == \
412
+ Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
413
+ assert ds(x*y + x*KD(i, j), (j, 1, k)) == \
414
+ Piecewise((k*x*y + x, And(1 <= i, i <= k)), (k*x*y, True))
415
+ assert ds(x*y + x*KD(i, j), (j, k, 3)) == \
416
+ Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
417
+ assert ds(x*y + x*KD(i, j), (j, k, l)) == Piecewise(
418
+ ((l - k + 1)*x*y + x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
419
+
420
+
421
+ def test_deltasummation_mul_x_add_y_kd():
422
+ assert ds(x*(y + KD(i, j)), (j, 1, 3)) == \
423
+ Piecewise((3*x*y + x, And(1 <= i, i <= 3)), (3*x*y, True))
424
+ assert ds(x*(y + KD(i, j)), (j, 1, 1)) == \
425
+ Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
426
+ assert ds(x*(y + KD(i, j)), (j, 2, 2)) == \
427
+ Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
428
+ assert ds(x*(y + KD(i, j)), (j, 3, 3)) == \
429
+ Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
430
+ assert ds(x*(y + KD(i, j)), (j, 1, k)) == \
431
+ Piecewise((k*x*y + x, And(1 <= i, i <= k)), (k*x*y, True))
432
+ assert ds(x*(y + KD(i, j)), (j, k, 3)) == \
433
+ Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
434
+ assert ds(x*(y + KD(i, j)), (j, k, l)) == Piecewise(
435
+ ((l - k + 1)*x*y + x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
436
+
437
+
438
+ def test_deltasummation_mul_x_add_y_twokd():
439
+ assert ds(x*(y + 2*KD(i, j)), (j, 1, 3)) == \
440
+ Piecewise((3*x*y + 2*x, And(1 <= i, i <= 3)), (3*x*y, True))
441
+ assert ds(x*(y + 2*KD(i, j)), (j, 1, 1)) == \
442
+ Piecewise((x*y + 2*x, Eq(i, 1)), (x*y, True))
443
+ assert ds(x*(y + 2*KD(i, j)), (j, 2, 2)) == \
444
+ Piecewise((x*y + 2*x, Eq(i, 2)), (x*y, True))
445
+ assert ds(x*(y + 2*KD(i, j)), (j, 3, 3)) == \
446
+ Piecewise((x*y + 2*x, Eq(i, 3)), (x*y, True))
447
+ assert ds(x*(y + 2*KD(i, j)), (j, 1, k)) == \
448
+ Piecewise((k*x*y + 2*x, And(1 <= i, i <= k)), (k*x*y, True))
449
+ assert ds(x*(y + 2*KD(i, j)), (j, k, 3)) == Piecewise(
450
+ ((4 - k)*x*y + 2*x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
451
+ assert ds(x*(y + 2*KD(i, j)), (j, k, l)) == Piecewise(
452
+ ((l - k + 1)*x*y + 2*x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
453
+
454
+
455
+ def test_deltasummation_mul_add_x_y_add_y_kd():
456
+ assert ds((x + y)*(y + KD(i, j)), (j, 1, 3)) == Piecewise(
457
+ (3*(x + y)*y + x + y, And(1 <= i, i <= 3)), (3*(x + y)*y, True))
458
+ assert ds((x + y)*(y + KD(i, j)), (j, 1, 1)) == \
459
+ Piecewise(((x + y)*y + x + y, Eq(i, 1)), ((x + y)*y, True))
460
+ assert ds((x + y)*(y + KD(i, j)), (j, 2, 2)) == \
461
+ Piecewise(((x + y)*y + x + y, Eq(i, 2)), ((x + y)*y, True))
462
+ assert ds((x + y)*(y + KD(i, j)), (j, 3, 3)) == \
463
+ Piecewise(((x + y)*y + x + y, Eq(i, 3)), ((x + y)*y, True))
464
+ assert ds((x + y)*(y + KD(i, j)), (j, 1, k)) == Piecewise(
465
+ (k*(x + y)*y + x + y, And(1 <= i, i <= k)), (k*(x + y)*y, True))
466
+ assert ds((x + y)*(y + KD(i, j)), (j, k, 3)) == Piecewise(
467
+ ((4 - k)*(x + y)*y + x + y, And(k <= i, i <= 3)),
468
+ ((4 - k)*(x + y)*y, True))
469
+ assert ds((x + y)*(y + KD(i, j)), (j, k, l)) == Piecewise(
470
+ ((l - k + 1)*(x + y)*y + x + y, And(k <= i, i <= l)),
471
+ ((l - k + 1)*(x + y)*y, True))
472
+
473
+
474
+ def test_deltasummation_mul_add_x_kd_add_y_kd():
475
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == piecewise_fold(
476
+ Piecewise((KD(i, k) + x, And(1 <= i, i <= 3)), (0, True)) +
477
+ 3*(KD(i, k) + x)*y)
478
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == piecewise_fold(
479
+ Piecewise((KD(i, k) + x, Eq(i, 1)), (0, True)) +
480
+ (KD(i, k) + x)*y)
481
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == piecewise_fold(
482
+ Piecewise((KD(i, k) + x, Eq(i, 2)), (0, True)) +
483
+ (KD(i, k) + x)*y)
484
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == piecewise_fold(
485
+ Piecewise((KD(i, k) + x, Eq(i, 3)), (0, True)) +
486
+ (KD(i, k) + x)*y)
487
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == piecewise_fold(
488
+ Piecewise((KD(i, k) + x, And(1 <= i, i <= k)), (0, True)) +
489
+ k*(KD(i, k) + x)*y)
490
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == piecewise_fold(
491
+ Piecewise((KD(i, k) + x, And(k <= i, i <= 3)), (0, True)) +
492
+ (4 - k)*(KD(i, k) + x)*y)
493
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == piecewise_fold(
494
+ Piecewise((KD(i, k) + x, And(k <= i, i <= l)), (0, True)) +
495
+ (l - k + 1)*(KD(i, k) + x)*y)
496
+
497
+
498
+ def test_extract_delta():
499
+ raises(ValueError, lambda: _extract_delta(KD(i, j) + KD(k, l), i))
venv/lib/python3.10/site-packages/sympy/concrete/tests/test_gosper.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for Gosper's algorithm for hypergeometric summation. """
2
+
3
+ from sympy.core.numbers import (Rational, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.combinatorial.factorials import (binomial, factorial)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.miscellaneous import sqrt
9
+ from sympy.functions.special.gamma_functions import gamma
10
+ from sympy.polys.polytools import Poly
11
+ from sympy.simplify.simplify import simplify
12
+ from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term
13
+ from sympy.abc import a, b, j, k, m, n, r, x
14
+
15
+
16
+ def test_gosper_normal():
17
+ eq = 4*n + 5, 2*(4*n + 1)*(2*n + 3), n
18
+ assert gosper_normal(*eq) == \
19
+ (Poly(Rational(1, 4), n), Poly(n + Rational(3, 2)), Poly(n + Rational(1, 4)))
20
+ assert gosper_normal(*eq, polys=False) == \
21
+ (Rational(1, 4), n + Rational(3, 2), n + Rational(1, 4))
22
+
23
+
24
+ def test_gosper_term():
25
+ assert gosper_term((4*k + 1)*factorial(
26
+ k)/factorial(2*k + 1), k) == (-k - S.Half)/(k + Rational(1, 4))
27
+
28
+
29
+ def test_gosper_sum():
30
+ assert gosper_sum(1, (k, 0, n)) == 1 + n
31
+ assert gosper_sum(k, (k, 0, n)) == n*(1 + n)/2
32
+ assert gosper_sum(k**2, (k, 0, n)) == n*(1 + n)*(1 + 2*n)/6
33
+ assert gosper_sum(k**3, (k, 0, n)) == n**2*(1 + n)**2/4
34
+
35
+ assert gosper_sum(2**k, (k, 0, n)) == 2*2**n - 1
36
+
37
+ assert gosper_sum(factorial(k), (k, 0, n)) is None
38
+ assert gosper_sum(binomial(n, k), (k, 0, n)) is None
39
+
40
+ assert gosper_sum(factorial(k)/k**2, (k, 0, n)) is None
41
+ assert gosper_sum((k - 3)*factorial(k), (k, 0, n)) is None
42
+
43
+ assert gosper_sum(k*factorial(k), k) == factorial(k)
44
+ assert gosper_sum(
45
+ k*factorial(k), (k, 0, n)) == n*factorial(n) + factorial(n) - 1
46
+
47
+ assert gosper_sum((-1)**k*binomial(n, k), (k, 0, n)) == 0
48
+ assert gosper_sum((
49
+ -1)**k*binomial(n, k), (k, 0, m)) == -(-1)**m*(m - n)*binomial(n, m)/n
50
+
51
+ assert gosper_sum((4*k + 1)*factorial(k)/factorial(2*k + 1), (k, 0, n)) == \
52
+ (2*factorial(2*n + 1) - factorial(n))/factorial(2*n + 1)
53
+
54
+ # issue 6033:
55
+ assert gosper_sum(
56
+ n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)), \
57
+ (n, 0, m)).simplify() == -exp(m*log(a) + m*log(b))*gamma(a + 1) \
58
+ *gamma(b + 1)/(gamma(a)*gamma(b)*gamma(a + m + 1)*gamma(b + m + 1)) \
59
+ + 1/(gamma(a)*gamma(b))
60
+
61
+
62
+ def test_gosper_sum_indefinite():
63
+ assert gosper_sum(k, k) == k*(k - 1)/2
64
+ assert gosper_sum(k**2, k) == k*(k - 1)*(2*k - 1)/6
65
+
66
+ assert gosper_sum(1/(k*(k + 1)), k) == -1/k
67
+ assert gosper_sum(-(27*k**4 + 158*k**3 + 430*k**2 + 678*k + 445)*gamma(2*k
68
+ + 4)/(3*(3*k + 7)*gamma(3*k + 6)), k) == \
69
+ (3*k + 5)*(k**2 + 2*k + 5)*gamma(2*k + 4)/gamma(3*k + 6)
70
+
71
+
72
+ def test_gosper_sum_parametric():
73
+ assert gosper_sum(binomial(S.Half, m - j + 1)*binomial(S.Half, m + j), (j, 1, n)) == \
74
+ n*(1 + m - n)*(-1 + 2*m + 2*n)*binomial(S.Half, 1 + m - n)* \
75
+ binomial(S.Half, m + n)/(m*(1 + 2*m))
76
+
77
+
78
+ def test_gosper_sum_algebraic():
79
+ assert gosper_sum(
80
+ n**2 + sqrt(2), (n, 0, m)) == (m + 1)*(2*m**2 + m + 6*sqrt(2))/6
81
+
82
+
83
+ def test_gosper_sum_iterated():
84
+ f1 = binomial(2*k, k)/4**k
85
+ f2 = (1 + 2*n)*binomial(2*n, n)/4**n
86
+ f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n)
87
+ f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n)
88
+ f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*binomial(2*n, n)/(105*4**n)
89
+
90
+ assert gosper_sum(f1, (k, 0, n)) == f2
91
+ assert gosper_sum(f2, (n, 0, n)) == f3
92
+ assert gosper_sum(f3, (n, 0, n)) == f4
93
+ assert gosper_sum(f4, (n, 0, n)) == f5
94
+
95
+ # the AeqB tests test expressions given in
96
+ # www.math.upenn.edu/~wilf/AeqB.pdf
97
+
98
+
99
+ def test_gosper_sum_AeqB_part1():
100
+ f1a = n**4
101
+ f1b = n**3*2**n
102
+ f1c = 1/(n**2 + sqrt(5)*n - 1)
103
+ f1d = n**4*4**n/binomial(2*n, n)
104
+ f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n)
105
+ f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n))
106
+ f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n))
107
+ f1h = n*factorial(n - S.Half)**2/factorial(n + 1)**2
108
+
109
+ g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30
110
+ g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13)
111
+ g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - (
112
+ 3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + 5*m**2 - 1)/6
113
+ g1d = Rational(-2, 231) + 2*4**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 -
114
+ 22*m + 3)/(693*binomial(2*m, m))
115
+ g1e = Rational(-9, 2) + (81*m**2 + 261*m + 200)*factorial(
116
+ 3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2))
117
+ g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1))
118
+ g1g = -binomial(2*m, m)**2/4**(2*m)
119
+ g1h = 4*pi -(2*m + 1)**2*(3*m + 4)*factorial(m - S.Half)**2/factorial(m + 1)**2
120
+
121
+ g = gosper_sum(f1a, (n, 0, m))
122
+ assert g is not None and simplify(g - g1a) == 0
123
+ g = gosper_sum(f1b, (n, 0, m))
124
+ assert g is not None and simplify(g - g1b) == 0
125
+ g = gosper_sum(f1c, (n, 0, m))
126
+ assert g is not None and simplify(g - g1c) == 0
127
+ g = gosper_sum(f1d, (n, 0, m))
128
+ assert g is not None and simplify(g - g1d) == 0
129
+ g = gosper_sum(f1e, (n, 0, m))
130
+ assert g is not None and simplify(g - g1e) == 0
131
+ g = gosper_sum(f1f, (n, 0, m))
132
+ assert g is not None and simplify(g - g1f) == 0
133
+ g = gosper_sum(f1g, (n, 0, m))
134
+ assert g is not None and simplify(g - g1g) == 0
135
+ g = gosper_sum(f1h, (n, 0, m))
136
+ # need to call rewrite(gamma) here because we have terms involving
137
+ # factorial(1/2)
138
+ assert g is not None and simplify(g - g1h).rewrite(gamma) == 0
139
+
140
+
141
+ def test_gosper_sum_AeqB_part2():
142
+ f2a = n**2*a**n
143
+ f2b = (n - r/2)*binomial(r, n)
144
+ f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x))
145
+
146
+ g2a = -a*(a + 1)/(a - 1)**3 + a**(
147
+ m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3
148
+ g2b = (m - r)*binomial(r, m)/2
149
+ ff = factorial(1 - x)*factorial(1 + x)
150
+ g2c = 1/ff*(
151
+ 1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x))
152
+
153
+ g = gosper_sum(f2a, (n, 0, m))
154
+ assert g is not None and simplify(g - g2a) == 0
155
+ g = gosper_sum(f2b, (n, 0, m))
156
+ assert g is not None and simplify(g - g2b) == 0
157
+ g = gosper_sum(f2c, (n, 1, m))
158
+ assert g is not None and simplify(g - g2c) == 0
159
+
160
+
161
+ def test_gosper_nan():
162
+ a = Symbol('a', positive=True)
163
+ b = Symbol('b', positive=True)
164
+ n = Symbol('n', integer=True)
165
+ m = Symbol('m', integer=True)
166
+ f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b))
167
+ g2d = 1/(factorial(a - 1)*factorial(
168
+ b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m))
169
+ g = gosper_sum(f2d, (n, 0, m))
170
+ assert simplify(g - g2d) == 0
171
+
172
+
173
+ def test_gosper_sum_AeqB_part3():
174
+ f3a = 1/n**4
175
+ f3b = (6*n + 3)/(4*n**4 + 8*n**3 + 8*n**2 + 4*n + 3)
176
+ f3c = 2**n*(n**2 - 2*n - 1)/(n**2*(n + 1)**2)
177
+ f3d = n**2*4**n/((n + 1)*(n + 2))
178
+ f3e = 2**n/(n + 1)
179
+ f3f = 4*(n - 1)*(n**2 - 2*n - 1)/(n**2*(n + 1)**2*(n - 2)**2*(n - 3)**2)
180
+ f3g = (n**4 - 14*n**2 - 24*n - 9)*2**n/(n**2*(n + 1)**2*(n + 2)**2*
181
+ (n + 3)**2)
182
+
183
+ # g3a -> no closed form
184
+ g3b = m*(m + 2)/(2*m**2 + 4*m + 3)
185
+ g3c = 2**m/m**2 - 2
186
+ g3d = Rational(2, 3) + 4**(m + 1)*(m - 1)/(m + 2)/3
187
+ # g3e -> no closed form
188
+ g3f = -(Rational(-1, 16) + 1/((m - 2)**2*(m + 1)**2)) # the AeqB key is wrong
189
+ g3g = Rational(-2, 9) + 2**(m + 1)/((m + 1)**2*(m + 3)**2)
190
+
191
+ g = gosper_sum(f3a, (n, 1, m))
192
+ assert g is None
193
+ g = gosper_sum(f3b, (n, 1, m))
194
+ assert g is not None and simplify(g - g3b) == 0
195
+ g = gosper_sum(f3c, (n, 1, m - 1))
196
+ assert g is not None and simplify(g - g3c) == 0
197
+ g = gosper_sum(f3d, (n, 1, m))
198
+ assert g is not None and simplify(g - g3d) == 0
199
+ g = gosper_sum(f3e, (n, 0, m - 1))
200
+ assert g is None
201
+ g = gosper_sum(f3f, (n, 4, m))
202
+ assert g is not None and simplify(g - g3f) == 0
203
+ g = gosper_sum(f3g, (n, 1, m))
204
+ assert g is not None and simplify(g - g3g) == 0
venv/lib/python3.10/site-packages/sympy/concrete/tests/test_guess.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.guess import (
2
+ find_simple_recurrence_vector,
3
+ find_simple_recurrence,
4
+ rationalize,
5
+ guess_generating_function_rational,
6
+ guess_generating_function,
7
+ guess
8
+ )
9
+ from sympy.concrete.products import Product
10
+ from sympy.core.function import Function
11
+ from sympy.core.numbers import Rational
12
+ from sympy.core.singleton import S
13
+ from sympy.core.symbol import (Symbol, symbols)
14
+ from sympy.core.sympify import sympify
15
+ from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
16
+ from sympy.functions.combinatorial.numbers import fibonacci
17
+ from sympy.functions.elementary.exponential import exp
18
+
19
+
20
+ def test_find_simple_recurrence_vector():
21
+ assert find_simple_recurrence_vector(
22
+ [fibonacci(k) for k in range(12)]) == [1, -1, -1]
23
+
24
+
25
+ def test_find_simple_recurrence():
26
+ a = Function('a')
27
+ n = Symbol('n')
28
+ assert find_simple_recurrence([fibonacci(k) for k in range(12)]) == (
29
+ -a(n) - a(n + 1) + a(n + 2))
30
+
31
+ f = Function('a')
32
+ i = Symbol('n')
33
+ a = [1, 1, 1]
34
+ for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
35
+ assert find_simple_recurrence(a, A=f, N=i) == (
36
+ -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3))
37
+ assert find_simple_recurrence([0, 2, 15, 74, 12, 3, 0,
38
+ 1, 2, 85, 4, 5, 63]) == 0
39
+
40
+
41
+ def test_rationalize():
42
+ from mpmath import cos, pi, mpf
43
+ assert rationalize(cos(pi/3)) == S.Half
44
+ assert rationalize(mpf("0.333333333333333")) == Rational(1, 3)
45
+ assert rationalize(mpf("-0.333333333333333")) == Rational(-1, 3)
46
+ assert rationalize(pi, maxcoeff = 250) == Rational(355, 113)
47
+
48
+
49
+ def test_guess_generating_function_rational():
50
+ x = Symbol('x')
51
+ assert guess_generating_function_rational([fibonacci(k)
52
+ for k in range(5, 15)]) == ((3*x + 5)/(-x**2 - x + 1))
53
+
54
+
55
+ def test_guess_generating_function():
56
+ x = Symbol('x')
57
+ assert guess_generating_function([fibonacci(k)
58
+ for k in range(5, 15)])['ogf'] == ((3*x + 5)/(-x**2 - x + 1))
59
+ assert guess_generating_function(
60
+ [1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf'] == (
61
+ (1/(x**4 + 2*x**2 - 4*x + 1))**S.Half)
62
+ assert guess_generating_function(sympify(
63
+ "[3/2, 11/2, 0, -121/2, -363/2, 121, 4719/2, 11495/2, -8712, -178717/2]")
64
+ )['ogf'] == (x + Rational(3, 2))/(11*x**2 - 3*x + 1)
65
+ assert guess_generating_function([factorial(k) for k in range(12)],
66
+ types=['egf'])['egf'] == 1/(-x + 1)
67
+ assert guess_generating_function([k+1 for k in range(12)],
68
+ types=['egf']) == {'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)}
69
+
70
+
71
+ def test_guess():
72
+ i0, i1 = symbols('i0 i1')
73
+ assert guess([1, 2, 6, 24, 120], evaluate=False) == [Product(i1 + 1, (i1, 1, i0 - 1))]
74
+ assert guess([1, 2, 6, 24, 120]) == [RisingFactorial(2, i0 - 1)]
75
+ assert guess([1, 2, 7, 42, 429, 7436, 218348, 10850216], niter=4) == [
76
+ 2**(i0 - 1)*(Rational(27, 16))**(i0**2/2 - 3*i0/2 +
77
+ 1)*Product(RisingFactorial(Rational(5, 3), i1 - 1)*RisingFactorial(Rational(7, 3), i1
78
+ - 1)/(RisingFactorial(Rational(3, 2), i1 - 1)*RisingFactorial(Rational(5, 2), i1 -
79
+ 1)), (i1, 1, i0 - 1))]
80
+ assert guess([1, 0, 2]) == []
81
+ x, y = symbols('x y')
82
+ assert guess([1, 2, 6, 24, 120], variables=[x, y]) == [RisingFactorial(2, x - 1)]
venv/lib/python3.10/site-packages/sympy/concrete/tests/test_products.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.products import (Product, product)
2
+ from sympy.concrete.summations import Sum
3
+ from sympy.core.function import (Derivative, Function, diff)
4
+ from sympy.core.numbers import (Rational, oo, pi)
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
7
+ from sympy.functions.combinatorial.factorials import (rf, factorial)
8
+ from sympy.functions.elementary.exponential import (exp, log)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import (cos, sin)
11
+ from sympy.functions.special.tensor_functions import KroneckerDelta
12
+ from sympy.simplify.combsimp import combsimp
13
+ from sympy.simplify.simplify import simplify
14
+ from sympy.testing.pytest import raises
15
+
16
+ a, k, n, m, x = symbols('a,k,n,m,x', integer=True)
17
+ f = Function('f')
18
+
19
+
20
+ def test_karr_convention():
21
+ # Test the Karr product convention that we want to hold.
22
+ # See his paper "Summation in Finite Terms" for a detailed
23
+ # reasoning why we really want exactly this definition.
24
+ # The convention is described for sums on page 309 and
25
+ # essentially in section 1.4, definition 3. For products
26
+ # we can find in analogy:
27
+ #
28
+ # \prod_{m <= i < n} f(i) 'has the obvious meaning' for m < n
29
+ # \prod_{m <= i < n} f(i) = 0 for m = n
30
+ # \prod_{m <= i < n} f(i) = 1 / \prod_{n <= i < m} f(i) for m > n
31
+ #
32
+ # It is important to note that he defines all products with
33
+ # the upper limit being *exclusive*.
34
+ # In contrast, SymPy and the usual mathematical notation has:
35
+ #
36
+ # prod_{i = a}^b f(i) = f(a) * f(a+1) * ... * f(b-1) * f(b)
37
+ #
38
+ # with the upper limit *inclusive*. So translating between
39
+ # the two we find that:
40
+ #
41
+ # \prod_{m <= i < n} f(i) = \prod_{i = m}^{n-1} f(i)
42
+ #
43
+ # where we intentionally used two different ways to typeset the
44
+ # products and its limits.
45
+
46
+ i = Symbol("i", integer=True)
47
+ k = Symbol("k", integer=True)
48
+ j = Symbol("j", integer=True, positive=True)
49
+
50
+ # A simple example with a concrete factors and symbolic limits.
51
+
52
+ # The normal product: m = k and n = k + j and therefore m < n:
53
+ m = k
54
+ n = k + j
55
+
56
+ a = m
57
+ b = n - 1
58
+ S1 = Product(i**2, (i, a, b)).doit()
59
+
60
+ # The reversed product: m = k + j and n = k and therefore m > n:
61
+ m = k + j
62
+ n = k
63
+
64
+ a = m
65
+ b = n - 1
66
+ S2 = Product(i**2, (i, a, b)).doit()
67
+
68
+ assert S1 * S2 == 1
69
+
70
+ # Test the empty product: m = k and n = k and therefore m = n:
71
+ m = k
72
+ n = k
73
+
74
+ a = m
75
+ b = n - 1
76
+ Sz = Product(i**2, (i, a, b)).doit()
77
+
78
+ assert Sz == 1
79
+
80
+ # Another example this time with an unspecified factor and
81
+ # numeric limits. (We can not do both tests in the same example.)
82
+ f = Function("f")
83
+
84
+ # The normal product with m < n:
85
+ m = 2
86
+ n = 11
87
+
88
+ a = m
89
+ b = n - 1
90
+ S1 = Product(f(i), (i, a, b)).doit()
91
+
92
+ # The reversed product with m > n:
93
+ m = 11
94
+ n = 2
95
+
96
+ a = m
97
+ b = n - 1
98
+ S2 = Product(f(i), (i, a, b)).doit()
99
+
100
+ assert simplify(S1 * S2) == 1
101
+
102
+ # Test the empty product with m = n:
103
+ m = 5
104
+ n = 5
105
+
106
+ a = m
107
+ b = n - 1
108
+ Sz = Product(f(i), (i, a, b)).doit()
109
+
110
+ assert Sz == 1
111
+
112
+
113
+ def test_karr_proposition_2a():
114
+ # Test Karr, page 309, proposition 2, part a
115
+ i, u, v = symbols('i u v', integer=True)
116
+
117
+ def test_the_product(m, n):
118
+ # g
119
+ g = i**3 + 2*i**2 - 3*i
120
+ # f = Delta g
121
+ f = simplify(g.subs(i, i+1) / g)
122
+ # The product
123
+ a = m
124
+ b = n - 1
125
+ P = Product(f, (i, a, b)).doit()
126
+ # Test if Product_{m <= i < n} f(i) = g(n) / g(m)
127
+ assert combsimp(P / (g.subs(i, n) / g.subs(i, m))) == 1
128
+
129
+ # m < n
130
+ test_the_product(u, u + v)
131
+ # m = n
132
+ test_the_product(u, u)
133
+ # m > n
134
+ test_the_product(u + v, u)
135
+
136
+
137
+ def test_karr_proposition_2b():
138
+ # Test Karr, page 309, proposition 2, part b
139
+ i, u, v, w = symbols('i u v w', integer=True)
140
+
141
+ def test_the_product(l, n, m):
142
+ # Productmand
143
+ s = i**3
144
+ # First product
145
+ a = l
146
+ b = n - 1
147
+ S1 = Product(s, (i, a, b)).doit()
148
+ # Second product
149
+ a = l
150
+ b = m - 1
151
+ S2 = Product(s, (i, a, b)).doit()
152
+ # Third product
153
+ a = m
154
+ b = n - 1
155
+ S3 = Product(s, (i, a, b)).doit()
156
+ # Test if S1 = S2 * S3 as required
157
+ assert combsimp(S1 / (S2 * S3)) == 1
158
+
159
+ # l < m < n
160
+ test_the_product(u, u + v, u + v + w)
161
+ # l < m = n
162
+ test_the_product(u, u + v, u + v)
163
+ # l < m > n
164
+ test_the_product(u, u + v + w, v)
165
+ # l = m < n
166
+ test_the_product(u, u, u + v)
167
+ # l = m = n
168
+ test_the_product(u, u, u)
169
+ # l = m > n
170
+ test_the_product(u + v, u + v, u)
171
+ # l > m < n
172
+ test_the_product(u + v, u, u + w)
173
+ # l > m = n
174
+ test_the_product(u + v, u, u)
175
+ # l > m > n
176
+ test_the_product(u + v + w, u + v, u)
177
+
178
+
179
+ def test_simple_products():
180
+ assert product(2, (k, a, n)) == 2**(n - a + 1)
181
+ assert product(k, (k, 1, n)) == factorial(n)
182
+ assert product(k**3, (k, 1, n)) == factorial(n)**3
183
+
184
+ assert product(k + 1, (k, 0, n - 1)) == factorial(n)
185
+ assert product(k + 1, (k, a, n - 1)) == rf(1 + a, n - a)
186
+
187
+ assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5)
188
+ assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5)
189
+ assert product(cos(k), (k, 1, Rational(5, 2))) != cos(1)*cos(2)
190
+
191
+ assert isinstance(product(k**k, (k, 1, n)), Product)
192
+
193
+ assert Product(x**k, (k, 1, n)).variables == [k]
194
+
195
+ raises(ValueError, lambda: Product(n))
196
+ raises(ValueError, lambda: Product(n, k))
197
+ raises(ValueError, lambda: Product(n, k, 1))
198
+ raises(ValueError, lambda: Product(n, k, 1, 10))
199
+ raises(ValueError, lambda: Product(n, (k, 1)))
200
+
201
+ assert product(1, (n, 1, oo)) == 1 # issue 8301
202
+ assert product(2, (n, 1, oo)) is oo
203
+ assert product(-1, (n, 1, oo)).func is Product
204
+
205
+
206
+ def test_multiple_products():
207
+ assert product(x, (n, 1, k), (k, 1, m)) == x**(m**2/2 + m/2)
208
+ assert product(f(n), (
209
+ n, 1, m), (m, 1, k)) == Product(f(n), (n, 1, m), (m, 1, k)).doit()
210
+ assert Product(f(n), (m, 1, k), (n, 1, k)).doit() == \
211
+ Product(Product(f(n), (m, 1, k)), (n, 1, k)).doit() == \
212
+ product(f(n), (m, 1, k), (n, 1, k)) == \
213
+ product(product(f(n), (m, 1, k)), (n, 1, k)) == \
214
+ Product(f(n)**k, (n, 1, k))
215
+ assert Product(
216
+ x, (x, 1, k), (k, 1, n)).doit() == Product(factorial(k), (k, 1, n))
217
+
218
+ assert Product(x**k, (n, 1, k), (k, 1, m)).variables == [n, k]
219
+
220
+
221
+ def test_rational_products():
222
+ assert product(1 + 1/k, (k, 1, n)) == rf(2, n)/factorial(n)
223
+
224
+
225
+ def test_special_products():
226
+ # Wallis product
227
+ assert product((4*k)**2 / (4*k**2 - 1), (k, 1, n)) == \
228
+ 4**n*factorial(n)**2/rf(S.Half, n)/rf(Rational(3, 2), n)
229
+
230
+ # Euler's product formula for sin
231
+ assert product(1 + a/k**2, (k, 1, n)) == \
232
+ rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2
233
+
234
+
235
+ def test__eval_product():
236
+ from sympy.abc import i, n
237
+ # issue 4809
238
+ a = Function('a')
239
+ assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n))
240
+ # issue 4810
241
+ assert product(2**i, (i, 1, n)) == 2**(n*(n + 1)/2)
242
+ k, m = symbols('k m', integer=True)
243
+ assert product(2**i, (i, k, m)) == 2**(-k**2/2 + k/2 + m**2/2 + m/2)
244
+ n = Symbol('n', negative=True, integer=True)
245
+ p = Symbol('p', positive=True, integer=True)
246
+ assert product(2**i, (i, n, p)) == 2**(-n**2/2 + n/2 + p**2/2 + p/2)
247
+ assert product(2**i, (i, p, n)) == 2**(n**2/2 + n/2 - p**2/2 + p/2)
248
+
249
+
250
+ def test_product_pow():
251
+ # issue 4817
252
+ assert product(2**f(k), (k, 1, n)) == 2**Sum(f(k), (k, 1, n))
253
+ assert product(2**(2*f(k)), (k, 1, n)) == 2**Sum(2*f(k), (k, 1, n))
254
+
255
+
256
+ def test_infinite_product():
257
+ # issue 5737
258
+ assert isinstance(Product(2**(1/factorial(n)), (n, 0, oo)), Product)
259
+
260
+
261
+ def test_conjugate_transpose():
262
+ p = Product(x**k, (k, 1, 3))
263
+ assert p.adjoint().doit() == p.doit().adjoint()
264
+ assert p.conjugate().doit() == p.doit().conjugate()
265
+ assert p.transpose().doit() == p.doit().transpose()
266
+
267
+ A, B = symbols("A B", commutative=False)
268
+ p = Product(A*B**k, (k, 1, 3))
269
+ assert p.adjoint().doit() == p.doit().adjoint()
270
+ assert p.conjugate().doit() == p.doit().conjugate()
271
+ assert p.transpose().doit() == p.doit().transpose()
272
+
273
+ p = Product(B**k*A, (k, 1, 3))
274
+ assert p.adjoint().doit() == p.doit().adjoint()
275
+ assert p.conjugate().doit() == p.doit().conjugate()
276
+ assert p.transpose().doit() == p.doit().transpose()
277
+
278
+
279
+ def test_simplify_prod():
280
+ y, t, b, c, v, d = symbols('y, t, b, c, v, d', integer = True)
281
+
282
+ _simplify = lambda e: simplify(e, doit=False)
283
+ assert _simplify(Product(x*y, (x, n, m), (y, a, k)) * \
284
+ Product(y, (x, n, m), (y, a, k))) == \
285
+ Product(x*y**2, (x, n, m), (y, a, k))
286
+ assert _simplify(3 * y* Product(x, (x, n, m)) * Product(x, (x, m + 1, a))) \
287
+ == 3 * y * Product(x, (x, n, a))
288
+ assert _simplify(Product(x, (x, k + 1, a)) * Product(x, (x, n, k))) == \
289
+ Product(x, (x, n, a))
290
+ assert _simplify(Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))) == \
291
+ Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))
292
+ assert _simplify(Product(x, (t, a, b)) * Product(y, (t, a, b)) * \
293
+ Product(x, (t, b+1, c))) == Product(x*y, (t, a, b)) * \
294
+ Product(x, (t, b+1, c))
295
+ assert _simplify(Product(x, (t, a, b)) * Product(x, (t, b+1, c)) * \
296
+ Product(y, (t, a, b))) == Product(x*y, (t, a, b)) * \
297
+ Product(x, (t, b+1, c))
298
+ assert _simplify(Product(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
299
+ Product(2, (t, a, b))
300
+ assert _simplify(Product(sin(t)**2 + cos(t)**2 - 1, (t, a, b))) == \
301
+ Product(0, (t, a, b))
302
+ assert _simplify(Product(v*Product(sin(t)**2 + cos(t)**2, (t, a, b)),
303
+ (v, c, d))) == Product(v*Product(1, (t, a, b)), (v, c, d))
304
+
305
+
306
+ def test_change_index():
307
+ b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
308
+
309
+ assert Product(x, (x, a, b)).change_index(x, x + 1, y) == \
310
+ Product(y - 1, (y, a + 1, b + 1))
311
+ assert Product(x**2, (x, a, b)).change_index(x, x - 1) == \
312
+ Product((x + 1)**2, (x, a - 1, b - 1))
313
+ assert Product(x**2, (x, a, b)).change_index(x, -x, y) == \
314
+ Product((-y)**2, (y, -b, -a))
315
+ assert Product(x, (x, a, b)).change_index(x, -x - 1) == \
316
+ Product(-x - 1, (x, - b - 1, -a - 1))
317
+ assert Product(x*y, (x, a, b), (y, c, d)).change_index(x, x - 1, z) == \
318
+ Product((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
319
+
320
+
321
+ def test_reorder():
322
+ b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
323
+
324
+ assert Product(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
325
+ Product(x*y, (y, c, d), (x, a, b))
326
+ assert Product(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
327
+ Product(x, (x, c, d), (x, a, b))
328
+ assert Product(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
329
+ (2, 0), (0, 1)) == Product(x*y + z, (z, m, n), (y, c, d), (x, a, b))
330
+ assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
331
+ (0, 1), (1, 2), (0, 2)) == \
332
+ Product(x*y*z, (x, a, b), (z, m, n), (y, c, d))
333
+ assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
334
+ (x, y), (y, z), (x, z)) == \
335
+ Product(x*y*z, (x, a, b), (z, m, n), (y, c, d))
336
+ assert Product(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
337
+ Product(x*y, (y, c, d), (x, a, b))
338
+ assert Product(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
339
+ Product(x*y, (y, c, d), (x, a, b))
340
+
341
+
342
+ def test_Product_is_convergent():
343
+ assert Product(1/n**2, (n, 1, oo)).is_convergent() is S.false
344
+ assert Product(exp(1/n**2), (n, 1, oo)).is_convergent() is S.true
345
+ assert Product(1/n, (n, 1, oo)).is_convergent() is S.false
346
+ assert Product(1 + 1/n, (n, 1, oo)).is_convergent() is S.false
347
+ assert Product(1 + 1/n**2, (n, 1, oo)).is_convergent() is S.true
348
+
349
+
350
+ def test_reverse_order():
351
+ x, y, a, b, c, d= symbols('x, y, a, b, c, d', integer = True)
352
+
353
+ assert Product(x, (x, 0, 3)).reverse_order(0) == Product(1/x, (x, 4, -1))
354
+ assert Product(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
355
+ Product(x*y, (x, 6, 0), (y, 7, -1))
356
+ assert Product(x, (x, 1, 2)).reverse_order(0) == Product(1/x, (x, 3, 0))
357
+ assert Product(x, (x, 1, 3)).reverse_order(0) == Product(1/x, (x, 4, 0))
358
+ assert Product(x, (x, 1, a)).reverse_order(0) == Product(1/x, (x, a + 1, 0))
359
+ assert Product(x, (x, a, 5)).reverse_order(0) == Product(1/x, (x, 6, a - 1))
360
+ assert Product(x, (x, a + 1, a + 5)).reverse_order(0) == \
361
+ Product(1/x, (x, a + 6, a))
362
+ assert Product(x, (x, a + 1, a + 2)).reverse_order(0) == \
363
+ Product(1/x, (x, a + 3, a))
364
+ assert Product(x, (x, a + 1, a + 1)).reverse_order(0) == \
365
+ Product(1/x, (x, a + 2, a))
366
+ assert Product(x, (x, a, b)).reverse_order(0) == Product(1/x, (x, b + 1, a - 1))
367
+ assert Product(x, (x, a, b)).reverse_order(x) == Product(1/x, (x, b + 1, a - 1))
368
+ assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
369
+ Product(x*y, (x, b + 1, a - 1), (y, 6, 1))
370
+ assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
371
+ Product(x*y, (x, b + 1, a - 1), (y, 6, 1))
372
+
373
+
374
+ def test_issue_9983():
375
+ n = Symbol('n', integer=True, positive=True)
376
+ p = Product(1 + 1/n**Rational(2, 3), (n, 1, oo))
377
+ assert p.is_convergent() is S.false
378
+ assert product(1 + 1/n**Rational(2, 3), (n, 1, oo)) == p.doit()
379
+
380
+
381
+ def test_issue_13546():
382
+ n = Symbol('n')
383
+ k = Symbol('k')
384
+ p = Product(n + 1 / 2**k, (k, 0, n-1)).doit()
385
+ assert p.subs(n, 2).doit() == Rational(15, 2)
386
+
387
+
388
+ def test_issue_14036():
389
+ a, n = symbols('a n')
390
+ assert product(1 - a**2 / (n*pi)**2, [n, 1, oo]) != 0
391
+
392
+
393
+ def test_rewrite_Sum():
394
+ assert Product(1 - S.Half**2/k**2, (k, 1, oo)).rewrite(Sum) == \
395
+ exp(Sum(log(1 - 1/(4*k**2)), (k, 1, oo)))
396
+
397
+
398
+ def test_KroneckerDelta_Product():
399
+ y = Symbol('y')
400
+ assert Product(x*KroneckerDelta(x, y), (x, 0, 1)).doit() == 0
401
+
402
+
403
+ def test_issue_20848():
404
+ _i = Dummy('i')
405
+ t, y, z = symbols('t y z')
406
+ assert diff(Product(x, (y, 1, z)), x).as_dummy() == Sum(Product(x, (y, 1, _i - 1))*Product(x, (y, _i + 1, z)), (_i, 1, z)).as_dummy()
407
+ assert diff(Product(x, (y, 1, z)), x).doit() == x**(z - 1)*z
408
+ assert diff(Product(x, (y, x, z)), x) == Derivative(Product(x, (y, x, z)), x)
409
+ assert diff(Product(t, (x, 1, z)), x) == S(0)
410
+ assert Product(sin(n*x), (n, -1, 1)).diff(x).doit() == S(0)
venv/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py ADDED
@@ -0,0 +1,1646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.concrete.expr_with_intlimits import ReorderError
4
+ from sympy.concrete.products import (Product, product)
5
+ from sympy.concrete.summations import (Sum, summation, telescopic,
6
+ eval_sum_residue, _dummy_with_inherited_properties_concrete)
7
+ from sympy.core.function import (Derivative, Function)
8
+ from sympy.core import (Catalan, EulerGamma)
9
+ from sympy.core.facts import InconsistentAssumptions
10
+ from sympy.core.mod import Mod
11
+ from sympy.core.numbers import (E, I, Rational, nan, oo, pi)
12
+ from sympy.core.relational import Eq
13
+ from sympy.core.numbers import Float
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
18
+ from sympy.functions.combinatorial.numbers import harmonic
19
+ from sympy.functions.elementary.complexes import Abs
20
+ from sympy.functions.elementary.exponential import (exp, log)
21
+ from sympy.functions.elementary.hyperbolic import (sinh, tanh)
22
+ from sympy.functions.elementary.integers import floor
23
+ from sympy.functions.elementary.miscellaneous import sqrt
24
+ from sympy.functions.elementary.piecewise import Piecewise
25
+ from sympy.functions.elementary.trigonometric import (cos, sin)
26
+ from sympy.functions.special.gamma_functions import (gamma, lowergamma)
27
+ from sympy.functions.special.tensor_functions import KroneckerDelta
28
+ from sympy.functions.special.zeta_functions import zeta
29
+ from sympy.integrals.integrals import Integral
30
+ from sympy.logic.boolalg import And, Or
31
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
32
+ from sympy.matrices.expressions.special import Identity
33
+ from sympy.matrices import (Matrix, SparseMatrix,
34
+ ImmutableDenseMatrix, ImmutableSparseMatrix, diag)
35
+ from sympy.sets.fancysets import Range
36
+ from sympy.sets.sets import Interval
37
+ from sympy.simplify.combsimp import combsimp
38
+ from sympy.simplify.simplify import simplify
39
+ from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
40
+ from sympy.testing.pytest import XFAIL, raises, slow
41
+ from sympy.abc import a, b, c, d, k, m, x, y, z
42
+
43
+ n = Symbol('n', integer=True)
44
+ f, g = symbols('f g', cls=Function)
45
+
46
+ def test_karr_convention():
47
+ # Test the Karr summation convention that we want to hold.
48
+ # See his paper "Summation in Finite Terms" for a detailed
49
+ # reasoning why we really want exactly this definition.
50
+ # The convention is described on page 309 and essentially
51
+ # in section 1.4, definition 3:
52
+ #
53
+ # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n
54
+ # \sum_{m <= i < n} f(i) = 0 for m = n
55
+ # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n
56
+ #
57
+ # It is important to note that he defines all sums with
58
+ # the upper limit being *exclusive*.
59
+ # In contrast, SymPy and the usual mathematical notation has:
60
+ #
61
+ # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
62
+ #
63
+ # with the upper limit *inclusive*. So translating between
64
+ # the two we find that:
65
+ #
66
+ # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
67
+ #
68
+ # where we intentionally used two different ways to typeset the
69
+ # sum and its limits.
70
+
71
+ i = Symbol("i", integer=True)
72
+ k = Symbol("k", integer=True)
73
+ j = Symbol("j", integer=True)
74
+
75
+ # A simple example with a concrete summand and symbolic limits.
76
+
77
+ # The normal sum: m = k and n = k + j and therefore m < n:
78
+ m = k
79
+ n = k + j
80
+
81
+ a = m
82
+ b = n - 1
83
+ S1 = Sum(i**2, (i, a, b)).doit()
84
+
85
+ # The reversed sum: m = k + j and n = k and therefore m > n:
86
+ m = k + j
87
+ n = k
88
+
89
+ a = m
90
+ b = n - 1
91
+ S2 = Sum(i**2, (i, a, b)).doit()
92
+
93
+ assert simplify(S1 + S2) == 0
94
+
95
+ # Test the empty sum: m = k and n = k and therefore m = n:
96
+ m = k
97
+ n = k
98
+
99
+ a = m
100
+ b = n - 1
101
+ Sz = Sum(i**2, (i, a, b)).doit()
102
+
103
+ assert Sz == 0
104
+
105
+ # Another example this time with an unspecified summand and
106
+ # numeric limits. (We can not do both tests in the same example.)
107
+
108
+ # The normal sum with m < n:
109
+ m = 2
110
+ n = 11
111
+
112
+ a = m
113
+ b = n - 1
114
+ S1 = Sum(f(i), (i, a, b)).doit()
115
+
116
+ # The reversed sum with m > n:
117
+ m = 11
118
+ n = 2
119
+
120
+ a = m
121
+ b = n - 1
122
+ S2 = Sum(f(i), (i, a, b)).doit()
123
+
124
+ assert simplify(S1 + S2) == 0
125
+
126
+ # Test the empty sum with m = n:
127
+ m = 5
128
+ n = 5
129
+
130
+ a = m
131
+ b = n - 1
132
+ Sz = Sum(f(i), (i, a, b)).doit()
133
+
134
+ assert Sz == 0
135
+
136
+ e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
137
+ s = Sum(e, (i, 0, 11))
138
+ assert s.n(3) == s.doit().n(3)
139
+
140
+
141
+ def test_karr_proposition_2a():
142
+ # Test Karr, page 309, proposition 2, part a
143
+ i = Symbol("i", integer=True)
144
+ u = Symbol("u", integer=True)
145
+ v = Symbol("v", integer=True)
146
+
147
+ def test_the_sum(m, n):
148
+ # g
149
+ g = i**3 + 2*i**2 - 3*i
150
+ # f = Delta g
151
+ f = simplify(g.subs(i, i+1) - g)
152
+ # The sum
153
+ a = m
154
+ b = n - 1
155
+ S = Sum(f, (i, a, b)).doit()
156
+ # Test if Sum_{m <= i < n} f(i) = g(n) - g(m)
157
+ assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0
158
+
159
+ # m < n
160
+ test_the_sum(u, u+v)
161
+ # m = n
162
+ test_the_sum(u, u )
163
+ # m > n
164
+ test_the_sum(u+v, u )
165
+
166
+
167
+ def test_karr_proposition_2b():
168
+ # Test Karr, page 309, proposition 2, part b
169
+ i = Symbol("i", integer=True)
170
+ u = Symbol("u", integer=True)
171
+ v = Symbol("v", integer=True)
172
+ w = Symbol("w", integer=True)
173
+
174
+ def test_the_sum(l, n, m):
175
+ # Summand
176
+ s = i**3
177
+ # First sum
178
+ a = l
179
+ b = n - 1
180
+ S1 = Sum(s, (i, a, b)).doit()
181
+ # Second sum
182
+ a = l
183
+ b = m - 1
184
+ S2 = Sum(s, (i, a, b)).doit()
185
+ # Third sum
186
+ a = m
187
+ b = n - 1
188
+ S3 = Sum(s, (i, a, b)).doit()
189
+ # Test if S1 = S2 + S3 as required
190
+ assert S1 - (S2 + S3) == 0
191
+
192
+ # l < m < n
193
+ test_the_sum(u, u+v, u+v+w)
194
+ # l < m = n
195
+ test_the_sum(u, u+v, u+v )
196
+ # l < m > n
197
+ test_the_sum(u, u+v+w, v )
198
+ # l = m < n
199
+ test_the_sum(u, u, u+v )
200
+ # l = m = n
201
+ test_the_sum(u, u, u )
202
+ # l = m > n
203
+ test_the_sum(u+v, u+v, u )
204
+ # l > m < n
205
+ test_the_sum(u+v, u, u+w )
206
+ # l > m = n
207
+ test_the_sum(u+v, u, u )
208
+ # l > m > n
209
+ test_the_sum(u+v+w, u+v, u )
210
+
211
+
212
+ def test_arithmetic_sums():
213
+ assert summation(1, (n, a, b)) == b - a + 1
214
+ assert Sum(S.NaN, (n, a, b)) is S.NaN
215
+ assert Sum(x, (n, a, a)).doit() == x
216
+ assert Sum(x, (x, a, a)).doit() == a
217
+ assert Sum(x, (n, 1, a)).doit() == a*x
218
+ assert Sum(x, (x, Range(1, 11))).doit() == 55
219
+ assert Sum(x, (x, Range(1, 11, 2))).doit() == 25
220
+ assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2)))
221
+ lo, hi = 1, 2
222
+ s1 = Sum(n, (n, lo, hi))
223
+ s2 = Sum(n, (n, hi, lo))
224
+ assert s1 != s2
225
+ assert s1.doit() == 3 and s2.doit() == 0
226
+ lo, hi = x, x + 1
227
+ s1 = Sum(n, (n, lo, hi))
228
+ s2 = Sum(n, (n, hi, lo))
229
+ assert s1 != s2
230
+ assert s1.doit() == 2*x + 1 and s2.doit() == 0
231
+ assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \
232
+ y**2 + 2
233
+ assert summation(1, (n, 1, 10)) == 10
234
+ assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000
235
+ assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \
236
+ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2
237
+ assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1)
238
+ assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2)
239
+ assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum)
240
+ assert summation(k, (k, 0, oo)) is oo
241
+ assert summation(k, (k, Range(1, 11))) == 55
242
+
243
+
244
+ def test_polynomial_sums():
245
+ assert summation(n**2, (n, 3, 8)) == 199
246
+ assert summation(n, (n, a, b)) == \
247
+ ((a + b)*(b - a + 1)/2).expand()
248
+ assert summation(n**2, (n, 1, b)) == \
249
+ ((2*b**3 + 3*b**2 + b)/6).expand()
250
+ assert summation(n**3, (n, 1, b)) == \
251
+ ((b**4 + 2*b**3 + b**2)/4).expand()
252
+ assert summation(n**6, (n, 1, b)) == \
253
+ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand()
254
+
255
+
256
+ def test_geometric_sums():
257
+ assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi)
258
+ assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1
259
+ assert summation(S.Half**n, (n, 1, oo)) == 1
260
+ assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
261
+ assert summation(2**n, (n, 1, oo)) is oo
262
+ assert summation(2**(-n), (n, 1, oo)) == 1
263
+ assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54)
264
+ assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15)
265
+ assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1)
266
+
267
+ # issue 6664:
268
+ assert summation(x**n, (n, 0, oo)) == \
269
+ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True))
270
+
271
+ assert summation(-2**n, (n, 0, oo)) is -oo
272
+ assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo))
273
+
274
+ # issue 6802:
275
+ assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1
276
+ assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3)
277
+ assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half
278
+ assert summation(y**x, (x, a, b)) == \
279
+ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True))
280
+ assert summation((-2)**(y*x + 2), (x, 0, n)) == \
281
+ 4*Piecewise((n + 1, Eq((-2)**y, 1)),
282
+ ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))
283
+
284
+ # issue 8251:
285
+ assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo
286
+
287
+ #issue 9908:
288
+ assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2))
289
+
290
+ #issue 11642:
291
+ result = Sum(0.5**n, (n, 1, oo)).doit()
292
+ assert result == 1.0
293
+ assert result.is_Float
294
+
295
+ result = Sum(0.25**n, (n, 1, oo)).doit()
296
+ assert result == 1/3.
297
+ assert result.is_Float
298
+
299
+ result = Sum(0.99999**n, (n, 1, oo)).doit()
300
+ assert result == 99999.0
301
+ assert result.is_Float
302
+
303
+ result = Sum(S.Half**n, (n, 1, oo)).doit()
304
+ assert result == 1
305
+ assert not result.is_Float
306
+
307
+ result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit()
308
+ assert result == Rational(3, 2)
309
+ assert not result.is_Float
310
+
311
+ assert Sum(1.0**n, (n, 1, oo)).doit() is oo
312
+ assert Sum(2.43**n, (n, 1, oo)).doit() is oo
313
+
314
+ # Issue 13979
315
+ i, k, q = symbols('i k q', integer=True)
316
+ result = summation(
317
+ exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1)
318
+ )
319
+ assert result.simplify() == Piecewise(
320
+ (1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True)
321
+ )
322
+
323
+ #Issue 23491
324
+ assert Sum(1/(n**2 + 1), (n, 1, oo)).doit() == S(-1)/2 + pi/(2*tanh(pi))
325
+
326
+ def test_harmonic_sums():
327
+ assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n))
328
+ assert summation(1/k, (k, 1, n)) == harmonic(n)
329
+ assert summation(n/k, (k, 1, n)) == n*harmonic(n)
330
+ assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4)
331
+
332
+
333
+ def test_composite_sums():
334
+ f = S.Half*(7 - 6*n + Rational(1, 7)*n**3)
335
+ s = summation(f, (n, a, b))
336
+ assert not isinstance(s, Sum)
337
+ A = 0
338
+ for i in range(-3, 5):
339
+ A += f.subs(n, i)
340
+ B = s.subs(a, -3).subs(b, 4)
341
+ assert A == B
342
+
343
+
344
+ def test_hypergeometric_sums():
345
+ assert summation(
346
+ binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n
347
+ assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5)
348
+
349
+
350
+ def test_other_sums():
351
+ f = m**2 + m*exp(m)
352
+ g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5
353
+
354
+ assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g
355
+ assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10)
356
+
357
+ fac = factorial
358
+
359
+
360
+ def NS(e, n=15, **options):
361
+ return str(sympify(e).evalf(n, **options))
362
+
363
+
364
+ def test_evalf_fast_series():
365
+ # Euler transformed series for sqrt(1+x)
366
+ assert NS(Sum(
367
+ fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100)
368
+
369
+ # Some series for exp(1)
370
+ estr = NS(E, 100)
371
+ assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr
372
+ assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr
373
+ assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr
374
+ assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr
375
+
376
+ pistr = NS(pi, 100)
377
+ # Ramanujan series for pi
378
+ assert NS(9801/sqrt(8)/Sum(fac(
379
+ 4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr
380
+ assert NS(1/Sum(
381
+ binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr
382
+ # Machin's formula for pi
383
+ assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) -
384
+ 4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr
385
+
386
+ # Apery's constant
387
+ astr = NS(zeta(3), 100)
388
+ P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \
389
+ n + 12463
390
+ assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac(
391
+ n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr
392
+ assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 /
393
+ fac(2*n + 1)**5, (n, 0, oo)), 100) == astr
394
+
395
+
396
+ def test_evalf_fast_series_issue_4021():
397
+ # Catalan's constant
398
+ assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3*
399
+ fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \
400
+ NS(Catalan, 100)
401
+ astr = NS(zeta(3), 100)
402
+ assert NS(5*Sum(
403
+ (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr
404
+ assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1)
405
+ **3 / fac(3*n), (n, 1, oo))/4, 100) == astr
406
+
407
+
408
+ def test_evalf_slow_series():
409
+ assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15)
410
+ assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50)
411
+ assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15)
412
+ assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100)
413
+ assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500)
414
+ assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15)
415
+ assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50)
416
+
417
+
418
+ def test_evalf_oo_to_oo():
419
+ # There used to be an error in certain cases
420
+ # Does not evaluate, but at least do not throw an error
421
+ # Evaluates symbolically to 0, which is not correct
422
+ assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo))
423
+ # This evaluates if from 1 to oo and symbolically
424
+ assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1))
425
+
426
+
427
+ def test_euler_maclaurin():
428
+ # Exact polynomial sums with E-M
429
+ def check_exact(f, a, b, m, n):
430
+ A = Sum(f, (k, a, b))
431
+ s, e = A.euler_maclaurin(m, n)
432
+ assert (e == 0) and (s.expand() == A.doit())
433
+ check_exact(k**4, a, b, 0, 2)
434
+ check_exact(k**4 + 2*k, a, b, 1, 2)
435
+ check_exact(k**4 + k**2, a, b, 1, 5)
436
+ check_exact(k**5, 2, 6, 1, 2)
437
+ check_exact(k**5, 2, 6, 1, 3)
438
+ assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0)
439
+ # Not exact
440
+ assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0
441
+ # Numerical test
442
+ for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]:
443
+ A = Sum(1/k**3, (k, 1, oo))
444
+ s, e = A.euler_maclaurin(mi, ni)
445
+ assert abs((s - zeta(3)).evalf()) < e.evalf()
446
+
447
+ raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin())
448
+
449
+
450
+ @slow
451
+ def test_evalf_euler_maclaurin():
452
+ assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266'
453
+ assert NS(Sum(1/k**k, (k, 1, oo)),
454
+ 50) == '1.2912859970626635404072825905956005414986193682745'
455
+ assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15)
456
+ assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50)
457
+ assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844'
458
+ assert NS(Sum(log(k)/k**2, (k, 1, oo)),
459
+ 50) == '0.93754825431584375370257409456786497789786028861483'
460
+ assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008'
461
+ assert NS(Sum(1/k, (k, 1000000, 2000000)),
462
+ 50) == '0.69314793056000780941723211364567656807940638436025'
463
+
464
+
465
+ def test_evalf_symbolic():
466
+ # issue 6328
467
+ expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3))
468
+ assert expr.evalf() == expr
469
+
470
+
471
+ def test_evalf_issue_3273():
472
+ assert Sum(0, (k, 1, oo)).evalf() == 0
473
+
474
+
475
+ def test_simple_products():
476
+ assert Product(S.NaN, (x, 1, 3)) is S.NaN
477
+ assert product(S.NaN, (x, 1, 3)) is S.NaN
478
+ assert Product(x, (n, a, a)).doit() == x
479
+ assert Product(x, (x, a, a)).doit() == a
480
+ assert Product(x, (y, 1, a)).doit() == x**a
481
+
482
+ lo, hi = 1, 2
483
+ s1 = Product(n, (n, lo, hi))
484
+ s2 = Product(n, (n, hi, lo))
485
+ assert s1 != s2
486
+ # This IS correct according to Karr product convention
487
+ assert s1.doit() == 2
488
+ assert s2.doit() == 1
489
+
490
+ lo, hi = x, x + 1
491
+ s1 = Product(n, (n, lo, hi))
492
+ s2 = Product(n, (n, hi, lo))
493
+ s3 = 1 / Product(n, (n, hi + 1, lo - 1))
494
+ assert s1 != s2
495
+ # This IS correct according to Karr product convention
496
+ assert s1.doit() == x*(x + 1)
497
+ assert s2.doit() == 1
498
+ assert s3.doit() == x*(x + 1)
499
+
500
+ assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \
501
+ (y**2 + 1)*(y**2 + 3)
502
+ assert product(2, (n, a, b)) == 2**(b - a + 1)
503
+ assert product(n, (n, 1, b)) == factorial(b)
504
+ assert product(n**3, (n, 1, b)) == factorial(b)**3
505
+ assert product(3**(2 + n), (n, a, b)) \
506
+ == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2)
507
+ assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5)
508
+ assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2)
509
+ assert isinstance(product(cos(n), (n, x, x + S.Half)), Product)
510
+ # If Product managed to evaluate this one, it most likely got it wrong!
511
+ assert isinstance(Product(n**n, (n, 1, b)), Product)
512
+
513
+
514
+ def test_rational_products():
515
+ assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a
516
+ assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a)
517
+ assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1))
518
+ assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \
519
+ a*gamma(a + 2)/(b + 1)/gamma(b + 3)
520
+ assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \
521
+ b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2))
522
+
523
+
524
+ def test_wallis_product():
525
+ # Wallis product, given in two different forms to ensure that Product
526
+ # can factor simple rational expressions
527
+ A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b))
528
+ B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b))
529
+ R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2)))
530
+ assert simplify(A.doit()) == R
531
+ assert simplify(B.doit()) == R
532
+ # This one should eventually also be doable (Euler's product formula for sin)
533
+ # assert Product(1+x/n**2, (n, 1, b)) == ...
534
+
535
+
536
+ def test_telescopic_sums():
537
+ #checks also input 2 of comment 1 issue 4127
538
+ assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n)
539
+ assert Sum(
540
+ f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m)
541
+ assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \
542
+ cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3)
543
+
544
+ # dummy variable shouldn't matter
545
+ assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \
546
+ telescopic(1/k, -k/(1 + k), (k, n - 1, n))
547
+
548
+ assert Sum(1/x/(x - 1), (x, a, b)).doit() == 1/(a - 1) - 1/b
549
+ eq = 1/((5*n + 2)*(5*(n + 1) + 2))
550
+ assert Sum(eq, (n, 0, oo)).doit() == S(1)/10
551
+ nz = symbols('nz', nonzero=True)
552
+ v = Sum(eq.subs(5, nz), (n, 0, oo)).doit()
553
+ assert v.subs(nz, 5).simplify() == S(1)/10
554
+ # check that apart is being used in non-symbolic case
555
+ s = Sum(eq, (n, 0, k)).doit()
556
+ v = Sum(eq, (n, 0, 10**100)).doit()
557
+ assert v == s.subs(k, 10**100)
558
+
559
+
560
+ def test_sum_reconstruct():
561
+ s = Sum(n**2, (n, -1, 1))
562
+ assert s == Sum(*s.args)
563
+ raises(ValueError, lambda: Sum(x, x))
564
+ raises(ValueError, lambda: Sum(x, (x, 1)))
565
+
566
+
567
+ def test_limit_subs():
568
+ for F in (Sum, Product, Integral):
569
+ assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2)
570
+ assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \
571
+ F(a, (a, c, 4))
572
+ assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1))
573
+
574
+
575
+ def test_function_subs():
576
+ S = Sum(x*f(y),(x,0,oo),(y,0,oo))
577
+ assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
578
+ assert S.subs(f(x),x) == S
579
+ raises(ValueError, lambda: S.subs(f(y),x+y) )
580
+ S = Sum(x*log(y),(x,0,oo),(y,0,oo))
581
+ assert S.subs(log(y),y) == S
582
+ S = Sum(x*f(y),(x,0,oo),(y,0,oo))
583
+ assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
584
+
585
+
586
+ def test_equality():
587
+ # if this fails remove special handling below
588
+ raises(ValueError, lambda: Sum(x, x))
589
+ r = symbols('x', real=True)
590
+ for F in (Sum, Product, Integral):
591
+ try:
592
+ assert F(x, x) != F(y, y)
593
+ assert F(x, (x, 1, 2)) != F(x, x)
594
+ assert F(x, (x, x)) != F(x, x) # or else they print the same
595
+ assert F(1, x) != F(1, y)
596
+ except ValueError:
597
+ pass
598
+ assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit
599
+ assert F(a, (x, 1, x)) != F(a, (y, 1, y))
600
+ assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression
601
+ assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions
602
+ assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff
603
+ assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x)))
604
+
605
+ # issue 5265
606
+ assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a))
607
+
608
+
609
+ def test_Sum_doit():
610
+ assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3
611
+ assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \
612
+ 3*Integral(a**2)
613
+ assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2)
614
+
615
+ # test nested sum evaluation
616
+ s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n))
617
+ assert 0 == (s.doit() - n*(n+1)*(n-1)).factor()
618
+
619
+ # Integer assumes finite
620
+ assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True))
621
+ assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1
622
+ assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True))
623
+ assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x
624
+ assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3
625
+ assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \
626
+ 3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True))
627
+ assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \
628
+ f(1) + f(2) + f(3)
629
+ assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \
630
+ Sum(f(n), (n, 1, oo))
631
+
632
+ # issue 2597
633
+ nmax = symbols('N', integer=True, positive=True)
634
+ pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True))
635
+ assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n),
636
+ (0, True)), (n, 1, nmax))
637
+
638
+ q, s = symbols('q, s')
639
+ assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1),
640
+ (Sum(n**(-2*s), (n, 1, oo)), True))
641
+ assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1),
642
+ (Sum((n + 1)**(-s), (n, 0, oo)), True))
643
+ assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise(
644
+ (zeta(s, q), And(q > 0, s > 1)),
645
+ (Sum((n + q)**(-s), (n, 0, oo)), True))
646
+ assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise(
647
+ (zeta(s, 2*q), And(2*q > 0, s > 1)),
648
+ (Sum((n + q)**(-s), (n, q, oo)), True))
649
+ assert summation(1/n**2, (n, 1, oo)) == zeta(2)
650
+ assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo))
651
+
652
+
653
+ def test_Product_doit():
654
+ assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9
655
+ assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \
656
+ 6*Integral(a**2)**3
657
+ assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3
658
+
659
+
660
+ def test_Sum_interface():
661
+ assert isinstance(Sum(0, (n, 0, 2)), Sum)
662
+ assert Sum(nan, (n, 0, 2)) is nan
663
+ assert Sum(nan, (n, 0, oo)) is nan
664
+ assert Sum(0, (n, 0, 2)).doit() == 0
665
+ assert isinstance(Sum(0, (n, 0, oo)), Sum)
666
+ assert Sum(0, (n, 0, oo)).doit() == 0
667
+ raises(ValueError, lambda: Sum(1))
668
+ raises(ValueError, lambda: summation(1))
669
+
670
+
671
+ def test_diff():
672
+ assert Sum(x, (x, 1, 2)).diff(x) == 0
673
+ assert Sum(x*y, (x, 1, 2)).diff(x) == 0
674
+ assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2))
675
+ e = Sum(x*y, (x, 1, a))
676
+ assert e.diff(a) == Derivative(e, a)
677
+ assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \
678
+ Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24
679
+ assert Sum(x, (x, 1, 2)).diff(y) == 0
680
+
681
+
682
+ def test_hypersum():
683
+ assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x)
684
+ assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x)
685
+ assert simplify(summation((-1)**n*x**(2*n + 1) /
686
+ factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120
687
+
688
+ assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3)
689
+ assert summation(1/n**4, (n, 1, oo)) == pi**4/90
690
+
691
+ s = summation(x**n*n, (n, -oo, 0))
692
+ assert s.is_Piecewise
693
+ assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2)
694
+ assert s.args[0].args[1] == (abs(1/x) < 1)
695
+
696
+ m = Symbol('n', integer=True, positive=True)
697
+ assert summation(binomial(m, k), (k, 0, m)) == 2**m
698
+
699
+
700
+ def test_issue_4170():
701
+ assert summation(1/factorial(k), (k, 0, oo)) == E
702
+
703
+
704
+ def test_is_commutative():
705
+ from sympy.physics.secondquant import NO, F, Fd
706
+ m = Symbol('m', commutative=False)
707
+ for f in (Sum, Product, Integral):
708
+ assert f(z, (z, 1, 1)).is_commutative is True
709
+ assert f(z*y, (z, 1, 6)).is_commutative is True
710
+ assert f(m*x, (x, 1, 2)).is_commutative is False
711
+
712
+ assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False
713
+
714
+
715
+ def test_is_zero():
716
+ for func in [Sum, Product]:
717
+ assert func(0, (x, 1, 1)).is_zero is True
718
+ assert func(x, (x, 1, 1)).is_zero is None
719
+
720
+ assert Sum(0, (x, 1, 0)).is_zero is True
721
+ assert Product(0, (x, 1, 0)).is_zero is False
722
+
723
+
724
+ def test_is_number():
725
+ # is number should not rely on evaluation or assumptions,
726
+ # it should be equivalent to `not foo.free_symbols`
727
+ assert Sum(1, (x, 1, 1)).is_number is True
728
+ assert Sum(1, (x, 1, x)).is_number is False
729
+ assert Sum(0, (x, y, z)).is_number is False
730
+ assert Sum(x, (y, 1, 2)).is_number is False
731
+ assert Sum(x, (y, 1, 1)).is_number is False
732
+ assert Sum(x, (x, 1, 2)).is_number is True
733
+ assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
734
+
735
+ assert Product(2, (x, 1, 1)).is_number is True
736
+ assert Product(2, (x, 1, y)).is_number is False
737
+ assert Product(0, (x, y, z)).is_number is False
738
+ assert Product(1, (x, y, z)).is_number is False
739
+ assert Product(x, (y, 1, x)).is_number is False
740
+ assert Product(x, (y, 1, 2)).is_number is False
741
+ assert Product(x, (y, 1, 1)).is_number is False
742
+ assert Product(x, (x, 1, 2)).is_number is True
743
+
744
+
745
+ def test_free_symbols():
746
+ for func in [Sum, Product]:
747
+ assert func(1, (x, 1, 2)).free_symbols == set()
748
+ assert func(0, (x, 1, y)).free_symbols == {y}
749
+ assert func(2, (x, 1, y)).free_symbols == {y}
750
+ assert func(x, (x, 1, 2)).free_symbols == set()
751
+ assert func(x, (x, 1, y)).free_symbols == {y}
752
+ assert func(x, (y, 1, y)).free_symbols == {x, y}
753
+ assert func(x, (y, 1, 2)).free_symbols == {x}
754
+ assert func(x, (y, 1, 1)).free_symbols == {x}
755
+ assert func(x, (y, 1, z)).free_symbols == {x, z}
756
+ assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set()
757
+ assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z}
758
+ assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y}
759
+ assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z}
760
+ assert Sum(1, (x, 1, y)).free_symbols == {y}
761
+ # free_symbols answers whether the object *as written* has free symbols,
762
+ # not whether the evaluated expression has free symbols
763
+ assert Product(1, (x, 1, y)).free_symbols == {y}
764
+ # don't count free symbols that are not independent of integration
765
+ # variable(s)
766
+ assert func(f(x), (f(x), 1, 2)).free_symbols == set()
767
+ assert func(f(x), (f(x), 1, x)).free_symbols == {x}
768
+ assert func(f(x), (f(x), 1, y)).free_symbols == {y}
769
+ assert func(f(x), (z, 1, y)).free_symbols == {x, y}
770
+
771
+
772
+ def test_conjugate_transpose():
773
+ A, B = symbols("A B", commutative=False)
774
+ p = Sum(A*B**n, (n, 1, 3))
775
+ assert p.adjoint().doit() == p.doit().adjoint()
776
+ assert p.conjugate().doit() == p.doit().conjugate()
777
+ assert p.transpose().doit() == p.doit().transpose()
778
+
779
+ p = Sum(B**n*A, (n, 1, 3))
780
+ assert p.adjoint().doit() == p.doit().adjoint()
781
+ assert p.conjugate().doit() == p.doit().conjugate()
782
+ assert p.transpose().doit() == p.doit().transpose()
783
+
784
+
785
+ def test_noncommutativity_honoured():
786
+ A, B = symbols("A B", commutative=False)
787
+ M = symbols('M', integer=True, positive=True)
788
+ p = Sum(A*B**n, (n, 1, M))
789
+ assert p.doit() == A*Piecewise((M, Eq(B, 1)),
790
+ ((B - B**(M + 1))*(1 - B)**(-1), True))
791
+
792
+ p = Sum(B**n*A, (n, 1, M))
793
+ assert p.doit() == Piecewise((M, Eq(B, 1)),
794
+ ((B - B**(M + 1))*(1 - B)**(-1), True))*A
795
+
796
+ p = Sum(B**n*A*B**n, (n, 1, M))
797
+ assert p.doit() == p
798
+
799
+
800
+ def test_issue_4171():
801
+ assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo
802
+ assert summation(2*k + 1, (k, 0, oo)) is oo
803
+
804
+
805
+ def test_issue_6273():
806
+ assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == Float(1, 2)
807
+
808
+
809
+ def test_issue_6274():
810
+ assert Sum(x, (x, 1, 0)).doit() == 0
811
+ assert NS(Sum(x, (x, 1, 0))) == '0'
812
+ assert Sum(n, (n, 10, 5)).doit() == -30
813
+ assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000'
814
+
815
+
816
+ def test_simplify_sum():
817
+ y, t, v = symbols('y, t, v')
818
+
819
+ _simplify = lambda e: simplify(e, doit=False)
820
+ assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \
821
+ Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k))
822
+ assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \
823
+ Sum(x, (x, n, a))
824
+ assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \
825
+ Sum(x, (x, n, a))
826
+ assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \
827
+ Sum(x, (x, n, a)) + Sum(1, (x, n, k))
828
+ assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \
829
+ 4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6))
830
+ assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \
831
+ Sum(x*(3*x + 1), (x, a, b))
832
+ assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \
833
+ 4 * y * Sum(z, (z, n, k))) + 1 == \
834
+ 4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1
835
+ assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \
836
+ 1 + Sum(x, (x, a, c))
837
+ assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \
838
+ Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
839
+ assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \
840
+ Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
841
+ assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \
842
+ _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c)))
843
+ assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \
844
+ Sum(x, (x, a, b)) * Sum(x**2, (x, a, b))
845
+ assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \
846
+ == (x + y + z) * Sum(1, (t, a, b)) # issue 8596
847
+ assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \
848
+ Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596
849
+ assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \
850
+ (Sum(x, (x, a, b)) / 3)
851
+ assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \
852
+ == Sum(f(x), (x, a, b))
853
+ assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0
854
+ assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b)))
855
+ assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \
856
+ c * (y + 1) * Sum(x, (x, a, b))
857
+ assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \
858
+ c * Sum(x, (x, a, b), (y, a, b))
859
+ assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \
860
+ c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b))
861
+ assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \
862
+ c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b))
863
+ assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \
864
+ Sum(d * t, (x, b, c)), (t, a, b))) == \
865
+ d * Sum(1, (x, a, c)) * Sum(t, (t, a, b))
866
+ assert _simplify(Sum(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
867
+ 2 * Sum(1, (t, a, b))
868
+
869
+
870
+ def test_change_index():
871
+ b, v, w = symbols('b, v, w', integer = True)
872
+
873
+ assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \
874
+ Sum(y - 1, (y, a + 1, b + 1))
875
+ assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \
876
+ Sum((x+1)**2, (x, a - 1, b - 1))
877
+ assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \
878
+ Sum((-y)**2, (y, -b, -a))
879
+ assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \
880
+ Sum(-x - 1, (x, -b - 1, -a - 1))
881
+ assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \
882
+ Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
883
+ assert Sum(x, (x, a, b)).change_index( x, x + v) == \
884
+ Sum(-v + x, (x, a + v, b + v))
885
+ assert Sum(x, (x, a, b)).change_index( x, -x - v) == \
886
+ Sum(-v - x, (x, -b - v, -a - v))
887
+ assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \
888
+ Sum(v/w, (v, b*w, a*w))
889
+ raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x))
890
+
891
+
892
+ def test_reorder():
893
+ b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
894
+
895
+ assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
896
+ Sum(x*y, (y, c, d), (x, a, b))
897
+ assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
898
+ Sum(x, (x, c, d), (x, a, b))
899
+ assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
900
+ (2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b))
901
+ assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
902
+ (0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
903
+ assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
904
+ (x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
905
+ assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
906
+ Sum(x*y, (y, c, d), (x, a, b))
907
+ assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
908
+ Sum(x*y, (y, c, d), (x, a, b))
909
+
910
+
911
+ def test_reverse_order():
912
+ assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1))
913
+ assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
914
+ Sum(x*y, (x, 6, 0), (y, 7, -1))
915
+ assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0))
916
+ assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0))
917
+ assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0))
918
+ assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1))
919
+ assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \
920
+ Sum(-x, (x, a + 6, a))
921
+ assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \
922
+ Sum(-x, (x, a + 3, a))
923
+ assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \
924
+ Sum(-x, (x, a + 2, a))
925
+ assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1))
926
+ assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1))
927
+ assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
928
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
929
+ assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
930
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
931
+
932
+
933
+ def test_issue_7097():
934
+ assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400))
935
+
936
+
937
+ def test_factor_expand_subs():
938
+ # test factoring
939
+ assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y))
940
+ assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y))
941
+ assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y))
942
+ assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y))
943
+
944
+ # test expand
945
+ _x = Symbol('x', zero=False)
946
+ assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y))
947
+ assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y))
948
+ assert Sum(_x**(n + 1)*(n + 1), (n, -1, oo)).expand() \
949
+ == Sum(n*_x*_x**n + _x*_x**n, (n, -1, oo))
950
+ assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \
951
+ == Sum(n*x**(n + 1) + x**(n + 1), (n, -1, oo))
952
+ assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(force=True) \
953
+ == Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo))
954
+ assert Sum(a*n+a*n**2,(n,0,4)).expand() \
955
+ == Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4))
956
+ assert Sum(_x**a*_x**n,(x,0,3)) \
957
+ == Sum(_x**(a+n),(x,0,3)).expand(power_exp=True)
958
+ _a, _n = symbols('a n', positive=True)
959
+ assert Sum(x**(_a+_n),(x,0,3)).expand(power_exp=True) \
960
+ == Sum(x**_a*x**_n, (x, 0, 3))
961
+ assert Sum(x**(_a-_n),(x,0,3)).expand(power_exp=True) \
962
+ == Sum(x**(_a-_n),(x,0,3)).expand(power_exp=False)
963
+
964
+ # test subs
965
+ assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3))
966
+ assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3))
967
+ assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10))
968
+ assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10))
969
+ assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10))
970
+
971
+
972
+ def test_distribution_over_equality():
973
+ assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
974
+ assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
975
+ Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
976
+
977
+
978
+ def test_issue_2787():
979
+ n, k = symbols('n k', positive=True, integer=True)
980
+ p = symbols('p', positive=True)
981
+ binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
982
+ s = Sum(binomial_dist*k, (k, 0, n))
983
+ res = s.doit().simplify()
984
+ ans = Piecewise(
985
+ (n*p, x),
986
+ (Sum(k*p**k*binomial(n, k)*(1 - p)**(n - k), (k, 0, n)),
987
+ True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
988
+ ans2 = Piecewise(
989
+ (n*p, x),
990
+ (factorial(n)*Sum(p**k*(1 - p)**(-k + n)/
991
+ (factorial(-k + n)*factorial(k - 1)), (k, 0, n)),
992
+ True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
993
+ assert res in [ans, ans2] # XXX system dependent
994
+ # Issue #17165: make sure that another simplify does not complicate
995
+ # the result by much. Why didn't first simplify replace
996
+ # Eq(n, 1) | (n > 1) with True?
997
+ assert res.simplify().count_ops() <= res.count_ops() + 2
998
+
999
+
1000
+ def test_issue_4668():
1001
+ assert summation(1/n, (n, 2, oo)) is oo
1002
+
1003
+
1004
+ def test_matrix_sum():
1005
+ A = Matrix([[0, 1], [n, 0]])
1006
+
1007
+ result = Sum(A, (n, 0, 3)).doit()
1008
+ assert result == Matrix([[0, 4], [6, 0]])
1009
+ assert result.__class__ == ImmutableDenseMatrix
1010
+
1011
+ A = SparseMatrix([[0, 1], [n, 0]])
1012
+
1013
+ result = Sum(A, (n, 0, 3)).doit()
1014
+ assert result.__class__ == ImmutableSparseMatrix
1015
+
1016
+
1017
+ def test_failing_matrix_sum():
1018
+ n = Symbol('n')
1019
+ # TODO Implement matrix geometric series summation.
1020
+ A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]])
1021
+ assert Sum(A ** n, (n, 1, 4)).doit() == \
1022
+ Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
1023
+ # issue sympy/sympy#16989
1024
+ assert summation(A**n, (n, 1, 1)) == A
1025
+
1026
+
1027
+ def test_indexed_idx_sum():
1028
+ i = symbols('i', cls=Idx)
1029
+ r = Indexed('r', i)
1030
+ assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)])
1031
+ assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)])
1032
+
1033
+ j = symbols('j', integer=True)
1034
+ assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)])
1035
+ assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)])
1036
+
1037
+ k = Idx('k', range=(1, 3))
1038
+ A = IndexedBase('A')
1039
+ assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)])
1040
+ assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)])
1041
+
1042
+ raises(ValueError, lambda: Sum(A[k], (k, 1, 4)))
1043
+ raises(ValueError, lambda: Sum(A[k], (k, 0, 3)))
1044
+ raises(ValueError, lambda: Sum(A[k], (k, 2, oo)))
1045
+
1046
+ raises(ValueError, lambda: Product(A[k], (k, 1, 4)))
1047
+ raises(ValueError, lambda: Product(A[k], (k, 0, 3)))
1048
+ raises(ValueError, lambda: Product(A[k], (k, 2, oo)))
1049
+
1050
+
1051
+ @slow
1052
+ def test_is_convergent():
1053
+ # divergence tests --
1054
+ assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false
1055
+ assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false
1056
+ assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false
1057
+ assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false
1058
+ assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false
1059
+ assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false
1060
+
1061
+ # Raabe's test --
1062
+ assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true
1063
+
1064
+ # root test --
1065
+ assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false
1066
+
1067
+ # integral test --
1068
+
1069
+ # p-series test --
1070
+ assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true
1071
+ assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true
1072
+ assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true
1073
+ assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false
1074
+ assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true
1075
+ assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true
1076
+ assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false
1077
+
1078
+ # comparison test --
1079
+ assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false
1080
+ assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
1081
+ assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false
1082
+ assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true
1083
+ assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true
1084
+ assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true
1085
+ assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false
1086
+ assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false
1087
+ assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
1088
+ assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false
1089
+ assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true
1090
+ assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true
1091
+
1092
+ # alternating series tests --
1093
+ assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true
1094
+
1095
+ # with -negativeInfinite Limits
1096
+ assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true
1097
+ assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false
1098
+ assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true
1099
+ assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true
1100
+ assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true
1101
+
1102
+ # piecewise functions
1103
+ f = Piecewise((n**(-2), n <= 1), (n**2, n > 1))
1104
+ assert Sum(f, (n, 1, oo)).is_convergent() is S.false
1105
+ assert Sum(f, (n, -oo, oo)).is_convergent() is S.false
1106
+ assert Sum(f, (n, 1, 100)).is_convergent() is S.true
1107
+ #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true
1108
+
1109
+ # integral test
1110
+
1111
+ assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
1112
+ assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
1113
+ # the following function has maxima located at (x, y) =
1114
+ # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050)
1115
+ eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x)
1116
+ assert Sum(eq, (x, 1, oo)).is_convergent() is S.true
1117
+ assert Sum(eq, (x, 1, 2)).is_convergent() is S.true
1118
+ assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true
1119
+ assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false
1120
+
1121
+ # issue 19545
1122
+ assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true
1123
+
1124
+ # issue 19836
1125
+ assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true
1126
+
1127
+
1128
+ def test_is_absolutely_convergent():
1129
+ assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false
1130
+ assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true
1131
+
1132
+
1133
+ @XFAIL
1134
+ def test_convergent_failing():
1135
+ # dirichlet tests
1136
+ assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true
1137
+ assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true
1138
+
1139
+
1140
+ def test_issue_6966():
1141
+ i, k, m = symbols('i k m', integer=True)
1142
+ z_i, q_i = symbols('z_i q_i')
1143
+ a_k = Sum(-q_i*z_i/k,(i,1,m))
1144
+ b_k = a_k.diff(z_i)
1145
+ assert isinstance(b_k, Sum)
1146
+ assert b_k == Sum(-q_i/k,(i,1,m))
1147
+
1148
+
1149
+ def test_issue_10156():
1150
+ cx = Sum(2*y**2*x, (x, 1,3))
1151
+ e = 2*y*Sum(2*cx*x**2, (x, 1, 9))
1152
+ assert e.factor() == \
1153
+ 8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9))
1154
+
1155
+
1156
+ def test_issue_10973():
1157
+ assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true
1158
+
1159
+
1160
+ def test_issue_14129():
1161
+ x = Symbol('x', zero=False)
1162
+ assert Sum( k*x**k, (k, 0, n-1)).doit() == \
1163
+ Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n -
1164
+ n*x**n - x*x**n + x)/(x - 1)**2, True))
1165
+ assert Sum( x**k, (k, 0, n-1)).doit() == \
1166
+ Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True))
1167
+ assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \
1168
+ Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))),
1169
+ (x*(y + 1)*(n*x*y*(x + x/y)**(n - 1) +
1170
+ n*x*(x + x/y)**(n - 1) - n*y*(x + x/y)**(n - 1) -
1171
+ x*y*(x + x/y)**(n - 1) - x*(x + x/y)**(n - 1) + y)/
1172
+ (x*y + x - y)**2, True))
1173
+
1174
+
1175
+ def test_issue_14112():
1176
+ assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false
1177
+ assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false
1178
+ assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false
1179
+
1180
+
1181
+ def test_issue_14219():
1182
+ A = diag(0, 2, -3)
1183
+ res = diag(1, 15, -20)
1184
+ assert Sum(A**n, (n, 0, 3)).doit() == res
1185
+
1186
+
1187
+ def test_sin_times_absolutely_convergent():
1188
+ assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true
1189
+ assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
1190
+
1191
+
1192
+ def test_issue_14111():
1193
+ assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false
1194
+
1195
+
1196
+ def test_issue_14484():
1197
+ assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false
1198
+
1199
+
1200
+ def test_issue_14640():
1201
+ i, n = symbols("i n", integer=True)
1202
+ a, b, c = symbols("a b c", zero=False)
1203
+
1204
+ assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum(
1205
+ 1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise(
1206
+ (n + 1, Eq(1/a, 1)),
1207
+ ((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b)
1208
+
1209
+ assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise(
1210
+ (n + 1, Eq(a**(-2), 1)),
1211
+ ((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2
1212
+
1213
+ s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit()
1214
+ assert not s.has(Sum)
1215
+ assert s.subs({a: 2, b: 3, n: 5}) == 122
1216
+
1217
+
1218
+ def test_issue_15943():
1219
+ s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma)
1220
+ assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2
1221
+ ) + E*gamma(n + 1)
1222
+ assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1))
1223
+
1224
+
1225
+ def test_Sum_dummy_eq():
1226
+ assert not Sum(x, (x, a, b)).dummy_eq(1)
1227
+ assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2)))
1228
+ assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c)))
1229
+ assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b)))
1230
+ d = Dummy()
1231
+ assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c)
1232
+ assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)))
1233
+ assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c)))
1234
+ assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c)
1235
+ assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)))
1236
+
1237
+
1238
+ def test_issue_15852():
1239
+ assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo))
1240
+
1241
+
1242
+ def test_exceptions():
1243
+ S = Sum(x, (x, a, b))
1244
+ raises(ValueError, lambda: S.change_index(x, x**2, y))
1245
+ S = Sum(x, (x, a, b), (x, 1, 4))
1246
+ raises(ValueError, lambda: S.index(x))
1247
+ S = Sum(x, (x, a, b), (y, 1, 4))
1248
+ raises(ValueError, lambda: S.reorder([x]))
1249
+ S = Sum(x, (x, y, b), (y, 1, 4))
1250
+ raises(ReorderError, lambda: S.reorder_limit(0, 1))
1251
+ S = Sum(x*y, (x, a, b), (y, 1, 4))
1252
+ raises(NotImplementedError, lambda: S.is_convergent())
1253
+
1254
+
1255
+ def test_sumproducts_assumptions():
1256
+ M = Symbol('M', integer=True, positive=True)
1257
+
1258
+ m = Symbol('m', integer=True)
1259
+ for func in [Sum, Product]:
1260
+ assert func(m, (m, -M, M)).is_positive is None
1261
+ assert func(m, (m, -M, M)).is_nonpositive is None
1262
+ assert func(m, (m, -M, M)).is_negative is None
1263
+ assert func(m, (m, -M, M)).is_nonnegative is None
1264
+ assert func(m, (m, -M, M)).is_finite is True
1265
+
1266
+ m = Symbol('m', integer=True, nonnegative=True)
1267
+ for func in [Sum, Product]:
1268
+ assert func(m, (m, 0, M)).is_positive is None
1269
+ assert func(m, (m, 0, M)).is_nonpositive is None
1270
+ assert func(m, (m, 0, M)).is_negative is False
1271
+ assert func(m, (m, 0, M)).is_nonnegative is True
1272
+ assert func(m, (m, 0, M)).is_finite is True
1273
+
1274
+ m = Symbol('m', integer=True, positive=True)
1275
+ for func in [Sum, Product]:
1276
+ assert func(m, (m, 1, M)).is_positive is True
1277
+ assert func(m, (m, 1, M)).is_nonpositive is False
1278
+ assert func(m, (m, 1, M)).is_negative is False
1279
+ assert func(m, (m, 1, M)).is_nonnegative is True
1280
+ assert func(m, (m, 1, M)).is_finite is True
1281
+
1282
+ m = Symbol('m', integer=True, negative=True)
1283
+ assert Sum(m, (m, -M, -1)).is_positive is False
1284
+ assert Sum(m, (m, -M, -1)).is_nonpositive is True
1285
+ assert Sum(m, (m, -M, -1)).is_negative is True
1286
+ assert Sum(m, (m, -M, -1)).is_nonnegative is False
1287
+ assert Sum(m, (m, -M, -1)).is_finite is True
1288
+ assert Product(m, (m, -M, -1)).is_positive is None
1289
+ assert Product(m, (m, -M, -1)).is_nonpositive is None
1290
+ assert Product(m, (m, -M, -1)).is_negative is None
1291
+ assert Product(m, (m, -M, -1)).is_nonnegative is None
1292
+ assert Product(m, (m, -M, -1)).is_finite is True
1293
+
1294
+ m = Symbol('m', integer=True, nonpositive=True)
1295
+ assert Sum(m, (m, -M, 0)).is_positive is False
1296
+ assert Sum(m, (m, -M, 0)).is_nonpositive is True
1297
+ assert Sum(m, (m, -M, 0)).is_negative is None
1298
+ assert Sum(m, (m, -M, 0)).is_nonnegative is None
1299
+ assert Sum(m, (m, -M, 0)).is_finite is True
1300
+ assert Product(m, (m, -M, 0)).is_positive is None
1301
+ assert Product(m, (m, -M, 0)).is_nonpositive is None
1302
+ assert Product(m, (m, -M, 0)).is_negative is None
1303
+ assert Product(m, (m, -M, 0)).is_nonnegative is None
1304
+ assert Product(m, (m, -M, 0)).is_finite is True
1305
+
1306
+ m = Symbol('m', integer=True)
1307
+ assert Sum(2, (m, 0, oo)).is_positive is None
1308
+ assert Sum(2, (m, 0, oo)).is_nonpositive is None
1309
+ assert Sum(2, (m, 0, oo)).is_negative is None
1310
+ assert Sum(2, (m, 0, oo)).is_nonnegative is None
1311
+ assert Sum(2, (m, 0, oo)).is_finite is None
1312
+
1313
+ assert Product(2, (m, 0, oo)).is_positive is None
1314
+ assert Product(2, (m, 0, oo)).is_nonpositive is None
1315
+ assert Product(2, (m, 0, oo)).is_negative is False
1316
+ assert Product(2, (m, 0, oo)).is_nonnegative is None
1317
+ assert Product(2, (m, 0, oo)).is_finite is None
1318
+
1319
+ assert Product(0, (x, M, M-1)).is_positive is True
1320
+ assert Product(0, (x, M, M-1)).is_finite is True
1321
+
1322
+
1323
+ def test_expand_with_assumptions():
1324
+ M = Symbol('M', integer=True, positive=True)
1325
+ x = Symbol('x', positive=True)
1326
+ m = Symbol('m', nonnegative=True)
1327
+ assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M))
1328
+ assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M))
1329
+ assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M))
1330
+ assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M))
1331
+
1332
+ n = Symbol('n', nonnegative=True)
1333
+ i, j = symbols('i,j', positive=True, integer=True)
1334
+ x, y = symbols('x,y', positive=True)
1335
+ assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \
1336
+ == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
1337
+
1338
+ m = Symbol('m', nonnegative=True, integer=True)
1339
+ s = Sum(x**m, (m, 0, M))
1340
+ s_as_product = s.rewrite(Product)
1341
+ assert s_as_product.has(Product)
1342
+ assert s_as_product == log(Product(exp(x**m), (m, 0, M)))
1343
+ assert s_as_product.expand() == s
1344
+ s5 = s.subs(M, 5)
1345
+ s5_as_product = s5.rewrite(Product)
1346
+ assert s5_as_product.has(Product)
1347
+ assert s5_as_product.doit().expand() == s5.doit()
1348
+
1349
+
1350
+ def test_has_finite_limits():
1351
+ x = Symbol('x')
1352
+ assert Sum(1, (x, 1, 9)).has_finite_limits is True
1353
+ assert Sum(1, (x, 1, oo)).has_finite_limits is False
1354
+ M = Symbol('M')
1355
+ assert Sum(1, (x, 1, M)).has_finite_limits is None
1356
+ M = Symbol('M', positive=True)
1357
+ assert Sum(1, (x, 1, M)).has_finite_limits is True
1358
+ x = Symbol('x', positive=True)
1359
+ M = Symbol('M')
1360
+ assert Sum(1, (x, 1, M)).has_finite_limits is True
1361
+
1362
+ assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False
1363
+
1364
+ def test_has_reversed_limits():
1365
+ assert Sum(1, (x, 1, 1)).has_reversed_limits is False
1366
+ assert Sum(1, (x, 1, 9)).has_reversed_limits is False
1367
+ assert Sum(1, (x, 1, -9)).has_reversed_limits is True
1368
+ assert Sum(1, (x, 1, 0)).has_reversed_limits is True
1369
+ assert Sum(1, (x, 1, oo)).has_reversed_limits is False
1370
+ M = Symbol('M')
1371
+ assert Sum(1, (x, 1, M)).has_reversed_limits is None
1372
+ M = Symbol('M', positive=True, integer=True)
1373
+ assert Sum(1, (x, 1, M)).has_reversed_limits is False
1374
+ assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False
1375
+ M = Symbol('M', negative=True)
1376
+ assert Sum(1, (x, 1, M)).has_reversed_limits is True
1377
+
1378
+ assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True
1379
+ assert Sum(1, (x, oo, oo)).has_reversed_limits is None
1380
+
1381
+
1382
+ def test_has_empty_sequence():
1383
+ assert Sum(1, (x, 1, 1)).has_empty_sequence is False
1384
+ assert Sum(1, (x, 1, 9)).has_empty_sequence is False
1385
+ assert Sum(1, (x, 1, -9)).has_empty_sequence is False
1386
+ assert Sum(1, (x, 1, 0)).has_empty_sequence is True
1387
+ assert Sum(1, (x, y, y - 1)).has_empty_sequence is True
1388
+ assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True
1389
+ assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True
1390
+ assert Sum(1, (x, oo, oo)).has_empty_sequence is False
1391
+
1392
+
1393
+ def test_empty_sequence():
1394
+ assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1
1395
+ assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1
1396
+ assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0
1397
+ assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0
1398
+
1399
+
1400
+ def test_issue_8016():
1401
+ k = Symbol('k', integer=True)
1402
+ n, m = symbols('n, m', integer=True, positive=True)
1403
+ s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n))
1404
+ assert s.doit().simplify() == \
1405
+ cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1)
1406
+
1407
+
1408
+ def test_issue_14313():
1409
+ assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent()
1410
+
1411
+
1412
+ def test_issue_14563():
1413
+ # The assertion was failing due to no assumptions methods in Sums and Product
1414
+ assert 1 % Sum(1, (x, 0, 1)) == 1
1415
+
1416
+
1417
+ def test_issue_16735():
1418
+ assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true
1419
+
1420
+
1421
+ def test_issue_14871():
1422
+ assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1
1423
+
1424
+
1425
+ def test_issue_17165():
1426
+ n = symbols("n", integer=True)
1427
+ x = symbols('x')
1428
+ s = (x*Sum(x**n, (n, -1, oo)))
1429
+ ssimp = s.doit().simplify()
1430
+
1431
+ assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)),
1432
+ (x*Sum(x**n, (n, -1, oo)), True)), ssimp
1433
+ assert ssimp.simplify() == ssimp
1434
+
1435
+
1436
+ def test_issue_19379():
1437
+ assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true
1438
+
1439
+
1440
+ def test_issue_20777():
1441
+ assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m))
1442
+
1443
+
1444
+ def test__dummy_with_inherited_properties_concrete():
1445
+ x = Symbol('x')
1446
+
1447
+ from sympy.core.containers import Tuple
1448
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5))
1449
+ assert d.is_real
1450
+ assert d.is_integer
1451
+ assert d.is_nonnegative
1452
+ assert d.is_extended_nonnegative
1453
+
1454
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9))
1455
+ assert d.is_real
1456
+ assert d.is_integer
1457
+ assert d.is_positive
1458
+ assert d.is_odd is None
1459
+
1460
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5))
1461
+ assert d.is_real
1462
+ assert d.is_integer
1463
+ assert d.is_positive is None
1464
+ assert d.is_extended_nonnegative is None
1465
+ assert d.is_odd is None
1466
+
1467
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5))
1468
+ assert d.is_real
1469
+ assert d.is_integer is None
1470
+ assert d.is_positive is None
1471
+ assert d.is_extended_nonnegative is None
1472
+
1473
+ N = Symbol('N', integer=True, positive=True)
1474
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N))
1475
+ assert d.is_real
1476
+ assert d.is_positive
1477
+ assert d.is_integer
1478
+
1479
+ # Return None if no assumptions are added
1480
+ N = Symbol('N', integer=True, positive=True)
1481
+ d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4))
1482
+ assert d is None
1483
+
1484
+ x = Symbol('x', negative=True)
1485
+ raises(InconsistentAssumptions,
1486
+ lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5)))
1487
+
1488
+
1489
+ def test_matrixsymbol_summation_numerical_limits():
1490
+ A = MatrixSymbol('A', 3, 3)
1491
+ n = Symbol('n', integer=True)
1492
+
1493
+ assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2
1494
+ assert Sum(A, (n, 0, 2)).doit() == 3*A
1495
+ assert Sum(n*A, (n, 0, 2)).doit() == 3*A
1496
+
1497
+ B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]])
1498
+ ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A
1499
+ assert Sum(A+B, (n, 0, 3)).doit() == ans
1500
+ ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]])
1501
+ assert Sum(A*B, (n, 0, 3)).doit() == ans
1502
+
1503
+ ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) +
1504
+ A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) +
1505
+ A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]]))
1506
+ assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans
1507
+
1508
+
1509
+ def test_issue_21651():
1510
+ i = Symbol('i')
1511
+ a = Sum(floor(2*2**(-i)), (i, S.One, 2))
1512
+ assert a.doit() == S.One
1513
+
1514
+
1515
+ @XFAIL
1516
+ def test_matrixsymbol_summation_symbolic_limits():
1517
+ N = Symbol('N', integer=True, positive=True)
1518
+
1519
+ A = MatrixSymbol('A', 3, 3)
1520
+ n = Symbol('n', integer=True)
1521
+ assert Sum(A, (n, 0, N)).doit() == (N+1)*A
1522
+ assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A
1523
+
1524
+
1525
+ def test_summation_by_residues():
1526
+ x = Symbol('x')
1527
+
1528
+ # Examples from Nakhle H. Asmar, Loukas Grafakos,
1529
+ # Complex Analysis with Applications
1530
+ assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi)
1531
+ assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945
1532
+ assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi))
1533
+ assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
1534
+ (-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2)
1535
+ assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
1536
+ (-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2)
1537
+ assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0
1538
+ assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2
1539
+ assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8
1540
+ assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi)
1541
+ assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6
1542
+ assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90
1543
+ assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \
1544
+ -pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2
1545
+
1546
+ # Some examples made from 1 / (x**2 + 1)
1547
+ assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \
1548
+ S(1)/2 + pi/(2*tanh(pi))
1549
+ assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \
1550
+ -S(1)/2 + pi/(2*tanh(pi))
1551
+ assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \
1552
+ 1 + pi/(2*tanh(pi))
1553
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \
1554
+ pi/sinh(pi)
1555
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \
1556
+ pi/(2*sinh(pi)) + S(1)/2
1557
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \
1558
+ -S(1)/2 + pi/(2*sinh(pi))
1559
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \
1560
+ pi/(2*sinh(pi))
1561
+
1562
+ # Some examples made from shifting of 1 / (x**2 + 1)
1563
+ assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi))
1564
+ assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi))
1565
+ assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi))
1566
+ assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi))
1567
+ assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi))
1568
+ assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi))
1569
+
1570
+ # Some examples made from 1 / x**2
1571
+ assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6
1572
+ assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6
1573
+ assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12
1574
+ assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12
1575
+
1576
+
1577
+ @slow
1578
+ def test_summation_by_residues_failing():
1579
+ x = Symbol('x')
1580
+
1581
+ # Failing because of the bug in residue computation
1582
+ assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo))
1583
+ assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0
1584
+
1585
+
1586
+ def test_process_limits():
1587
+ from sympy.concrete.expr_with_limits import _process_limits
1588
+
1589
+ # these should be (x, Range(3)) not Range(3)
1590
+ raises(ValueError, lambda: _process_limits(
1591
+ Range(3), discrete=True))
1592
+ raises(ValueError, lambda: _process_limits(
1593
+ Range(3), discrete=False))
1594
+ # these should be (x, union) not union
1595
+ # (but then we would get a TypeError because we don't
1596
+ # handle non-contiguous sets: see below use of `union`)
1597
+ union = Or(x < 1, x > 3).as_set()
1598
+ raises(ValueError, lambda: _process_limits(
1599
+ union, discrete=True))
1600
+ raises(ValueError, lambda: _process_limits(
1601
+ union, discrete=False))
1602
+
1603
+ # error not triggered if not needed
1604
+ assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1)
1605
+
1606
+ # this equivalence is used to detect Reals in _process_limits
1607
+ assert isinstance(S.Reals, Interval)
1608
+
1609
+ C = Integral # continuous limits
1610
+ assert C(x, x >= 5) == C(x, (x, 5, oo))
1611
+ assert C(x, x < 3) == C(x, (x, -oo, 3))
1612
+ ans = C(x, (x, 0, 3))
1613
+ assert C(x, And(x >= 0, x < 3)) == ans
1614
+ assert C(x, (x, Interval.Ropen(0, 3))) == ans
1615
+ raises(TypeError, lambda: C(x, (x, Range(3))))
1616
+
1617
+ # discrete limits
1618
+ for D in (Sum, Product):
1619
+ r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3))
1620
+ assert D(x, (x, r)) == ans
1621
+ assert D(x, (x, r.reversed)) == ans
1622
+ r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo))
1623
+ assert D(x, (x, r)) == ans
1624
+ assert D(x, (x, r.reversed)) == ans
1625
+ r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo))
1626
+ assert D(x, (x, r)) == ans
1627
+ assert D(x, (x, r.reversed)) == ans
1628
+ raises(TypeError, lambda: D(x, x > 0))
1629
+ raises(ValueError, lambda: D(x, Interval(1, 3)))
1630
+ raises(NotImplementedError, lambda: D(x, (x, union)))
1631
+
1632
+
1633
+ def test_pr_22677():
1634
+ b = Symbol('b', integer=True, positive=True)
1635
+ assert Sum(1/x**2,(x, 0, b)).doit() == Sum(x**(-2), (x, 0, b))
1636
+ assert Sum(1/(x - b)**2,(x, 0, b-1)).doit() == Sum(
1637
+ (-b + x)**(-2), (x, 0, b - 1))
1638
+
1639
+
1640
+ def test_issue_23952():
1641
+ p, q = symbols("p q", real=True, nonnegative=True)
1642
+ k1, k2 = symbols("k1 k2", integer=True, nonnegative=True)
1643
+ n = Symbol("n", integer=True, positive=True)
1644
+ expr = Sum(abs(k1 - k2)*p**k1 *(1 - q)**(n - k2),
1645
+ (k1, 0, n), (k2, 0, n))
1646
+ assert expr.subs(p,0).subs(q,1).subs(n, 3).doit() == 3
venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.49 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/determinant.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrices.cpython-310.pyc ADDED
Binary file (70.7 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/__pycache__/repmatrix.cpython-310.pyc ADDED
Binary file (22 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/bench_matrix.cpython-310.pyc ADDED
Binary file (901 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Integer
2
+ from sympy.matrices.dense import (eye, zeros)
3
+
4
+ i3 = Integer(3)
5
+ M = eye(100)
6
+
7
+
8
+ def timeit_Matrix__getitem_ii():
9
+ M[3, 3]
10
+
11
+
12
+ def timeit_Matrix__getitem_II():
13
+ M[i3, i3]
14
+
15
+
16
+ def timeit_Matrix__getslice():
17
+ M[:, :]
18
+
19
+
20
+ def timeit_Matrix_zeronm():
21
+ zeros(100, 100)
venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (200 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_companion.cpython-310.pyc ADDED
Binary file (2.38 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_diagonal.cpython-310.pyc ADDED
Binary file (4.38 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_matmul.cpython-310.pyc ADDED
Binary file (8.06 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_special.cpython-310.pyc ADDED
Binary file (8.41 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_trace.cpython-310.pyc ADDED
Binary file (4.67 kB). View file
 
venv/lib/python3.10/site-packages/sympy/matrices/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/matrices/tests/test_graph.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics import Permutation
2
+ from sympy.core.symbol import symbols
3
+ from sympy.matrices import Matrix
4
+ from sympy.matrices.expressions import (
5
+ PermutationMatrix, BlockDiagMatrix, BlockMatrix)
6
+
7
+
8
+ def test_connected_components():
9
+ a, b, c, d, e, f, g, h, i, j, k, l, m = symbols('a:m')
10
+
11
+ M = Matrix([
12
+ [a, 0, 0, 0, b, 0, 0, 0, 0, 0, c, 0, 0],
13
+ [0, d, 0, 0, 0, e, 0, 0, 0, 0, 0, f, 0],
14
+ [0, 0, g, 0, 0, 0, h, 0, 0, 0, 0, 0, i],
15
+ [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
16
+ [m, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
17
+ [0, m, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
18
+ [0, 0, m, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
19
+ [j, 0, 0, 0, k, 0, 0, 1, 0, 0, l, 0, 0],
20
+ [0, j, 0, 0, 0, k, 0, 0, 1, 0, 0, l, 0],
21
+ [0, 0, j, 0, 0, 0, k, 0, 0, 1, 0, 0, l],
22
+ [0, 0, 0, 0, d, 0, 0, 0, 0, 0, 1, 0, 0],
23
+ [0, 0, 0, 0, 0, d, 0, 0, 0, 0, 0, 1, 0],
24
+ [0, 0, 0, 0, 0, 0, d, 0, 0, 0, 0, 0, 1]])
25
+ cc = M.connected_components()
26
+ assert cc == [[0, 4, 7, 10], [1, 5, 8, 11], [2, 6, 9, 12], [3]]
27
+
28
+ P, B = M.connected_components_decomposition()
29
+ p = Permutation([0, 4, 7, 10, 1, 5, 8, 11, 2, 6, 9, 12, 3])
30
+ assert P == PermutationMatrix(p)
31
+
32
+ B0 = Matrix([
33
+ [a, b, 0, c],
34
+ [m, 1, 0, 0],
35
+ [j, k, 1, l],
36
+ [0, d, 0, 1]])
37
+ B1 = Matrix([
38
+ [d, e, 0, f],
39
+ [m, 1, 0, 0],
40
+ [j, k, 1, l],
41
+ [0, d, 0, 1]])
42
+ B2 = Matrix([
43
+ [g, h, 0, i],
44
+ [m, 1, 0, 0],
45
+ [j, k, 1, l],
46
+ [0, d, 0, 1]])
47
+ B3 = Matrix([[1]])
48
+ assert B == BlockDiagMatrix(B0, B1, B2, B3)
49
+
50
+
51
+ def test_strongly_connected_components():
52
+ M = Matrix([
53
+ [11, 14, 10, 0, 15, 0],
54
+ [0, 44, 0, 0, 45, 0],
55
+ [1, 4, 0, 0, 5, 0],
56
+ [0, 0, 0, 22, 0, 23],
57
+ [0, 54, 0, 0, 55, 0],
58
+ [0, 0, 0, 32, 0, 33]])
59
+ scc = M.strongly_connected_components()
60
+ assert scc == [[1, 4], [0, 2], [3, 5]]
61
+
62
+ P, B = M.strongly_connected_components_decomposition()
63
+ p = Permutation([1, 4, 0, 2, 3, 5])
64
+ assert P == PermutationMatrix(p)
65
+ assert B == BlockMatrix([
66
+ [
67
+ Matrix([[44, 45], [54, 55]]),
68
+ Matrix.zeros(2, 2),
69
+ Matrix.zeros(2, 2)
70
+ ],
71
+ [
72
+ Matrix([[14, 15], [4, 5]]),
73
+ Matrix([[11, 10], [1, 0]]),
74
+ Matrix.zeros(2, 2)
75
+ ],
76
+ [
77
+ Matrix.zeros(2, 2),
78
+ Matrix.zeros(2, 2),
79
+ Matrix([[22, 23], [32, 33]])
80
+ ]
81
+ ])
82
+ P = P.as_explicit()
83
+ B = B.as_explicit()
84
+ assert P.T * B * P == M
85
+
86
+ P, B = M.strongly_connected_components_decomposition(lower=False)
87
+ p = Permutation([3, 5, 0, 2, 1, 4])
88
+ assert P == PermutationMatrix(p)
89
+ assert B == BlockMatrix([
90
+ [
91
+ Matrix([[22, 23], [32, 33]]),
92
+ Matrix.zeros(2, 2),
93
+ Matrix.zeros(2, 2)
94
+ ],
95
+ [
96
+ Matrix.zeros(2, 2),
97
+ Matrix([[11, 10], [1, 0]]),
98
+ Matrix([[14, 15], [4, 5]])
99
+ ],
100
+ [
101
+ Matrix.zeros(2, 2),
102
+ Matrix.zeros(2, 2),
103
+ Matrix([[44, 45], [54, 55]])
104
+ ]
105
+ ])
106
+ P = P.as_explicit()
107
+ B = B.as_explicit()
108
+ assert P.T * B * P == M
venv/lib/python3.10/site-packages/sympy/matrices/tests/test_matrices.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/sympy/matrices/tests/test_sparsetools.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.sparsetools import _doktocsr, _csrtodok, banded
2
+ from sympy.matrices.dense import (Matrix, eye, ones, zeros)
3
+ from sympy.matrices import SparseMatrix
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ def test_doktocsr():
8
+ a = SparseMatrix([[1, 2, 0, 0], [0, 3, 9, 0], [0, 1, 4, 0]])
9
+ b = SparseMatrix(4, 6, [10, 20, 0, 0, 0, 0, 0, 30, 0, 40, 0, 0, 0, 0, 50,
10
+ 60, 70, 0, 0, 0, 0, 0, 0, 80])
11
+ c = SparseMatrix(4, 4, [0, 0, 0, 0, 0, 12, 0, 2, 15, 0, 12, 0, 0, 0, 0, 4])
12
+ d = SparseMatrix(10, 10, {(1, 1): 12, (3, 5): 7, (7, 8): 12})
13
+ e = SparseMatrix([[0, 0, 0], [1, 0, 2], [3, 0, 0]])
14
+ f = SparseMatrix(7, 8, {(2, 3): 5, (4, 5):12})
15
+ assert _doktocsr(a) == [[1, 2, 3, 9, 1, 4], [0, 1, 1, 2, 1, 2],
16
+ [0, 2, 4, 6], [3, 4]]
17
+ assert _doktocsr(b) == [[10, 20, 30, 40, 50, 60, 70, 80],
18
+ [0, 1, 1, 3, 2, 3, 4, 5], [0, 2, 4, 7, 8], [4, 6]]
19
+ assert _doktocsr(c) == [[12, 2, 15, 12, 4], [1, 3, 0, 2, 3],
20
+ [0, 0, 2, 4, 5], [4, 4]]
21
+ assert _doktocsr(d) == [[12, 7, 12], [1, 5, 8],
22
+ [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3], [10, 10]]
23
+ assert _doktocsr(e) == [[1, 2, 3], [0, 2, 0], [0, 0, 2, 3], [3, 3]]
24
+ assert _doktocsr(f) == [[5, 12], [3, 5], [0, 0, 0, 1, 1, 2, 2, 2], [7, 8]]
25
+
26
+
27
+ def test_csrtodok():
28
+ h = [[5, 7, 5], [2, 1, 3], [0, 1, 1, 3], [3, 4]]
29
+ g = [[12, 5, 4], [2, 4, 2], [0, 1, 2, 3], [3, 7]]
30
+ i = [[1, 3, 12], [0, 2, 4], [0, 2, 3], [2, 5]]
31
+ j = [[11, 15, 12, 15], [2, 4, 1, 2], [0, 1, 1, 2, 3, 4], [5, 8]]
32
+ k = [[1, 3], [2, 1], [0, 1, 1, 2], [3, 3]]
33
+ m = _csrtodok(h)
34
+ assert isinstance(m, SparseMatrix)
35
+ assert m == SparseMatrix(3, 4,
36
+ {(0, 2): 5, (2, 1): 7, (2, 3): 5})
37
+ assert _csrtodok(g) == SparseMatrix(3, 7,
38
+ {(0, 2): 12, (1, 4): 5, (2, 2): 4})
39
+ assert _csrtodok(i) == SparseMatrix([[1, 0, 3, 0, 0], [0, 0, 0, 0, 12]])
40
+ assert _csrtodok(j) == SparseMatrix(5, 8,
41
+ {(0, 2): 11, (2, 4): 15, (3, 1): 12, (4, 2): 15})
42
+ assert _csrtodok(k) == SparseMatrix(3, 3, {(0, 2): 1, (2, 1): 3})
43
+
44
+
45
+ def test_banded():
46
+ raises(TypeError, lambda: banded())
47
+ raises(TypeError, lambda: banded(1))
48
+ raises(TypeError, lambda: banded(1, 2))
49
+ raises(TypeError, lambda: banded(1, 2, 3))
50
+ raises(TypeError, lambda: banded(1, 2, 3, 4))
51
+ raises(ValueError, lambda: banded({0: (1, 2)}, rows=1))
52
+ raises(ValueError, lambda: banded({0: (1, 2)}, cols=1))
53
+ raises(ValueError, lambda: banded(1, {0: (1, 2)}))
54
+ raises(ValueError, lambda: banded(2, 1, {0: (1, 2)}))
55
+ raises(ValueError, lambda: banded(1, 2, {0: (1, 2)}))
56
+
57
+ assert isinstance(banded(2, 4, {}), SparseMatrix)
58
+ assert banded(2, 4, {}) == zeros(2, 4)
59
+ assert banded({0: 0, 1: 0}) == zeros(0)
60
+ assert banded({0: Matrix([1, 2])}) == Matrix([1, 2])
61
+ assert banded({1: [1, 2, 3, 0], -1: [4, 5, 6]}) == \
62
+ banded({1: (1, 2, 3), -1: (4, 5, 6)}) == \
63
+ Matrix([
64
+ [0, 1, 0, 0],
65
+ [4, 0, 2, 0],
66
+ [0, 5, 0, 3],
67
+ [0, 0, 6, 0]])
68
+ assert banded(3, 4, {-1: 1, 0: 2, 1: 3}) == \
69
+ Matrix([
70
+ [2, 3, 0, 0],
71
+ [1, 2, 3, 0],
72
+ [0, 1, 2, 3]])
73
+ s = lambda d: (1 + d)**2
74
+ assert banded(5, {0: s, 2: s}) == \
75
+ Matrix([
76
+ [1, 0, 1, 0, 0],
77
+ [0, 4, 0, 4, 0],
78
+ [0, 0, 9, 0, 9],
79
+ [0, 0, 0, 16, 0],
80
+ [0, 0, 0, 0, 25]])
81
+ assert banded(2, {0: 1}) == \
82
+ Matrix([
83
+ [1, 0],
84
+ [0, 1]])
85
+ assert banded(2, 3, {0: 1}) == \
86
+ Matrix([
87
+ [1, 0, 0],
88
+ [0, 1, 0]])
89
+ vert = Matrix([1, 2, 3])
90
+ assert banded({0: vert}, cols=3) == \
91
+ Matrix([
92
+ [1, 0, 0],
93
+ [2, 1, 0],
94
+ [3, 2, 1],
95
+ [0, 3, 2],
96
+ [0, 0, 3]])
97
+ assert banded(4, {0: ones(2)}) == \
98
+ Matrix([
99
+ [1, 1, 0, 0],
100
+ [1, 1, 0, 0],
101
+ [0, 0, 1, 1],
102
+ [0, 0, 1, 1]])
103
+ raises(ValueError, lambda: banded({0: 2, 1: ones(2)}, rows=5))
104
+ assert banded({0: 2, 2: (ones(2),)*3}) == \
105
+ Matrix([
106
+ [2, 0, 1, 1, 0, 0, 0, 0],
107
+ [0, 2, 1, 1, 0, 0, 0, 0],
108
+ [0, 0, 2, 0, 1, 1, 0, 0],
109
+ [0, 0, 0, 2, 1, 1, 0, 0],
110
+ [0, 0, 0, 0, 2, 0, 1, 1],
111
+ [0, 0, 0, 0, 0, 2, 1, 1]])
112
+ raises(ValueError, lambda: banded({0: (2,)*5, 1: (ones(2),)*3}))
113
+ u2 = Matrix([[1, 1], [0, 1]])
114
+ assert banded({0: (2,)*5, 1: (u2,)*3}) == \
115
+ Matrix([
116
+ [2, 1, 1, 0, 0, 0, 0],
117
+ [0, 2, 1, 0, 0, 0, 0],
118
+ [0, 0, 2, 1, 1, 0, 0],
119
+ [0, 0, 0, 2, 1, 0, 0],
120
+ [0, 0, 0, 0, 2, 1, 1],
121
+ [0, 0, 0, 0, 0, 0, 1]])
122
+ assert banded({0:(0, ones(2)), 2: 2}) == \
123
+ Matrix([
124
+ [0, 0, 2],
125
+ [0, 1, 1],
126
+ [0, 1, 1]])
127
+ raises(ValueError, lambda: banded({0: (0, ones(2)), 1: 2}))
128
+ assert banded({0: 1}, cols=3) == banded({0: 1}, rows=3) == eye(3)
129
+ assert banded({1: 1}, rows=3) == Matrix([
130
+ [0, 1, 0],
131
+ [0, 0, 1],
132
+ [0, 0, 0]])
venv/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import dispatch
2
+ from .dispatcher import (Dispatcher, halt_ordering, restart_ordering,
3
+ MDNotImplementedError)
4
+
5
+ __version__ = '0.4.9'
6
+
7
+ __all__ = [
8
+ 'dispatch',
9
+
10
+ 'Dispatcher', 'halt_ordering', 'restart_ordering', 'MDNotImplementedError',
11
+ ]