applied-ai-018 commited on
Commit
7f9fcd6
·
verified ·
1 Parent(s): ee917cb

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_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/exp_avg.pt +3 -0
  4. ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  5. venv/lib/python3.10/site-packages/sympy/discrete/__init__.py +20 -0
  6. venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py +488 -0
  11. venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py +166 -0
  12. venv/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py +0 -0
  13. venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py +365 -0
  18. venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py +59 -0
  19. venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py +154 -0
  20. venv/lib/python3.10/site-packages/sympy/discrete/transforms.py +425 -0
  21. venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/sympy/holonomic/__init__.py +18 -0
  23. venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/sympy/holonomic/holonomic.py +2899 -0
  29. venv/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py +49 -0
  30. venv/lib/python3.10/site-packages/sympy/holonomic/numerical.py +109 -0
  31. venv/lib/python3.10/site-packages/sympy/holonomic/recurrence.py +365 -0
  32. venv/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py +0 -0
  33. venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py +830 -0
  37. venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py +29 -0
  38. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/setexpr.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py +0 -0
  47. venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4586809e8477531c1be667ed9f40288eae4f575c7b55deea0fe8d345feb3f76e
3
+ size 33555627
ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2392581b4eb4d1171c6475b42694faef618df8fc29305229fc81673dd2b0083
3
+ size 50332749
ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08708ef57b0072b691d4f8166bac6c0c0ae15dd6b88bda166f219b73053d5324
3
+ size 50332828
ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac2ec226fa03c790b2817a0f76128b0342851bc719449d17039b576a38fdec97
3
+ size 33555627
venv/lib/python3.10/site-packages/sympy/discrete/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module contains functions which operate on discrete sequences.
2
+
3
+ Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``,
4
+ ``mobius_transform``, ``inverse_mobius_transform``
5
+
6
+ Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``,
7
+ ``convolution_fwht``, ``convolution_subset``,
8
+ ``covering_product``, ``intersecting_product``
9
+ """
10
+
11
+ from .transforms import (fft, ifft, ntt, intt, fwht, ifwht,
12
+ mobius_transform, inverse_mobius_transform)
13
+ from .convolutions import convolution, covering_product, intersecting_product
14
+
15
+ __all__ = [
16
+ 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
17
+ 'inverse_mobius_transform',
18
+
19
+ 'convolution', 'covering_product', 'intersecting_product',
20
+ ]
venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (955 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc ADDED
Binary file (5.09 kB). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convolution (using **FFT**, **NTT**, **FWHT**), Subset Convolution,
3
+ Covering Product, Intersecting Product
4
+ """
5
+
6
+ from sympy.core import S, sympify
7
+ from sympy.core.function import expand_mul
8
+ from sympy.discrete.transforms import (
9
+ fft, ifft, ntt, intt, fwht, ifwht,
10
+ mobius_transform, inverse_mobius_transform)
11
+ from sympy.utilities.iterables import iterable
12
+ from sympy.utilities.misc import as_int
13
+
14
+
15
+ def convolution(a, b, cycle=0, dps=None, prime=None, dyadic=None, subset=None):
16
+ """
17
+ Performs convolution by determining the type of desired
18
+ convolution using hints.
19
+
20
+ Exactly one of ``dps``, ``prime``, ``dyadic``, ``subset`` arguments
21
+ should be specified explicitly for identifying the type of convolution,
22
+ and the argument ``cycle`` can be specified optionally.
23
+
24
+ For the default arguments, linear convolution is performed using **FFT**.
25
+
26
+ Parameters
27
+ ==========
28
+
29
+ a, b : iterables
30
+ The sequences for which convolution is performed.
31
+ cycle : Integer
32
+ Specifies the length for doing cyclic convolution.
33
+ dps : Integer
34
+ Specifies the number of decimal digits for precision for
35
+ performing **FFT** on the sequence.
36
+ prime : Integer
37
+ Prime modulus of the form `(m 2^k + 1)` to be used for
38
+ performing **NTT** on the sequence.
39
+ dyadic : bool
40
+ Identifies the convolution type as dyadic (*bitwise-XOR*)
41
+ convolution, which is performed using **FWHT**.
42
+ subset : bool
43
+ Identifies the convolution type as subset convolution.
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy import convolution, symbols, S, I
49
+ >>> u, v, w, x, y, z = symbols('u v w x y z')
50
+
51
+ >>> convolution([1 + 2*I, 4 + 3*I], [S(5)/4, 6], dps=3)
52
+ [1.25 + 2.5*I, 11.0 + 15.8*I, 24.0 + 18.0*I]
53
+ >>> convolution([1, 2, 3], [4, 5, 6], cycle=3)
54
+ [31, 31, 28]
55
+
56
+ >>> convolution([111, 777], [888, 444], prime=19*2**10 + 1)
57
+ [1283, 19351, 14219]
58
+ >>> convolution([111, 777], [888, 444], prime=19*2**10 + 1, cycle=2)
59
+ [15502, 19351]
60
+
61
+ >>> convolution([u, v], [x, y, z], dyadic=True)
62
+ [u*x + v*y, u*y + v*x, u*z, v*z]
63
+ >>> convolution([u, v], [x, y, z], dyadic=True, cycle=2)
64
+ [u*x + u*z + v*y, u*y + v*x + v*z]
65
+
66
+ >>> convolution([u, v, w], [x, y, z], subset=True)
67
+ [u*x, u*y + v*x, u*z + w*x, v*z + w*y]
68
+ >>> convolution([u, v, w], [x, y, z], subset=True, cycle=3)
69
+ [u*x + v*z + w*y, u*y + v*x, u*z + w*x]
70
+
71
+ """
72
+
73
+ c = as_int(cycle)
74
+ if c < 0:
75
+ raise ValueError("The length for cyclic convolution "
76
+ "must be non-negative")
77
+
78
+ dyadic = True if dyadic else None
79
+ subset = True if subset else None
80
+ if sum(x is not None for x in (prime, dps, dyadic, subset)) > 1:
81
+ raise TypeError("Ambiguity in determining the type of convolution")
82
+
83
+ if prime is not None:
84
+ ls = convolution_ntt(a, b, prime=prime)
85
+ return ls if not c else [sum(ls[i::c]) % prime for i in range(c)]
86
+
87
+ if dyadic:
88
+ ls = convolution_fwht(a, b)
89
+ elif subset:
90
+ ls = convolution_subset(a, b)
91
+ else:
92
+ ls = convolution_fft(a, b, dps=dps)
93
+
94
+ return ls if not c else [sum(ls[i::c]) for i in range(c)]
95
+
96
+
97
+ #----------------------------------------------------------------------------#
98
+ # #
99
+ # Convolution for Complex domain #
100
+ # #
101
+ #----------------------------------------------------------------------------#
102
+
103
+ def convolution_fft(a, b, dps=None):
104
+ """
105
+ Performs linear convolution using Fast Fourier Transform.
106
+
107
+ Parameters
108
+ ==========
109
+
110
+ a, b : iterables
111
+ The sequences for which convolution is performed.
112
+ dps : Integer
113
+ Specifies the number of decimal digits for precision.
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy import S, I
119
+ >>> from sympy.discrete.convolutions import convolution_fft
120
+
121
+ >>> convolution_fft([2, 3], [4, 5])
122
+ [8, 22, 15]
123
+ >>> convolution_fft([2, 5], [6, 7, 3])
124
+ [12, 44, 41, 15]
125
+ >>> convolution_fft([1 + 2*I, 4 + 3*I], [S(5)/4, 6])
126
+ [5/4 + 5*I/2, 11 + 63*I/4, 24 + 18*I]
127
+
128
+ References
129
+ ==========
130
+
131
+ .. [1] https://en.wikipedia.org/wiki/Convolution_theorem
132
+ .. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
133
+
134
+ """
135
+
136
+ a, b = a[:], b[:]
137
+ n = m = len(a) + len(b) - 1 # convolution size
138
+
139
+ if n > 0 and n&(n - 1): # not a power of 2
140
+ n = 2**n.bit_length()
141
+
142
+ # padding with zeros
143
+ a += [S.Zero]*(n - len(a))
144
+ b += [S.Zero]*(n - len(b))
145
+
146
+ a, b = fft(a, dps), fft(b, dps)
147
+ a = [expand_mul(x*y) for x, y in zip(a, b)]
148
+ a = ifft(a, dps)[:m]
149
+
150
+ return a
151
+
152
+
153
+ #----------------------------------------------------------------------------#
154
+ # #
155
+ # Convolution for GF(p) #
156
+ # #
157
+ #----------------------------------------------------------------------------#
158
+
159
+ def convolution_ntt(a, b, prime):
160
+ """
161
+ Performs linear convolution using Number Theoretic Transform.
162
+
163
+ Parameters
164
+ ==========
165
+
166
+ a, b : iterables
167
+ The sequences for which convolution is performed.
168
+ prime : Integer
169
+ Prime modulus of the form `(m 2^k + 1)` to be used for performing
170
+ **NTT** on the sequence.
171
+
172
+ Examples
173
+ ========
174
+
175
+ >>> from sympy.discrete.convolutions import convolution_ntt
176
+ >>> convolution_ntt([2, 3], [4, 5], prime=19*2**10 + 1)
177
+ [8, 22, 15]
178
+ >>> convolution_ntt([2, 5], [6, 7, 3], prime=19*2**10 + 1)
179
+ [12, 44, 41, 15]
180
+ >>> convolution_ntt([333, 555], [222, 666], prime=19*2**10 + 1)
181
+ [15555, 14219, 19404]
182
+
183
+ References
184
+ ==========
185
+
186
+ .. [1] https://en.wikipedia.org/wiki/Convolution_theorem
187
+ .. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
188
+
189
+ """
190
+
191
+ a, b, p = a[:], b[:], as_int(prime)
192
+ n = m = len(a) + len(b) - 1 # convolution size
193
+
194
+ if n > 0 and n&(n - 1): # not a power of 2
195
+ n = 2**n.bit_length()
196
+
197
+ # padding with zeros
198
+ a += [0]*(n - len(a))
199
+ b += [0]*(n - len(b))
200
+
201
+ a, b = ntt(a, p), ntt(b, p)
202
+ a = [x*y % p for x, y in zip(a, b)]
203
+ a = intt(a, p)[:m]
204
+
205
+ return a
206
+
207
+
208
+ #----------------------------------------------------------------------------#
209
+ # #
210
+ # Convolution for 2**n-group #
211
+ # #
212
+ #----------------------------------------------------------------------------#
213
+
214
+ def convolution_fwht(a, b):
215
+ """
216
+ Performs dyadic (*bitwise-XOR*) convolution using Fast Walsh Hadamard
217
+ Transform.
218
+
219
+ The convolution is automatically padded to the right with zeros, as the
220
+ *radix-2 FWHT* requires the number of sample points to be a power of 2.
221
+
222
+ Parameters
223
+ ==========
224
+
225
+ a, b : iterables
226
+ The sequences for which convolution is performed.
227
+
228
+ Examples
229
+ ========
230
+
231
+ >>> from sympy import symbols, S, I
232
+ >>> from sympy.discrete.convolutions import convolution_fwht
233
+
234
+ >>> u, v, x, y = symbols('u v x y')
235
+ >>> convolution_fwht([u, v], [x, y])
236
+ [u*x + v*y, u*y + v*x]
237
+
238
+ >>> convolution_fwht([2, 3], [4, 5])
239
+ [23, 22]
240
+ >>> convolution_fwht([2, 5 + 4*I, 7], [6*I, 7, 3 + 4*I])
241
+ [56 + 68*I, -10 + 30*I, 6 + 50*I, 48 + 32*I]
242
+
243
+ >>> convolution_fwht([S(33)/7, S(55)/6, S(7)/4], [S(2)/3, 5])
244
+ [2057/42, 1870/63, 7/6, 35/4]
245
+
246
+ References
247
+ ==========
248
+
249
+ .. [1] https://www.radioeng.cz/fulltexts/2002/02_03_40_42.pdf
250
+ .. [2] https://en.wikipedia.org/wiki/Hadamard_transform
251
+
252
+ """
253
+
254
+ if not a or not b:
255
+ return []
256
+
257
+ a, b = a[:], b[:]
258
+ n = max(len(a), len(b))
259
+
260
+ if n&(n - 1): # not a power of 2
261
+ n = 2**n.bit_length()
262
+
263
+ # padding with zeros
264
+ a += [S.Zero]*(n - len(a))
265
+ b += [S.Zero]*(n - len(b))
266
+
267
+ a, b = fwht(a), fwht(b)
268
+ a = [expand_mul(x*y) for x, y in zip(a, b)]
269
+ a = ifwht(a)
270
+
271
+ return a
272
+
273
+
274
+ #----------------------------------------------------------------------------#
275
+ # #
276
+ # Subset Convolution #
277
+ # #
278
+ #----------------------------------------------------------------------------#
279
+
280
+ def convolution_subset(a, b):
281
+ """
282
+ Performs Subset Convolution of given sequences.
283
+
284
+ The indices of each argument, considered as bit strings, correspond to
285
+ subsets of a finite set.
286
+
287
+ The sequence is automatically padded to the right with zeros, as the
288
+ definition of subset based on bitmasks (indices) requires the size of
289
+ sequence to be a power of 2.
290
+
291
+ Parameters
292
+ ==========
293
+
294
+ a, b : iterables
295
+ The sequences for which convolution is performed.
296
+
297
+ Examples
298
+ ========
299
+
300
+ >>> from sympy import symbols, S
301
+ >>> from sympy.discrete.convolutions import convolution_subset
302
+ >>> u, v, x, y, z = symbols('u v x y z')
303
+
304
+ >>> convolution_subset([u, v], [x, y])
305
+ [u*x, u*y + v*x]
306
+ >>> convolution_subset([u, v, x], [y, z])
307
+ [u*y, u*z + v*y, x*y, x*z]
308
+
309
+ >>> convolution_subset([1, S(2)/3], [3, 4])
310
+ [3, 6]
311
+ >>> convolution_subset([1, 3, S(5)/7], [7])
312
+ [7, 21, 5, 0]
313
+
314
+ References
315
+ ==========
316
+
317
+ .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
318
+
319
+ """
320
+
321
+ if not a or not b:
322
+ return []
323
+
324
+ if not iterable(a) or not iterable(b):
325
+ raise TypeError("Expected a sequence of coefficients for convolution")
326
+
327
+ a = [sympify(arg) for arg in a]
328
+ b = [sympify(arg) for arg in b]
329
+ n = max(len(a), len(b))
330
+
331
+ if n&(n - 1): # not a power of 2
332
+ n = 2**n.bit_length()
333
+
334
+ # padding with zeros
335
+ a += [S.Zero]*(n - len(a))
336
+ b += [S.Zero]*(n - len(b))
337
+
338
+ c = [S.Zero]*n
339
+
340
+ for mask in range(n):
341
+ smask = mask
342
+ while smask > 0:
343
+ c[mask] += expand_mul(a[smask] * b[mask^smask])
344
+ smask = (smask - 1)&mask
345
+
346
+ c[mask] += expand_mul(a[smask] * b[mask^smask])
347
+
348
+ return c
349
+
350
+
351
+ #----------------------------------------------------------------------------#
352
+ # #
353
+ # Covering Product #
354
+ # #
355
+ #----------------------------------------------------------------------------#
356
+
357
+ def covering_product(a, b):
358
+ """
359
+ Returns the covering product of given sequences.
360
+
361
+ The indices of each argument, considered as bit strings, correspond to
362
+ subsets of a finite set.
363
+
364
+ The covering product of given sequences is a sequence which contains
365
+ the sum of products of the elements of the given sequences grouped by
366
+ the *bitwise-OR* of the corresponding indices.
367
+
368
+ The sequence is automatically padded to the right with zeros, as the
369
+ definition of subset based on bitmasks (indices) requires the size of
370
+ sequence to be a power of 2.
371
+
372
+ Parameters
373
+ ==========
374
+
375
+ a, b : iterables
376
+ The sequences for which covering product is to be obtained.
377
+
378
+ Examples
379
+ ========
380
+
381
+ >>> from sympy import symbols, S, I, covering_product
382
+ >>> u, v, x, y, z = symbols('u v x y z')
383
+
384
+ >>> covering_product([u, v], [x, y])
385
+ [u*x, u*y + v*x + v*y]
386
+ >>> covering_product([u, v, x], [y, z])
387
+ [u*y, u*z + v*y + v*z, x*y, x*z]
388
+
389
+ >>> covering_product([1, S(2)/3], [3, 4 + 5*I])
390
+ [3, 26/3 + 25*I/3]
391
+ >>> covering_product([1, 3, S(5)/7], [7, 8])
392
+ [7, 53, 5, 40/7]
393
+
394
+ References
395
+ ==========
396
+
397
+ .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
398
+
399
+ """
400
+
401
+ if not a or not b:
402
+ return []
403
+
404
+ a, b = a[:], b[:]
405
+ n = max(len(a), len(b))
406
+
407
+ if n&(n - 1): # not a power of 2
408
+ n = 2**n.bit_length()
409
+
410
+ # padding with zeros
411
+ a += [S.Zero]*(n - len(a))
412
+ b += [S.Zero]*(n - len(b))
413
+
414
+ a, b = mobius_transform(a), mobius_transform(b)
415
+ a = [expand_mul(x*y) for x, y in zip(a, b)]
416
+ a = inverse_mobius_transform(a)
417
+
418
+ return a
419
+
420
+
421
+ #----------------------------------------------------------------------------#
422
+ # #
423
+ # Intersecting Product #
424
+ # #
425
+ #----------------------------------------------------------------------------#
426
+
427
+ def intersecting_product(a, b):
428
+ """
429
+ Returns the intersecting product of given sequences.
430
+
431
+ The indices of each argument, considered as bit strings, correspond to
432
+ subsets of a finite set.
433
+
434
+ The intersecting product of given sequences is the sequence which
435
+ contains the sum of products of the elements of the given sequences
436
+ grouped by the *bitwise-AND* of the corresponding indices.
437
+
438
+ The sequence is automatically padded to the right with zeros, as the
439
+ definition of subset based on bitmasks (indices) requires the size of
440
+ sequence to be a power of 2.
441
+
442
+ Parameters
443
+ ==========
444
+
445
+ a, b : iterables
446
+ The sequences for which intersecting product is to be obtained.
447
+
448
+ Examples
449
+ ========
450
+
451
+ >>> from sympy import symbols, S, I, intersecting_product
452
+ >>> u, v, x, y, z = symbols('u v x y z')
453
+
454
+ >>> intersecting_product([u, v], [x, y])
455
+ [u*x + u*y + v*x, v*y]
456
+ >>> intersecting_product([u, v, x], [y, z])
457
+ [u*y + u*z + v*y + x*y + x*z, v*z, 0, 0]
458
+
459
+ >>> intersecting_product([1, S(2)/3], [3, 4 + 5*I])
460
+ [9 + 5*I, 8/3 + 10*I/3]
461
+ >>> intersecting_product([1, 3, S(5)/7], [7, 8])
462
+ [327/7, 24, 0, 0]
463
+
464
+ References
465
+ ==========
466
+
467
+ .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
468
+
469
+ """
470
+
471
+ if not a or not b:
472
+ return []
473
+
474
+ a, b = a[:], b[:]
475
+ n = max(len(a), len(b))
476
+
477
+ if n&(n - 1): # not a power of 2
478
+ n = 2**n.bit_length()
479
+
480
+ # padding with zeros
481
+ a += [S.Zero]*(n - len(a))
482
+ b += [S.Zero]*(n - len(b))
483
+
484
+ a, b = mobius_transform(a, subset=False), mobius_transform(b, subset=False)
485
+ a = [expand_mul(x*y) for x, y in zip(a, b)]
486
+ a = inverse_mobius_transform(a, subset=False)
487
+
488
+ return a
venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Recurrences
3
+ """
4
+
5
+ from sympy.core import S, sympify
6
+ from sympy.utilities.iterables import iterable
7
+ from sympy.utilities.misc import as_int
8
+
9
+
10
+ def linrec(coeffs, init, n):
11
+ r"""
12
+ Evaluation of univariate linear recurrences of homogeneous type
13
+ having coefficients independent of the recurrence variable.
14
+
15
+ Parameters
16
+ ==========
17
+
18
+ coeffs : iterable
19
+ Coefficients of the recurrence
20
+ init : iterable
21
+ Initial values of the recurrence
22
+ n : Integer
23
+ Point of evaluation for the recurrence
24
+
25
+ Notes
26
+ =====
27
+
28
+ Let `y(n)` be the recurrence of given type, ``c`` be the sequence
29
+ of coefficients, ``b`` be the sequence of initial/base values of the
30
+ recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence.
31
+ Then,
32
+
33
+ .. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\
34
+ c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k
35
+ \end{cases}
36
+
37
+ Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation
38
+ that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is
39
+ replaced by the corresponding value `x_i`. The sequence is then a solution
40
+ of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where
41
+ `p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic
42
+ polynomial.
43
+
44
+ Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear
45
+ combination of powers `x^i`). Now, if `x^n` is congruent to
46
+ `g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then
47
+ `T(x^n) = x_n` is equal to
48
+ `T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`.
49
+
50
+ Computation of `x^n`,
51
+ given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
52
+ is performed using exponentiation by squaring (refer to [1_]) with
53
+ an additional reduction step performed to retain only first `k` powers
54
+ of `x` in the representation of `x^n`.
55
+
56
+ Examples
57
+ ========
58
+
59
+ >>> from sympy.discrete.recurrences import linrec
60
+ >>> from sympy.abc import x, y, z
61
+
62
+ >>> linrec(coeffs=[1, 1], init=[0, 1], n=10)
63
+ 55
64
+
65
+ >>> linrec(coeffs=[1, 1], init=[x, y], n=10)
66
+ 34*x + 55*y
67
+
68
+ >>> linrec(coeffs=[x, y], init=[0, 1], n=5)
69
+ x**2*y + x*(x**3 + 2*x*y) + y**2
70
+
71
+ >>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16)
72
+ 13576*x + 5676*y + 2356*z
73
+
74
+ References
75
+ ==========
76
+
77
+ .. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring
78
+ .. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation&section=6#Matrices
79
+
80
+ See Also
81
+ ========
82
+
83
+ sympy.polys.agca.extensions.ExtensionElement.__pow__
84
+
85
+ """
86
+
87
+ if not coeffs:
88
+ return S.Zero
89
+
90
+ if not iterable(coeffs):
91
+ raise TypeError("Expected a sequence of coefficients for"
92
+ " the recurrence")
93
+
94
+ if not iterable(init):
95
+ raise TypeError("Expected a sequence of values for the initialization"
96
+ " of the recurrence")
97
+
98
+ n = as_int(n)
99
+ if n < 0:
100
+ raise ValueError("Point of evaluation of recurrence must be a "
101
+ "non-negative integer")
102
+
103
+ c = [sympify(arg) for arg in coeffs]
104
+ b = [sympify(arg) for arg in init]
105
+ k = len(c)
106
+
107
+ if len(b) > k:
108
+ raise TypeError("Count of initial values should not exceed the "
109
+ "order of the recurrence")
110
+ else:
111
+ b += [S.Zero]*(k - len(b)) # remaining initial values default to zero
112
+
113
+ if n < k:
114
+ return b[n]
115
+ terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)]
116
+ return sum(terms[:-1], terms[-1])
117
+
118
+
119
+ def linrec_coeffs(c, n):
120
+ r"""
121
+ Compute the coefficients of n'th term in linear recursion
122
+ sequence defined by c.
123
+
124
+ `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`.
125
+
126
+ It computes the coefficients by using binary exponentiation.
127
+ This function is used by `linrec` and `_eval_pow_by_cayley`.
128
+
129
+ Parameters
130
+ ==========
131
+
132
+ c = coefficients of the divisor polynomial
133
+ n = exponent of x, so dividend is x^n
134
+
135
+ """
136
+
137
+ k = len(c)
138
+
139
+ def _square_and_reduce(u, offset):
140
+ # squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and
141
+ # multiplies by `x` if offset is 1) and reduces the above result of
142
+ # length upto `2k` to `k` using the characteristic equation of the
143
+ # recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
144
+
145
+ w = [S.Zero]*(2*len(u) - 1 + offset)
146
+ for i, p in enumerate(u):
147
+ for j, q in enumerate(u):
148
+ w[offset + i + j] += p*q
149
+
150
+ for j in range(len(w) - 1, k - 1, -1):
151
+ for i in range(k):
152
+ w[j - i - 1] += w[j]*c[i]
153
+
154
+ return w[:k]
155
+
156
+ def _final_coeffs(n):
157
+ # computes the final coefficient list - `cf` corresponding to the
158
+ # point at which recurrence is to be evalauted - `n`, such that,
159
+ # `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)`
160
+
161
+ if n < k:
162
+ return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1)
163
+ else:
164
+ return _square_and_reduce(_final_coeffs(n // 2), n % 2)
165
+
166
+ return _final_coeffs(n)
venv/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc ADDED
Binary file (3.45 kB). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc ADDED
Binary file (6.74 kB). View file
 
venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (E, Rational, pi)
2
+ from sympy.functions.elementary.exponential import exp
3
+ from sympy.functions.elementary.miscellaneous import sqrt
4
+ from sympy.core import S, symbols, I
5
+ from sympy.discrete.convolutions import (
6
+ convolution, convolution_fft, convolution_ntt, convolution_fwht,
7
+ convolution_subset, covering_product, intersecting_product)
8
+ from sympy.testing.pytest import raises
9
+ from sympy.abc import x, y
10
+
11
+ def test_convolution():
12
+ # fft
13
+ a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
14
+ b = [9, 5, 5, 4, 3, 2]
15
+ c = [3, 5, 3, 7, 8]
16
+ d = [1422, 6572, 3213, 5552]
17
+
18
+ assert convolution(a, b) == convolution_fft(a, b)
19
+ assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
20
+ assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
21
+ assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
22
+
23
+ # prime moduli of the form (m*2**k + 1), sequence length
24
+ # should be a divisor of 2**k
25
+ p = 7*17*2**23 + 1
26
+ q = 19*2**10 + 1
27
+
28
+ # ntt
29
+ assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
30
+ assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
31
+ assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
32
+ raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
33
+ raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
34
+
35
+ # fwht
36
+ assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
37
+ assert convolution(a, b, dyadic=False) == convolution(a, b)
38
+ raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
39
+ raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
40
+ raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
41
+ raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
42
+
43
+ # subset
44
+ assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
45
+ convolution(a, b, subset=True, dyadic=False) == \
46
+ convolution(a, b, subset=True)
47
+ assert convolution(a, b, subset=False) == convolution(a, b)
48
+ raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
49
+ raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
50
+ raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
51
+
52
+
53
+ def test_cyclic_convolution():
54
+ # fft
55
+ a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
56
+ b = [9, 5, 5, 4, 3, 2]
57
+
58
+ assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
59
+ convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
60
+ convolution([1, 2, 3], [4, 5, 6])
61
+
62
+ assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
63
+
64
+ a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
65
+ b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
66
+
67
+ assert convolution(a, b, cycle=0) == \
68
+ convolution(a, b, cycle=len(a) + len(b) - 1)
69
+
70
+ assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
71
+ Rational(11125, 4032), Rational(3653, 1080)]
72
+
73
+ assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
74
+ Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
75
+
76
+ assert convolution(a, b, cycle=9) == \
77
+ convolution(a, b, cycle=0) + [S.Zero]
78
+
79
+ # ntt
80
+ a = [2313, 5323532, S(3232), 42142, 42242421]
81
+ b = [S(33456), 56757, 45754, 432423]
82
+
83
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
84
+ convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
85
+ convolution(a, b, prime=19*2**10 + 1)
86
+
87
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
88
+ 15534, 3517]
89
+
90
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
91
+ 15534, 3517, 16314, 13688]
92
+
93
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
94
+ convolution(a, b, prime=19*2**10 + 1) + [0]
95
+
96
+ # fwht
97
+ u, v, w, x, y = symbols('u v w x y')
98
+ p, q, r, s, t = symbols('p q r s t')
99
+ c = [u, v, w, x, y]
100
+ d = [p, q, r, s, t]
101
+
102
+ assert convolution(a, b, dyadic=True, cycle=3) == \
103
+ [2499522285783, 19861417974796, 4702176579021]
104
+
105
+ assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
106
+ 2114320852171, 20571217906407, 246166418903, 1413262436976]
107
+
108
+ assert convolution(c, d, dyadic=True, cycle=4) == \
109
+ [p*u + p*y + q*v + r*w + s*x + t*u + t*y,
110
+ p*v + q*u + q*y + r*x + s*w + t*v,
111
+ p*w + q*x + r*u + r*y + s*v + t*w,
112
+ p*x + q*w + r*v + s*u + s*y + t*x]
113
+
114
+ assert convolution(c, d, dyadic=True, cycle=6) == \
115
+ [p*u + q*v + r*w + r*y + s*x + t*w + t*y,
116
+ p*v + q*u + r*x + s*w + s*y + t*x,
117
+ p*w + q*x + r*u + s*v,
118
+ p*x + q*w + r*v + s*u,
119
+ p*y + t*u,
120
+ q*y + t*v]
121
+
122
+ # subset
123
+ assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
124
+ 178235365533, 213958794, 246166418903, 1413262436976,
125
+ 2397553088697, 1932759730434]
126
+
127
+ assert convolution(a[1:], b, subset=True, cycle=4) == \
128
+ [178104086592, 302255835516, 244982785880, 3717819845434]
129
+
130
+ assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
131
+ 178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
132
+
133
+ assert convolution(c, d, subset=True, cycle=3) == \
134
+ [p*u + p*x + q*w + r*v + r*y + s*u + t*w,
135
+ p*v + p*y + q*u + s*y + t*u + t*x,
136
+ p*w + q*y + r*u + t*v]
137
+
138
+ assert convolution(c, d, subset=True, cycle=5) == \
139
+ [p*u + q*y + t*v,
140
+ p*v + q*u + r*y + t*w,
141
+ p*w + r*u + s*y + t*x,
142
+ p*x + q*w + r*v + s*u,
143
+ p*y + t*u]
144
+
145
+ raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
146
+
147
+
148
+ def test_convolution_fft():
149
+ assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
150
+ assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
151
+ assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
152
+ assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
153
+
154
+ assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
155
+ assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \
156
+ [Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175]
157
+
158
+ assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
159
+ [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
160
+
161
+ assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
162
+ [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
163
+
164
+ assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
165
+ [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
166
+ sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
167
+
168
+ assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
169
+ [12350041, 190918524, 374911166, 2362431729]
170
+
171
+ assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
172
+ [10037624576503, 1005370659728895, 9997492572392]
173
+
174
+ raises(TypeError, lambda: convolution_fft(x, y))
175
+ raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
176
+
177
+
178
+ def test_convolution_ntt():
179
+ # prime moduli of the form (m*2**k + 1), sequence length
180
+ # should be a divisor of 2**k
181
+ p = 7*17*2**23 + 1
182
+ q = 19*2**10 + 1
183
+ r = 2*500000003 + 1 # only for sequences of length 1 or 2
184
+ # s = 2*3*5*7 # composite modulus
185
+
186
+ assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
187
+ assert convolution_ntt([2], [3], r) == [6]
188
+ assert convolution_ntt([2, 3], [4], r) == [8, 12]
189
+
190
+ assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
191
+ 459741727, 79180879, 831885249, 381344700, 369993322]
192
+ assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
193
+ [8158, 3065, 3682, 7090, 1239, 2232, 3744]
194
+
195
+ assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
196
+ convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
197
+ assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
198
+ convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
199
+
200
+ raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
201
+ raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
202
+ raises(TypeError, lambda: convolution_ntt(x, y, p))
203
+
204
+
205
+ def test_convolution_fwht():
206
+ assert convolution_fwht([], []) == []
207
+ assert convolution_fwht([], [1]) == []
208
+ assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
209
+
210
+ assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
211
+ [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
212
+
213
+ a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
214
+ b = [94, 51, 53, 45, 31, 27, 13]
215
+ c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
216
+
217
+ assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
218
+ 45*sqrt(3) + Rational(5848, 15) + 135*I,
219
+ 94*sqrt(3) + Rational(1257, 5) + 65*I,
220
+ 51*sqrt(3) + Rational(3974, 15),
221
+ 13*sqrt(3) + 452 + 470*I,
222
+ Rational(4513, 15) + 255*I,
223
+ 31*sqrt(3) + Rational(1314, 5) + 265*I,
224
+ 27*sqrt(3) + Rational(3676, 15) + 225*I]
225
+
226
+ assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
227
+ Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
228
+ Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
229
+
230
+ assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5,
231
+ Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
232
+
233
+ u, v, w, x, y, z = symbols('u v w x y z')
234
+
235
+ assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
236
+
237
+ assert convolution_fwht([u, v, w], [x, y]) == \
238
+ [u*x + v*y, u*y + v*x, w*x, w*y]
239
+
240
+ assert convolution_fwht([u, v, w], [x, y, z]) == \
241
+ [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
242
+
243
+ raises(TypeError, lambda: convolution_fwht(x, y))
244
+ raises(TypeError, lambda: convolution_fwht(x*y, u + v))
245
+
246
+
247
+ def test_convolution_subset():
248
+ assert convolution_subset([], []) == []
249
+ assert convolution_subset([], [Rational(1, 3)]) == []
250
+ assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
251
+
252
+ a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
253
+ b = [64, 71, 55, 47, 33, 29, 15]
254
+ c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9]
255
+
256
+ assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
257
+ 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
258
+ 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
259
+
260
+ assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3,
261
+ 613 + I*110/3, Rational(5013, 5) + I*1249/3,
262
+ 675 + 22*I, 891 + I*751/3,
263
+ 771 + 10*I, Rational(3736, 5) + 105*I]
264
+
265
+ assert convolution_subset(a, c) == convolution_subset(c, a)
266
+ assert convolution_subset(a[:2], b) == \
267
+ [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
268
+
269
+ assert convolution_subset(a[:2], c) == \
270
+ [3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0]
271
+
272
+ u, v, w, x, y, z = symbols('u v w x y z')
273
+
274
+ assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
275
+ assert convolution_subset([u, v, w, x], [y, z]) == \
276
+ [u*y, u*z + v*y, w*y, w*z + x*y]
277
+
278
+ assert convolution_subset([u, v], [x, y, z]) == \
279
+ convolution_subset([x, y, z], [u, v])
280
+
281
+ raises(TypeError, lambda: convolution_subset(x, z))
282
+ raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
283
+
284
+
285
+ def test_covering_product():
286
+ assert covering_product([], []) == []
287
+ assert covering_product([], [Rational(1, 3)]) == []
288
+ assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
289
+
290
+ a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
291
+ b = [66, 81, 95, 49, 37, 89, 17]
292
+ c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91]
293
+
294
+ assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
295
+ 130*sqrt(7) + 1303 + 2619*I, 37,
296
+ Rational(671, 4), 17 + 54*sqrt(7),
297
+ 89*sqrt(7) + Rational(4661, 8) + 1287*I]
298
+
299
+ assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
300
+ 1412 + I*190/3, Rational(42684, 5) + I*31202/3,
301
+ 9484 + I*74/3, 22163 + I*27394/3,
302
+ 10621 + I*34/3, Rational(90236, 15) + 1224*I]
303
+
304
+ assert covering_product(a, c) == covering_product(c, a)
305
+ assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
306
+ 1412 + I*190/3, Rational(42684, 5) + I*31202/3,
307
+ 111 + I*74/3, 6693 + I*27394/3,
308
+ 429 + I*34/3, Rational(23351, 15) + 1224*I]
309
+
310
+ assert covering_product(a, c[:-1]) == [3 + I*2/3,
311
+ Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
312
+ -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15]
313
+
314
+ u, v, w, x, y, z = symbols('u v w x y z')
315
+
316
+ assert covering_product([u, v, w], [x, y]) == \
317
+ [u*x, u*y + v*x + v*y, w*x, w*y]
318
+
319
+ assert covering_product([u, v, w, x], [y, z]) == \
320
+ [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
321
+
322
+ assert covering_product([u, v], [x, y, z]) == \
323
+ covering_product([x, y, z], [u, v])
324
+
325
+ raises(TypeError, lambda: covering_product(x, z))
326
+ raises(TypeError, lambda: covering_product(Rational(7, 3), u))
327
+
328
+
329
+ def test_intersecting_product():
330
+ assert intersecting_product([], []) == []
331
+ assert intersecting_product([], [Rational(1, 3)]) == []
332
+ assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
333
+
334
+ a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
335
+ b = [67, 51, 65, 48, 36, 79, 27]
336
+ c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13]
337
+
338
+ assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
339
+ 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
340
+ 192 + 336*I, 0, 0, 0, 0]
341
+
342
+ assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5,
343
+ Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
344
+
345
+ assert intersecting_product(a, c) == intersecting_product(c, a)
346
+ assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5,
347
+ Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
348
+
349
+ assert intersecting_product(a, c[:-2]) == \
350
+ [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40,
351
+ -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
352
+
353
+ u, v, w, x, y, z = symbols('u v w x y z')
354
+
355
+ assert intersecting_product([u, v, w], [x, y]) == \
356
+ [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
357
+
358
+ assert intersecting_product([u, v, w, x], [y, z]) == \
359
+ [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
360
+
361
+ assert intersecting_product([u, v], [x, y, z]) == \
362
+ intersecting_product([x, y, z], [u, v])
363
+
364
+ raises(TypeError, lambda: intersecting_product(x, z))
365
+ raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.functions.combinatorial.numbers import fibonacci
3
+ from sympy.core import S, symbols
4
+ from sympy.testing.pytest import raises
5
+ from sympy.discrete.recurrences import linrec
6
+
7
+ def test_linrec():
8
+ assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946
9
+ assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040
10
+ assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384
11
+ assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165
12
+ assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \
13
+ 56889923441670659718376223533331214868804815612050381493741233489928913241
14
+ assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \
15
+ 702633573874937994980598979769135096432444135301118916539
16
+
17
+ assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4)
18
+ assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5)
19
+
20
+ assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n)
21
+ for n in range(95, 115))
22
+
23
+ assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1)
24
+ for n in range(595, 615))
25
+
26
+ a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)]
27
+ b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6]
28
+ x, y, z = symbols('x y z')
29
+
30
+ assert linrec(coeffs=a[:5], init=b[:4], n=80) == \
31
+ Rational(1726244235456268979436592226626304376013002142588105090705187189,
32
+ 1960143456748895967474334873705475211264)
33
+
34
+ assert linrec(coeffs=a[:4], init=b[:4], n=50) == \
35
+ Rational(368949940033050147080268092104304441, 504857282956046106624)
36
+
37
+ assert linrec(coeffs=a[3:], init=b[:3], n=35) == \
38
+ Rational(97409272177295731943657945116791049305244422833125109,
39
+ 814315512679031689453125)
40
+
41
+ assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \
42
+ Rational(26777668739896791448594650497024, 48084516708184142230517578125)
43
+
44
+ raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1))
45
+ raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000))
46
+ raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000))
47
+ raises(TypeError, lambda: linrec(x, b, n=10000))
48
+ raises(TypeError, lambda: linrec(a, y, n=10000))
49
+
50
+ assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \
51
+ x**2 + x*y + x*z + y + z
52
+ assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \
53
+ 269542*x + 664575*y + 578949*z
54
+ assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \
55
+ 58516436*x + 56372788*y
56
+ assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \
57
+ 11477135884896*x + 25999077948732*y + 41975630244216*z
58
+ assert linrec(coeffs=[], init=[1, 1], n=20) == 0
59
+ assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3
venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.functions.elementary.miscellaneous import sqrt
2
+ from sympy.core import S, Symbol, symbols, I, Rational
3
+ from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht,
4
+ mobius_transform, inverse_mobius_transform)
5
+ from sympy.testing.pytest import raises
6
+
7
+
8
+ def test_fft_ifft():
9
+ assert all(tf(ls) == ls for tf in (fft, ifft)
10
+ for ls in ([], [Rational(5, 3)]))
11
+
12
+ ls = list(range(6))
13
+ fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I,
14
+ -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3,
15
+ -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I,
16
+ 2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2]
17
+
18
+ assert fft(ls) == fls
19
+ assert ifft(fls) == ls + [S.Zero]*2
20
+
21
+ ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
22
+ ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4]
23
+
24
+ assert ifft(ls) == ifls
25
+ assert fft(ifls) == ls + [S.Zero]
26
+
27
+ x = Symbol('x', real=True)
28
+ raises(TypeError, lambda: fft(x))
29
+ raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3]))
30
+
31
+
32
+ def test_ntt_intt():
33
+ # prime moduli of the form (m*2**k + 1), sequence length
34
+ # should be a divisor of 2**k
35
+ p = 7*17*2**23 + 1
36
+ q = 2*500000003 + 1 # only for sequences of length 1 or 2
37
+ r = 2*3*5*7 # composite modulus
38
+
39
+ assert all(tf(ls, p) == ls for tf in (ntt, intt)
40
+ for ls in ([], [5]))
41
+
42
+ ls = list(range(6))
43
+ nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224,
44
+ 259751156, 12232587]
45
+
46
+ assert ntt(ls, p) == nls
47
+ assert intt(nls, p) == ls + [0]*2
48
+
49
+ ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
50
+ x = Symbol('x', integer=True)
51
+
52
+ raises(TypeError, lambda: ntt(x, p))
53
+ raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p))
54
+ raises(ValueError, lambda: intt(ls, p))
55
+ raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p))
56
+ raises(ValueError, lambda: ntt([3, 5, 6], q))
57
+ raises(ValueError, lambda: ntt([4, 5, 7], r))
58
+ raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p))
59
+
60
+
61
+ def test_fwht_ifwht():
62
+ assert all(tf(ls) == ls for tf in (fwht, ifwht) \
63
+ for ls in ([], [Rational(7, 4)]))
64
+
65
+ ls = [213, 321, 43235, 5325, 312, 53]
66
+ fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277]
67
+
68
+ assert fwht(ls) == fls
69
+ assert ifwht(fls) == ls + [S.Zero]*2
70
+
71
+ ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)]
72
+ ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I,
73
+ Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I]
74
+
75
+ assert ifwht(ls) == ifls
76
+ assert fwht(ifls) == ls + [S.Zero]*3
77
+
78
+ x, y = symbols('x y')
79
+
80
+ raises(TypeError, lambda: fwht(x))
81
+
82
+ ls = [x, 2*x, 3*x**2, 4*x**3]
83
+ ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4),
84
+ -x**3 + 3*x**2/4 - x/4,
85
+ -x**3 - 3*x**2/4 + x*Rational(3, 4),
86
+ x**3 - 3*x**2/4 - x/4]
87
+
88
+ assert ifwht(ls) == ifls
89
+ assert fwht(ifls) == ls
90
+
91
+ ls = [x, y, x**2, y**2, x*y]
92
+ fls = [x**2 + x*y + x + y**2 + y,
93
+ x**2 + x*y + x - y**2 - y,
94
+ -x**2 + x*y + x - y**2 + y,
95
+ -x**2 + x*y + x + y**2 - y,
96
+ x**2 - x*y + x + y**2 + y,
97
+ x**2 - x*y + x - y**2 - y,
98
+ -x**2 - x*y + x - y**2 + y,
99
+ -x**2 - x*y + x + y**2 - y]
100
+
101
+ assert fwht(ls) == fls
102
+ assert ifwht(fls) == ls + [S.Zero]*3
103
+
104
+ ls = list(range(6))
105
+
106
+ assert fwht(ls) == [x*8 for x in ifwht(ls)]
107
+
108
+
109
+ def test_mobius_transform():
110
+ assert all(tf(ls, subset=subset) == ls
111
+ for ls in ([], [Rational(7, 4)]) for subset in (True, False)
112
+ for tf in (mobius_transform, inverse_mobius_transform))
113
+
114
+ w, x, y, z = symbols('w x y z')
115
+
116
+ assert mobius_transform([x, y]) == [x, x + y]
117
+ assert inverse_mobius_transform([x, x + y]) == [x, y]
118
+ assert mobius_transform([x, y], subset=False) == [x + y, y]
119
+ assert inverse_mobius_transform([x + y, y], subset=False) == [x, y]
120
+
121
+ assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z]
122
+ assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \
123
+ [w, x, y, z]
124
+ assert mobius_transform([w, x, y, z], subset=False) == \
125
+ [w + x + y + z, x + z, y + z, z]
126
+ assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \
127
+ [w, x, y, z]
128
+
129
+ ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I]
130
+ mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168),
131
+ Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I,
132
+ Rational(2153, 168) + 7*I]
133
+
134
+ assert mobius_transform(ls) == mls
135
+ assert inverse_mobius_transform(mls) == ls + [S.Zero]*3
136
+
137
+ mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0]
138
+
139
+ assert mobius_transform(ls, subset=False) == mls
140
+ assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3
141
+
142
+ ls = ls[:-1]
143
+ mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)]
144
+
145
+ assert mobius_transform(ls) == mls
146
+ assert inverse_mobius_transform(mls) == ls
147
+
148
+ mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9]
149
+
150
+ assert mobius_transform(ls, subset=False) == mls
151
+ assert inverse_mobius_transform(mls, subset=False) == ls
152
+
153
+ raises(TypeError, lambda: mobius_transform(x, subset=True))
154
+ raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
venv/lib/python3.10/site-packages/sympy/discrete/transforms.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Discrete Fourier Transform, Number Theoretic Transform,
3
+ Walsh Hadamard Transform, Mobius Transform
4
+ """
5
+
6
+ from sympy.core import S, Symbol, sympify
7
+ from sympy.core.function import expand_mul
8
+ from sympy.core.numbers import pi, I
9
+ from sympy.functions.elementary.trigonometric import sin, cos
10
+ from sympy.ntheory import isprime, primitive_root
11
+ from sympy.utilities.iterables import ibin, iterable
12
+ from sympy.utilities.misc import as_int
13
+
14
+
15
+ #----------------------------------------------------------------------------#
16
+ # #
17
+ # Discrete Fourier Transform #
18
+ # #
19
+ #----------------------------------------------------------------------------#
20
+
21
+ def _fourier_transform(seq, dps, inverse=False):
22
+ """Utility function for the Discrete Fourier Transform"""
23
+
24
+ if not iterable(seq):
25
+ raise TypeError("Expected a sequence of numeric coefficients "
26
+ "for Fourier Transform")
27
+
28
+ a = [sympify(arg) for arg in seq]
29
+ if any(x.has(Symbol) for x in a):
30
+ raise ValueError("Expected non-symbolic coefficients")
31
+
32
+ n = len(a)
33
+ if n < 2:
34
+ return a
35
+
36
+ b = n.bit_length() - 1
37
+ if n&(n - 1): # not a power of 2
38
+ b += 1
39
+ n = 2**b
40
+
41
+ a += [S.Zero]*(n - len(a))
42
+ for i in range(1, n):
43
+ j = int(ibin(i, b, str=True)[::-1], 2)
44
+ if i < j:
45
+ a[i], a[j] = a[j], a[i]
46
+
47
+ ang = -2*pi/n if inverse else 2*pi/n
48
+
49
+ if dps is not None:
50
+ ang = ang.evalf(dps + 2)
51
+
52
+ w = [cos(ang*i) + I*sin(ang*i) for i in range(n // 2)]
53
+
54
+ h = 2
55
+ while h <= n:
56
+ hf, ut = h // 2, n // h
57
+ for i in range(0, n, h):
58
+ for j in range(hf):
59
+ u, v = a[i + j], expand_mul(a[i + j + hf]*w[ut * j])
60
+ a[i + j], a[i + j + hf] = u + v, u - v
61
+ h *= 2
62
+
63
+ if inverse:
64
+ a = [(x/n).evalf(dps) for x in a] if dps is not None \
65
+ else [x/n for x in a]
66
+
67
+ return a
68
+
69
+
70
+ def fft(seq, dps=None):
71
+ r"""
72
+ Performs the Discrete Fourier Transform (**DFT**) in the complex domain.
73
+
74
+ The sequence is automatically padded to the right with zeros, as the
75
+ *radix-2 FFT* requires the number of sample points to be a power of 2.
76
+
77
+ This method should be used with default arguments only for short sequences
78
+ as the complexity of expressions increases with the size of the sequence.
79
+
80
+ Parameters
81
+ ==========
82
+
83
+ seq : iterable
84
+ The sequence on which **DFT** is to be applied.
85
+ dps : Integer
86
+ Specifies the number of decimal digits for precision.
87
+
88
+ Examples
89
+ ========
90
+
91
+ >>> from sympy import fft, ifft
92
+
93
+ >>> fft([1, 2, 3, 4])
94
+ [10, -2 - 2*I, -2, -2 + 2*I]
95
+ >>> ifft(_)
96
+ [1, 2, 3, 4]
97
+
98
+ >>> ifft([1, 2, 3, 4])
99
+ [5/2, -1/2 + I/2, -1/2, -1/2 - I/2]
100
+ >>> fft(_)
101
+ [1, 2, 3, 4]
102
+
103
+ >>> ifft([1, 7, 3, 4], dps=15)
104
+ [3.75, -0.5 - 0.75*I, -1.75, -0.5 + 0.75*I]
105
+ >>> fft(_)
106
+ [1.0, 7.0, 3.0, 4.0]
107
+
108
+ References
109
+ ==========
110
+
111
+ .. [1] https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
112
+ .. [2] https://mathworld.wolfram.com/FastFourierTransform.html
113
+
114
+ """
115
+
116
+ return _fourier_transform(seq, dps=dps)
117
+
118
+
119
+ def ifft(seq, dps=None):
120
+ return _fourier_transform(seq, dps=dps, inverse=True)
121
+
122
+ ifft.__doc__ = fft.__doc__
123
+
124
+
125
+ #----------------------------------------------------------------------------#
126
+ # #
127
+ # Number Theoretic Transform #
128
+ # #
129
+ #----------------------------------------------------------------------------#
130
+
131
+ def _number_theoretic_transform(seq, prime, inverse=False):
132
+ """Utility function for the Number Theoretic Transform"""
133
+
134
+ if not iterable(seq):
135
+ raise TypeError("Expected a sequence of integer coefficients "
136
+ "for Number Theoretic Transform")
137
+
138
+ p = as_int(prime)
139
+ if not isprime(p):
140
+ raise ValueError("Expected prime modulus for "
141
+ "Number Theoretic Transform")
142
+
143
+ a = [as_int(x) % p for x in seq]
144
+
145
+ n = len(a)
146
+ if n < 1:
147
+ return a
148
+
149
+ b = n.bit_length() - 1
150
+ if n&(n - 1):
151
+ b += 1
152
+ n = 2**b
153
+
154
+ if (p - 1) % n:
155
+ raise ValueError("Expected prime modulus of the form (m*2**k + 1)")
156
+
157
+ a += [0]*(n - len(a))
158
+ for i in range(1, n):
159
+ j = int(ibin(i, b, str=True)[::-1], 2)
160
+ if i < j:
161
+ a[i], a[j] = a[j], a[i]
162
+
163
+ pr = primitive_root(p)
164
+
165
+ rt = pow(pr, (p - 1) // n, p)
166
+ if inverse:
167
+ rt = pow(rt, p - 2, p)
168
+
169
+ w = [1]*(n // 2)
170
+ for i in range(1, n // 2):
171
+ w[i] = w[i - 1]*rt % p
172
+
173
+ h = 2
174
+ while h <= n:
175
+ hf, ut = h // 2, n // h
176
+ for i in range(0, n, h):
177
+ for j in range(hf):
178
+ u, v = a[i + j], a[i + j + hf]*w[ut * j]
179
+ a[i + j], a[i + j + hf] = (u + v) % p, (u - v) % p
180
+ h *= 2
181
+
182
+ if inverse:
183
+ rv = pow(n, p - 2, p)
184
+ a = [x*rv % p for x in a]
185
+
186
+ return a
187
+
188
+
189
+ def ntt(seq, prime):
190
+ r"""
191
+ Performs the Number Theoretic Transform (**NTT**), which specializes the
192
+ Discrete Fourier Transform (**DFT**) over quotient ring `Z/pZ` for prime
193
+ `p` instead of complex numbers `C`.
194
+
195
+ The sequence is automatically padded to the right with zeros, as the
196
+ *radix-2 NTT* requires the number of sample points to be a power of 2.
197
+
198
+ Parameters
199
+ ==========
200
+
201
+ seq : iterable
202
+ The sequence on which **DFT** is to be applied.
203
+ prime : Integer
204
+ Prime modulus of the form `(m 2^k + 1)` to be used for performing
205
+ **NTT** on the sequence.
206
+
207
+ Examples
208
+ ========
209
+
210
+ >>> from sympy import ntt, intt
211
+ >>> ntt([1, 2, 3, 4], prime=3*2**8 + 1)
212
+ [10, 643, 767, 122]
213
+ >>> intt(_, 3*2**8 + 1)
214
+ [1, 2, 3, 4]
215
+ >>> intt([1, 2, 3, 4], prime=3*2**8 + 1)
216
+ [387, 415, 384, 353]
217
+ >>> ntt(_, prime=3*2**8 + 1)
218
+ [1, 2, 3, 4]
219
+
220
+ References
221
+ ==========
222
+
223
+ .. [1] http://www.apfloat.org/ntt.html
224
+ .. [2] https://mathworld.wolfram.com/NumberTheoreticTransform.html
225
+ .. [3] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
226
+
227
+ """
228
+
229
+ return _number_theoretic_transform(seq, prime=prime)
230
+
231
+
232
+ def intt(seq, prime):
233
+ return _number_theoretic_transform(seq, prime=prime, inverse=True)
234
+
235
+ intt.__doc__ = ntt.__doc__
236
+
237
+
238
+ #----------------------------------------------------------------------------#
239
+ # #
240
+ # Walsh Hadamard Transform #
241
+ # #
242
+ #----------------------------------------------------------------------------#
243
+
244
+ def _walsh_hadamard_transform(seq, inverse=False):
245
+ """Utility function for the Walsh Hadamard Transform"""
246
+
247
+ if not iterable(seq):
248
+ raise TypeError("Expected a sequence of coefficients "
249
+ "for Walsh Hadamard Transform")
250
+
251
+ a = [sympify(arg) for arg in seq]
252
+ n = len(a)
253
+ if n < 2:
254
+ return a
255
+
256
+ if n&(n - 1):
257
+ n = 2**n.bit_length()
258
+
259
+ a += [S.Zero]*(n - len(a))
260
+ h = 2
261
+ while h <= n:
262
+ hf = h // 2
263
+ for i in range(0, n, h):
264
+ for j in range(hf):
265
+ u, v = a[i + j], a[i + j + hf]
266
+ a[i + j], a[i + j + hf] = u + v, u - v
267
+ h *= 2
268
+
269
+ if inverse:
270
+ a = [x/n for x in a]
271
+
272
+ return a
273
+
274
+
275
+ def fwht(seq):
276
+ r"""
277
+ Performs the Walsh Hadamard Transform (**WHT**), and uses Hadamard
278
+ ordering for the sequence.
279
+
280
+ The sequence is automatically padded to the right with zeros, as the
281
+ *radix-2 FWHT* requires the number of sample points to be a power of 2.
282
+
283
+ Parameters
284
+ ==========
285
+
286
+ seq : iterable
287
+ The sequence on which WHT is to be applied.
288
+
289
+ Examples
290
+ ========
291
+
292
+ >>> from sympy import fwht, ifwht
293
+ >>> fwht([4, 2, 2, 0, 0, 2, -2, 0])
294
+ [8, 0, 8, 0, 8, 8, 0, 0]
295
+ >>> ifwht(_)
296
+ [4, 2, 2, 0, 0, 2, -2, 0]
297
+
298
+ >>> ifwht([19, -1, 11, -9, -7, 13, -15, 5])
299
+ [2, 0, 4, 0, 3, 10, 0, 0]
300
+ >>> fwht(_)
301
+ [19, -1, 11, -9, -7, 13, -15, 5]
302
+
303
+ References
304
+ ==========
305
+
306
+ .. [1] https://en.wikipedia.org/wiki/Hadamard_transform
307
+ .. [2] https://en.wikipedia.org/wiki/Fast_Walsh%E2%80%93Hadamard_transform
308
+
309
+ """
310
+
311
+ return _walsh_hadamard_transform(seq)
312
+
313
+
314
+ def ifwht(seq):
315
+ return _walsh_hadamard_transform(seq, inverse=True)
316
+
317
+ ifwht.__doc__ = fwht.__doc__
318
+
319
+
320
+ #----------------------------------------------------------------------------#
321
+ # #
322
+ # Mobius Transform for Subset Lattice #
323
+ # #
324
+ #----------------------------------------------------------------------------#
325
+
326
+ def _mobius_transform(seq, sgn, subset):
327
+ r"""Utility function for performing Mobius Transform using
328
+ Yate's Dynamic Programming method"""
329
+
330
+ if not iterable(seq):
331
+ raise TypeError("Expected a sequence of coefficients")
332
+
333
+ a = [sympify(arg) for arg in seq]
334
+
335
+ n = len(a)
336
+ if n < 2:
337
+ return a
338
+
339
+ if n&(n - 1):
340
+ n = 2**n.bit_length()
341
+
342
+ a += [S.Zero]*(n - len(a))
343
+
344
+ if subset:
345
+ i = 1
346
+ while i < n:
347
+ for j in range(n):
348
+ if j & i:
349
+ a[j] += sgn*a[j ^ i]
350
+ i *= 2
351
+
352
+ else:
353
+ i = 1
354
+ while i < n:
355
+ for j in range(n):
356
+ if j & i:
357
+ continue
358
+ a[j] += sgn*a[j ^ i]
359
+ i *= 2
360
+
361
+ return a
362
+
363
+
364
+ def mobius_transform(seq, subset=True):
365
+ r"""
366
+ Performs the Mobius Transform for subset lattice with indices of
367
+ sequence as bitmasks.
368
+
369
+ The indices of each argument, considered as bit strings, correspond
370
+ to subsets of a finite set.
371
+
372
+ The sequence is automatically padded to the right with zeros, as the
373
+ definition of subset/superset based on bitmasks (indices) requires
374
+ the size of sequence to be a power of 2.
375
+
376
+ Parameters
377
+ ==========
378
+
379
+ seq : iterable
380
+ The sequence on which Mobius Transform is to be applied.
381
+ subset : bool
382
+ Specifies if Mobius Transform is applied by enumerating subsets
383
+ or supersets of the given set.
384
+
385
+ Examples
386
+ ========
387
+
388
+ >>> from sympy import symbols
389
+ >>> from sympy import mobius_transform, inverse_mobius_transform
390
+ >>> x, y, z = symbols('x y z')
391
+
392
+ >>> mobius_transform([x, y, z])
393
+ [x, x + y, x + z, x + y + z]
394
+ >>> inverse_mobius_transform(_)
395
+ [x, y, z, 0]
396
+
397
+ >>> mobius_transform([x, y, z], subset=False)
398
+ [x + y + z, y, z, 0]
399
+ >>> inverse_mobius_transform(_, subset=False)
400
+ [x, y, z, 0]
401
+
402
+ >>> mobius_transform([1, 2, 3, 4])
403
+ [1, 3, 4, 10]
404
+ >>> inverse_mobius_transform(_)
405
+ [1, 2, 3, 4]
406
+ >>> mobius_transform([1, 2, 3, 4], subset=False)
407
+ [10, 6, 7, 4]
408
+ >>> inverse_mobius_transform(_, subset=False)
409
+ [1, 2, 3, 4]
410
+
411
+ References
412
+ ==========
413
+
414
+ .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula
415
+ .. [2] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
416
+ .. [3] https://arxiv.org/pdf/1211.0189.pdf
417
+
418
+ """
419
+
420
+ return _mobius_transform(seq, sgn=+1, subset=subset)
421
+
422
+ def inverse_mobius_transform(seq, subset=True):
423
+ return _mobius_transform(seq, sgn=-1, subset=subset)
424
+
425
+ inverse_mobius_transform.__doc__ = mobius_transform.__doc__
venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (202 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ The :py:mod:`~sympy.holonomic` module is intended to deal with holonomic functions along
3
+ with various operations on them like addition, multiplication, composition,
4
+ integration and differentiation. The module also implements various kinds of
5
+ conversions such as converting holonomic functions to a different form and the
6
+ other way around.
7
+ """
8
+
9
+ from .holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators,
10
+ from_hyper, from_meijerg, expr_to_holonomic)
11
+ from .recurrence import RecurrenceOperators, RecurrenceOperator, HolonomicSequence
12
+
13
+ __all__ = [
14
+ 'DifferentialOperator', 'HolonomicFunction', 'DifferentialOperators',
15
+ 'from_hyper', 'from_meijerg', 'expr_to_holonomic',
16
+
17
+ 'RecurrenceOperators', 'RecurrenceOperator', 'HolonomicSequence',
18
+ ]
venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (906 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc ADDED
Binary file (68.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc ADDED
Binary file (3.41 kB). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc ADDED
Binary file (9.39 kB). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/holonomic.py ADDED
@@ -0,0 +1,2899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements Holonomic Functions and
3
+ various operations on them.
4
+ """
5
+
6
+ from sympy.core import Add, Mul, Pow
7
+ from sympy.core.numbers import (NaN, Infinity, NegativeInfinity, Float, I, pi,
8
+ equal_valued)
9
+ from sympy.core.singleton import S
10
+ from sympy.core.sorting import ordered
11
+ from sympy.core.symbol import Dummy, Symbol
12
+ from sympy.core.sympify import sympify
13
+ from sympy.functions.combinatorial.factorials import binomial, factorial, rf
14
+ from sympy.functions.elementary.exponential import exp_polar, exp, log
15
+ from sympy.functions.elementary.hyperbolic import (cosh, sinh)
16
+ from sympy.functions.elementary.miscellaneous import sqrt
17
+ from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
18
+ from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi)
19
+ from sympy.functions.special.gamma_functions import gamma
20
+ from sympy.functions.special.hyper import hyper, meijerg
21
+ from sympy.integrals import meijerint
22
+ from sympy.matrices import Matrix
23
+ from sympy.polys.rings import PolyElement
24
+ from sympy.polys.fields import FracElement
25
+ from sympy.polys.domains import QQ, RR
26
+ from sympy.polys.polyclasses import DMF
27
+ from sympy.polys.polyroots import roots
28
+ from sympy.polys.polytools import Poly
29
+ from sympy.polys.matrices import DomainMatrix
30
+ from sympy.printing import sstr
31
+ from sympy.series.limits import limit
32
+ from sympy.series.order import Order
33
+ from sympy.simplify.hyperexpand import hyperexpand
34
+ from sympy.simplify.simplify import nsimplify
35
+ from sympy.solvers.solvers import solve
36
+
37
+ from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators
38
+ from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError,
39
+ SingularityError, NotHolonomicError)
40
+
41
+
42
+ def _find_nonzero_solution(r, homosys):
43
+ ones = lambda shape: DomainMatrix.ones(shape, r.domain)
44
+ particular, nullspace = r._solve(homosys)
45
+ nullity = nullspace.shape[0]
46
+ nullpart = ones((1, nullity)) * nullspace
47
+ sol = (particular + nullpart).transpose()
48
+ return sol
49
+
50
+
51
+
52
+ def DifferentialOperators(base, generator):
53
+ r"""
54
+ This function is used to create annihilators using ``Dx``.
55
+
56
+ Explanation
57
+ ===========
58
+
59
+ Returns an Algebra of Differential Operators also called Weyl Algebra
60
+ and the operator for differentiation i.e. the ``Dx`` operator.
61
+
62
+ Parameters
63
+ ==========
64
+
65
+ base:
66
+ Base polynomial ring for the algebra.
67
+ The base polynomial ring is the ring of polynomials in :math:`x` that
68
+ will appear as coefficients in the operators.
69
+ generator:
70
+ Generator of the algebra which can
71
+ be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D".
72
+
73
+ Examples
74
+ ========
75
+
76
+ >>> from sympy import ZZ
77
+ >>> from sympy.abc import x
78
+ >>> from sympy.holonomic.holonomic import DifferentialOperators
79
+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
80
+ >>> R
81
+ Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x]
82
+ >>> Dx*x
83
+ (1) + (x)*Dx
84
+ """
85
+
86
+ ring = DifferentialOperatorAlgebra(base, generator)
87
+ return (ring, ring.derivative_operator)
88
+
89
+
90
+ class DifferentialOperatorAlgebra:
91
+ r"""
92
+ An Ore Algebra is a set of noncommutative polynomials in the
93
+ intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`.
94
+ It follows the commutation rule:
95
+
96
+ .. math ::
97
+ Dxa = \sigma(a)Dx + \delta(a)
98
+
99
+ for :math:`a \subset A`.
100
+
101
+ Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A`
102
+ is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`.
103
+
104
+ If one takes the sigma as identity map and delta as the standard derivation
105
+ then it becomes the algebra of Differential Operators also called
106
+ a Weyl Algebra i.e. an algebra whose elements are Differential Operators.
107
+
108
+ This class represents a Weyl Algebra and serves as the parent ring for
109
+ Differential Operators.
110
+
111
+ Examples
112
+ ========
113
+
114
+ >>> from sympy import ZZ
115
+ >>> from sympy import symbols
116
+ >>> from sympy.holonomic.holonomic import DifferentialOperators
117
+ >>> x = symbols('x')
118
+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
119
+ >>> R
120
+ Univariate Differential Operator Algebra in intermediate Dx over the base ring
121
+ ZZ[x]
122
+
123
+ See Also
124
+ ========
125
+
126
+ DifferentialOperator
127
+ """
128
+
129
+ def __init__(self, base, generator):
130
+ # the base polynomial ring for the algebra
131
+ self.base = base
132
+ # the operator representing differentiation i.e. `Dx`
133
+ self.derivative_operator = DifferentialOperator(
134
+ [base.zero, base.one], self)
135
+
136
+ if generator is None:
137
+ self.gen_symbol = Symbol('Dx', commutative=False)
138
+ else:
139
+ if isinstance(generator, str):
140
+ self.gen_symbol = Symbol(generator, commutative=False)
141
+ elif isinstance(generator, Symbol):
142
+ self.gen_symbol = generator
143
+
144
+ def __str__(self):
145
+ string = 'Univariate Differential Operator Algebra in intermediate '\
146
+ + sstr(self.gen_symbol) + ' over the base ring ' + \
147
+ (self.base).__str__()
148
+
149
+ return string
150
+
151
+ __repr__ = __str__
152
+
153
+ def __eq__(self, other):
154
+ if self.base == other.base and self.gen_symbol == other.gen_symbol:
155
+ return True
156
+ else:
157
+ return False
158
+
159
+
160
+ class DifferentialOperator:
161
+ """
162
+ Differential Operators are elements of Weyl Algebra. The Operators
163
+ are defined by a list of polynomials in the base ring and the
164
+ parent ring of the Operator i.e. the algebra it belongs to.
165
+
166
+ Explanation
167
+ ===========
168
+
169
+ Takes a list of polynomials for each power of ``Dx`` and the
170
+ parent ring which must be an instance of DifferentialOperatorAlgebra.
171
+
172
+ A Differential Operator can be created easily using
173
+ the operator ``Dx``. See examples below.
174
+
175
+ Examples
176
+ ========
177
+
178
+ >>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators
179
+ >>> from sympy import ZZ
180
+ >>> from sympy import symbols
181
+ >>> x = symbols('x')
182
+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
183
+
184
+ >>> DifferentialOperator([0, 1, x**2], R)
185
+ (1)*Dx + (x**2)*Dx**2
186
+
187
+ >>> (x*Dx*x + 1 - Dx**2)**2
188
+ (2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4
189
+
190
+ See Also
191
+ ========
192
+
193
+ DifferentialOperatorAlgebra
194
+ """
195
+
196
+ _op_priority = 20
197
+
198
+ def __init__(self, list_of_poly, parent):
199
+ """
200
+ Parameters
201
+ ==========
202
+
203
+ list_of_poly:
204
+ List of polynomials belonging to the base ring of the algebra.
205
+ parent:
206
+ Parent algebra of the operator.
207
+ """
208
+
209
+ # the parent ring for this operator
210
+ # must be an DifferentialOperatorAlgebra object
211
+ self.parent = parent
212
+ base = self.parent.base
213
+ self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0]
214
+ # sequence of polynomials in x for each power of Dx
215
+ # the list should not have trailing zeroes
216
+ # represents the operator
217
+ # convert the expressions into ring elements using from_sympy
218
+ for i, j in enumerate(list_of_poly):
219
+ if not isinstance(j, base.dtype):
220
+ list_of_poly[i] = base.from_sympy(sympify(j))
221
+ else:
222
+ list_of_poly[i] = base.from_sympy(base.to_sympy(j))
223
+
224
+ self.listofpoly = list_of_poly
225
+ # highest power of `Dx`
226
+ self.order = len(self.listofpoly) - 1
227
+
228
+ def __mul__(self, other):
229
+ """
230
+ Multiplies two DifferentialOperator and returns another
231
+ DifferentialOperator instance using the commutation rule
232
+ Dx*a = a*Dx + a'
233
+ """
234
+
235
+ listofself = self.listofpoly
236
+
237
+ if not isinstance(other, DifferentialOperator):
238
+ if not isinstance(other, self.parent.base.dtype):
239
+ listofother = [self.parent.base.from_sympy(sympify(other))]
240
+
241
+ else:
242
+ listofother = [other]
243
+ else:
244
+ listofother = other.listofpoly
245
+
246
+ # multiplies a polynomial `b` with a list of polynomials
247
+ def _mul_dmp_diffop(b, listofother):
248
+ if isinstance(listofother, list):
249
+ sol = []
250
+ for i in listofother:
251
+ sol.append(i * b)
252
+ return sol
253
+ else:
254
+ return [b * listofother]
255
+
256
+ sol = _mul_dmp_diffop(listofself[0], listofother)
257
+
258
+ # compute Dx^i * b
259
+ def _mul_Dxi_b(b):
260
+ sol1 = [self.parent.base.zero]
261
+ sol2 = []
262
+
263
+ if isinstance(b, list):
264
+ for i in b:
265
+ sol1.append(i)
266
+ sol2.append(i.diff())
267
+ else:
268
+ sol1.append(self.parent.base.from_sympy(b))
269
+ sol2.append(self.parent.base.from_sympy(b).diff())
270
+
271
+ return _add_lists(sol1, sol2)
272
+
273
+ for i in range(1, len(listofself)):
274
+ # find Dx^i * b in ith iteration
275
+ listofother = _mul_Dxi_b(listofother)
276
+ # solution = solution + listofself[i] * (Dx^i * b)
277
+ sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
278
+
279
+ return DifferentialOperator(sol, self.parent)
280
+
281
+ def __rmul__(self, other):
282
+ if not isinstance(other, DifferentialOperator):
283
+
284
+ if not isinstance(other, self.parent.base.dtype):
285
+ other = (self.parent.base).from_sympy(sympify(other))
286
+
287
+ sol = []
288
+ for j in self.listofpoly:
289
+ sol.append(other * j)
290
+
291
+ return DifferentialOperator(sol, self.parent)
292
+
293
+ def __add__(self, other):
294
+ if isinstance(other, DifferentialOperator):
295
+
296
+ sol = _add_lists(self.listofpoly, other.listofpoly)
297
+ return DifferentialOperator(sol, self.parent)
298
+
299
+ else:
300
+ list_self = self.listofpoly
301
+ if not isinstance(other, self.parent.base.dtype):
302
+ list_other = [((self.parent).base).from_sympy(sympify(other))]
303
+ else:
304
+ list_other = [other]
305
+ sol = []
306
+ sol.append(list_self[0] + list_other[0])
307
+ sol += list_self[1:]
308
+
309
+ return DifferentialOperator(sol, self.parent)
310
+
311
+ __radd__ = __add__
312
+
313
+ def __sub__(self, other):
314
+ return self + (-1) * other
315
+
316
+ def __rsub__(self, other):
317
+ return (-1) * self + other
318
+
319
+ def __neg__(self):
320
+ return -1 * self
321
+
322
+ def __truediv__(self, other):
323
+ return self * (S.One / other)
324
+
325
+ def __pow__(self, n):
326
+ if n == 1:
327
+ return self
328
+ if n == 0:
329
+ return DifferentialOperator([self.parent.base.one], self.parent)
330
+
331
+ # if self is `Dx`
332
+ if self.listofpoly == self.parent.derivative_operator.listofpoly:
333
+ sol = [self.parent.base.zero]*n
334
+ sol.append(self.parent.base.one)
335
+ return DifferentialOperator(sol, self.parent)
336
+
337
+ # the general case
338
+ else:
339
+ if n % 2 == 1:
340
+ powreduce = self**(n - 1)
341
+ return powreduce * self
342
+ elif n % 2 == 0:
343
+ powreduce = self**(n / 2)
344
+ return powreduce * powreduce
345
+
346
+ def __str__(self):
347
+ listofpoly = self.listofpoly
348
+ print_str = ''
349
+
350
+ for i, j in enumerate(listofpoly):
351
+ if j == self.parent.base.zero:
352
+ continue
353
+
354
+ if i == 0:
355
+ print_str += '(' + sstr(j) + ')'
356
+ continue
357
+
358
+ if print_str:
359
+ print_str += ' + '
360
+
361
+ if i == 1:
362
+ print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol)
363
+ continue
364
+
365
+ print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i)
366
+
367
+ return print_str
368
+
369
+ __repr__ = __str__
370
+
371
+ def __eq__(self, other):
372
+ if isinstance(other, DifferentialOperator):
373
+ if self.listofpoly == other.listofpoly and self.parent == other.parent:
374
+ return True
375
+ else:
376
+ return False
377
+ else:
378
+ if self.listofpoly[0] == other:
379
+ for i in self.listofpoly[1:]:
380
+ if i is not self.parent.base.zero:
381
+ return False
382
+ return True
383
+ else:
384
+ return False
385
+
386
+ def is_singular(self, x0):
387
+ """
388
+ Checks if the differential equation is singular at x0.
389
+ """
390
+
391
+ base = self.parent.base
392
+ return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x)
393
+
394
+
395
+ class HolonomicFunction:
396
+ r"""
397
+ A Holonomic Function is a solution to a linear homogeneous ordinary
398
+ differential equation with polynomial coefficients. This differential
399
+ equation can also be represented by an annihilator i.e. a Differential
400
+ Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions,
401
+ initial conditions can also be provided along with the annihilator.
402
+
403
+ Explanation
404
+ ===========
405
+
406
+ Holonomic functions have closure properties and thus forms a ring.
407
+ Given two Holonomic Functions f and g, their sum, product,
408
+ integral and derivative is also a Holonomic Function.
409
+
410
+ For ordinary points initial condition should be a vector of values of
411
+ the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`.
412
+
413
+ For regular singular points initial conditions can also be provided in this
414
+ format:
415
+ :math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}`
416
+ where s0, s1, ... are the roots of indicial equation and vectors
417
+ :math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial
418
+ terms of the associated power series. See Examples below.
419
+
420
+ Examples
421
+ ========
422
+
423
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
424
+ >>> from sympy import QQ
425
+ >>> from sympy import symbols, S
426
+ >>> x = symbols('x')
427
+ >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
428
+
429
+ >>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x
430
+ >>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x)
431
+
432
+ >>> p + q # annihilator of e^x + sin(x)
433
+ HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1])
434
+
435
+ >>> p * q # annihilator of e^x * sin(x)
436
+ HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1])
437
+
438
+ An example of initial conditions for regular singular points,
439
+ the indicial equation has only one root `1/2`.
440
+
441
+ >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]})
442
+ HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]})
443
+
444
+ >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr()
445
+ sqrt(x)
446
+
447
+ To plot a Holonomic Function, one can use `.evalf()` for numerical
448
+ computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib.
449
+
450
+ >>> import sympy.holonomic # doctest: +SKIP
451
+ >>> from sympy import var, sin # doctest: +SKIP
452
+ >>> import matplotlib.pyplot as plt # doctest: +SKIP
453
+ >>> import numpy as np # doctest: +SKIP
454
+ >>> var("x") # doctest: +SKIP
455
+ >>> r = np.linspace(1, 5, 100) # doctest: +SKIP
456
+ >>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP
457
+ >>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP
458
+ >>> plt.show() # doctest: +SKIP
459
+
460
+ """
461
+
462
+ _op_priority = 20
463
+
464
+ def __init__(self, annihilator, x, x0=0, y0=None):
465
+ """
466
+
467
+ Parameters
468
+ ==========
469
+
470
+ annihilator:
471
+ Annihilator of the Holonomic Function, represented by a
472
+ `DifferentialOperator` object.
473
+ x:
474
+ Variable of the function.
475
+ x0:
476
+ The point at which initial conditions are stored.
477
+ Generally an integer.
478
+ y0:
479
+ The initial condition. The proper format for the initial condition
480
+ is described in class docstring. To make the function unique,
481
+ length of the vector `y0` should be equal to or greater than the
482
+ order of differential equation.
483
+ """
484
+
485
+ # initial condition
486
+ self.y0 = y0
487
+ # the point for initial conditions, default is zero.
488
+ self.x0 = x0
489
+ # differential operator L such that L.f = 0
490
+ self.annihilator = annihilator
491
+ self.x = x
492
+
493
+ def __str__(self):
494
+ if self._have_init_cond():
495
+ str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\
496
+ sstr(self.x), sstr(self.x0), sstr(self.y0))
497
+ else:
498
+ str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\
499
+ sstr(self.x))
500
+
501
+ return str_sol
502
+
503
+ __repr__ = __str__
504
+
505
+ def unify(self, other):
506
+ """
507
+ Unifies the base polynomial ring of a given two Holonomic
508
+ Functions.
509
+ """
510
+
511
+ R1 = self.annihilator.parent.base
512
+ R2 = other.annihilator.parent.base
513
+
514
+ dom1 = R1.dom
515
+ dom2 = R2.dom
516
+
517
+ if R1 == R2:
518
+ return (self, other)
519
+
520
+ R = (dom1.unify(dom2)).old_poly_ring(self.x)
521
+
522
+ newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol))
523
+
524
+ sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly]
525
+ sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly]
526
+
527
+ sol1 = DifferentialOperator(sol1, newparent)
528
+ sol2 = DifferentialOperator(sol2, newparent)
529
+
530
+ sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0)
531
+ sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0)
532
+
533
+ return (sol1, sol2)
534
+
535
+ def is_singularics(self):
536
+ """
537
+ Returns True if the function have singular initial condition
538
+ in the dictionary format.
539
+
540
+ Returns False if the function have ordinary initial condition
541
+ in the list format.
542
+
543
+ Returns None for all other cases.
544
+ """
545
+
546
+ if isinstance(self.y0, dict):
547
+ return True
548
+ elif isinstance(self.y0, list):
549
+ return False
550
+
551
+ def _have_init_cond(self):
552
+ """
553
+ Checks if the function have initial condition.
554
+ """
555
+ return bool(self.y0)
556
+
557
+ def _singularics_to_ord(self):
558
+ """
559
+ Converts a singular initial condition to ordinary if possible.
560
+ """
561
+ a = list(self.y0)[0]
562
+ b = self.y0[a]
563
+
564
+ if len(self.y0) == 1 and a == int(a) and a > 0:
565
+ y0 = []
566
+ a = int(a)
567
+ for i in range(a):
568
+ y0.append(S.Zero)
569
+ y0 += [j * factorial(a + i) for i, j in enumerate(b)]
570
+
571
+ return HolonomicFunction(self.annihilator, self.x, self.x0, y0)
572
+
573
+ def __add__(self, other):
574
+ # if the ground domains are different
575
+ if self.annihilator.parent.base != other.annihilator.parent.base:
576
+ a, b = self.unify(other)
577
+ return a + b
578
+
579
+ deg1 = self.annihilator.order
580
+ deg2 = other.annihilator.order
581
+ dim = max(deg1, deg2)
582
+ R = self.annihilator.parent.base
583
+ K = R.get_field()
584
+
585
+ rowsself = [self.annihilator]
586
+ rowsother = [other.annihilator]
587
+ gen = self.annihilator.parent.derivative_operator
588
+
589
+ # constructing annihilators up to order dim
590
+ for i in range(dim - deg1):
591
+ diff1 = (gen * rowsself[-1])
592
+ rowsself.append(diff1)
593
+
594
+ for i in range(dim - deg2):
595
+ diff2 = (gen * rowsother[-1])
596
+ rowsother.append(diff2)
597
+
598
+ row = rowsself + rowsother
599
+
600
+ # constructing the matrix of the ansatz
601
+ r = []
602
+
603
+ for expr in row:
604
+ p = []
605
+ for i in range(dim + 1):
606
+ if i >= len(expr.listofpoly):
607
+ p.append(K.zero)
608
+ else:
609
+ p.append(K.new(expr.listofpoly[i].rep))
610
+ r.append(p)
611
+
612
+ # solving the linear system using gauss jordan solver
613
+ r = DomainMatrix(r, (len(row), dim+1), K).transpose()
614
+ homosys = DomainMatrix.zeros((dim+1, 1), K)
615
+ sol = _find_nonzero_solution(r, homosys)
616
+
617
+ # if a solution is not obtained then increasing the order by 1 in each
618
+ # iteration
619
+ while sol.is_zero_matrix:
620
+ dim += 1
621
+
622
+ diff1 = (gen * rowsself[-1])
623
+ rowsself.append(diff1)
624
+
625
+ diff2 = (gen * rowsother[-1])
626
+ rowsother.append(diff2)
627
+
628
+ row = rowsself + rowsother
629
+ r = []
630
+
631
+ for expr in row:
632
+ p = []
633
+ for i in range(dim + 1):
634
+ if i >= len(expr.listofpoly):
635
+ p.append(K.zero)
636
+ else:
637
+ p.append(K.new(expr.listofpoly[i].rep))
638
+ r.append(p)
639
+
640
+ # solving the linear system using gauss jordan solver
641
+ r = DomainMatrix(r, (len(row), dim+1), K).transpose()
642
+ homosys = DomainMatrix.zeros((dim+1, 1), K)
643
+ sol = _find_nonzero_solution(r, homosys)
644
+
645
+ # taking only the coefficients needed to multiply with `self`
646
+ # can be also be done the other way by taking R.H.S and multiplying with
647
+ # `other`
648
+ sol = sol.flat()[:dim + 1 - deg1]
649
+ sol1 = _normalize(sol, self.annihilator.parent)
650
+ # annihilator of the solution
651
+ sol = sol1 * (self.annihilator)
652
+ sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False)
653
+
654
+ if not (self._have_init_cond() and other._have_init_cond()):
655
+ return HolonomicFunction(sol, self.x)
656
+
657
+ # both the functions have ordinary initial conditions
658
+ if self.is_singularics() == False and other.is_singularics() == False:
659
+
660
+ # directly add the corresponding value
661
+ if self.x0 == other.x0:
662
+ # try to extended the initial conditions
663
+ # using the annihilator
664
+ y1 = _extend_y0(self, sol.order)
665
+ y2 = _extend_y0(other, sol.order)
666
+ y0 = [a + b for a, b in zip(y1, y2)]
667
+ return HolonomicFunction(sol, self.x, self.x0, y0)
668
+
669
+ else:
670
+ # change the initial conditions to a same point
671
+ selfat0 = self.annihilator.is_singular(0)
672
+ otherat0 = other.annihilator.is_singular(0)
673
+
674
+ if self.x0 == 0 and not selfat0 and not otherat0:
675
+ return self + other.change_ics(0)
676
+
677
+ elif other.x0 == 0 and not selfat0 and not otherat0:
678
+ return self.change_ics(0) + other
679
+
680
+ else:
681
+ selfatx0 = self.annihilator.is_singular(self.x0)
682
+ otheratx0 = other.annihilator.is_singular(self.x0)
683
+
684
+ if not selfatx0 and not otheratx0:
685
+ return self + other.change_ics(self.x0)
686
+
687
+ else:
688
+ return self.change_ics(other.x0) + other
689
+
690
+ if self.x0 != other.x0:
691
+ return HolonomicFunction(sol, self.x)
692
+
693
+ # if the functions have singular_ics
694
+ y1 = None
695
+ y2 = None
696
+
697
+ if self.is_singularics() == False and other.is_singularics() == True:
698
+ # convert the ordinary initial condition to singular.
699
+ _y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
700
+ y1 = {S.Zero: _y0}
701
+ y2 = other.y0
702
+ elif self.is_singularics() == True and other.is_singularics() == False:
703
+ _y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
704
+ y1 = self.y0
705
+ y2 = {S.Zero: _y0}
706
+ elif self.is_singularics() == True and other.is_singularics() == True:
707
+ y1 = self.y0
708
+ y2 = other.y0
709
+
710
+ # computing singular initial condition for the result
711
+ # taking union of the series terms of both functions
712
+ y0 = {}
713
+ for i in y1:
714
+ # add corresponding initial terms if the power
715
+ # on `x` is same
716
+ if i in y2:
717
+ y0[i] = [a + b for a, b in zip(y1[i], y2[i])]
718
+ else:
719
+ y0[i] = y1[i]
720
+ for i in y2:
721
+ if i not in y1:
722
+ y0[i] = y2[i]
723
+ return HolonomicFunction(sol, self.x, self.x0, y0)
724
+
725
+ def integrate(self, limits, initcond=False):
726
+ """
727
+ Integrates the given holonomic function.
728
+
729
+ Examples
730
+ ========
731
+
732
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
733
+ >>> from sympy import QQ
734
+ >>> from sympy import symbols
735
+ >>> x = symbols('x')
736
+ >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
737
+ >>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1
738
+ HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1])
739
+ >>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x))
740
+ HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0])
741
+ """
742
+
743
+ # to get the annihilator, just multiply by Dx from right
744
+ D = self.annihilator.parent.derivative_operator
745
+
746
+ # if the function have initial conditions of the series format
747
+ if self.is_singularics() == True:
748
+
749
+ r = self._singularics_to_ord()
750
+ if r:
751
+ return r.integrate(limits, initcond=initcond)
752
+
753
+ # computing singular initial condition for the function
754
+ # produced after integration.
755
+ y0 = {}
756
+ for i in self.y0:
757
+ c = self.y0[i]
758
+ c2 = []
759
+ for j, cj in enumerate(c):
760
+ if cj == 0:
761
+ c2.append(S.Zero)
762
+
763
+ # if power on `x` is -1, the integration becomes log(x)
764
+ # TODO: Implement this case
765
+ elif i + j + 1 == 0:
766
+ raise NotImplementedError("logarithmic terms in the series are not supported")
767
+ else:
768
+ c2.append(cj / S(i + j + 1))
769
+ y0[i + 1] = c2
770
+
771
+ if hasattr(limits, "__iter__"):
772
+ raise NotImplementedError("Definite integration for singular initial conditions")
773
+
774
+ return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
775
+
776
+ # if no initial conditions are available for the function
777
+ if not self._have_init_cond():
778
+ if initcond:
779
+ return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero])
780
+ return HolonomicFunction(self.annihilator * D, self.x)
781
+
782
+ # definite integral
783
+ # initial conditions for the answer will be stored at point `a`,
784
+ # where `a` is the lower limit of the integrand
785
+ if hasattr(limits, "__iter__"):
786
+
787
+ if len(limits) == 3 and limits[0] == self.x:
788
+ x0 = self.x0
789
+ a = limits[1]
790
+ b = limits[2]
791
+ definite = True
792
+
793
+ else:
794
+ definite = False
795
+
796
+ y0 = [S.Zero]
797
+ y0 += self.y0
798
+
799
+ indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
800
+
801
+ if not definite:
802
+ return indefinite_integral
803
+
804
+ # use evalf to get the values at `a`
805
+ if x0 != a:
806
+ try:
807
+ indefinite_expr = indefinite_integral.to_expr()
808
+ except (NotHyperSeriesError, NotPowerSeriesError):
809
+ indefinite_expr = None
810
+
811
+ if indefinite_expr:
812
+ lower = indefinite_expr.subs(self.x, a)
813
+ if isinstance(lower, NaN):
814
+ lower = indefinite_expr.limit(self.x, a)
815
+ else:
816
+ lower = indefinite_integral.evalf(a)
817
+
818
+ if b == self.x:
819
+ y0[0] = y0[0] - lower
820
+ return HolonomicFunction(self.annihilator * D, self.x, x0, y0)
821
+
822
+ elif S(b).is_Number:
823
+ if indefinite_expr:
824
+ upper = indefinite_expr.subs(self.x, b)
825
+ if isinstance(upper, NaN):
826
+ upper = indefinite_expr.limit(self.x, b)
827
+ else:
828
+ upper = indefinite_integral.evalf(b)
829
+
830
+ return upper - lower
831
+
832
+
833
+ # if the upper limit is `x`, the answer will be a function
834
+ if b == self.x:
835
+ return HolonomicFunction(self.annihilator * D, self.x, a, y0)
836
+
837
+ # if the upper limits is a Number, a numerical value will be returned
838
+ elif S(b).is_Number:
839
+ try:
840
+ s = HolonomicFunction(self.annihilator * D, self.x, a,\
841
+ y0).to_expr()
842
+ indefinite = s.subs(self.x, b)
843
+ if not isinstance(indefinite, NaN):
844
+ return indefinite
845
+ else:
846
+ return s.limit(self.x, b)
847
+ except (NotHyperSeriesError, NotPowerSeriesError):
848
+ return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b)
849
+
850
+ return HolonomicFunction(self.annihilator * D, self.x)
851
+
852
+ def diff(self, *args, **kwargs):
853
+ r"""
854
+ Differentiation of the given Holonomic function.
855
+
856
+ Examples
857
+ ========
858
+
859
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
860
+ >>> from sympy import ZZ
861
+ >>> from sympy import symbols
862
+ >>> x = symbols('x')
863
+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
864
+ >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr()
865
+ cos(x)
866
+ >>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr()
867
+ 2*exp(2*x)
868
+
869
+ See Also
870
+ ========
871
+
872
+ integrate
873
+ """
874
+ kwargs.setdefault('evaluate', True)
875
+ if args:
876
+ if args[0] != self.x:
877
+ return S.Zero
878
+ elif len(args) == 2:
879
+ sol = self
880
+ for i in range(args[1]):
881
+ sol = sol.diff(args[0])
882
+ return sol
883
+
884
+ ann = self.annihilator
885
+
886
+ # if the function is constant.
887
+ if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1:
888
+ return S.Zero
889
+
890
+ # if the coefficient of y in the differential equation is zero.
891
+ # a shifting is done to compute the answer in this case.
892
+ elif ann.listofpoly[0] == ann.parent.base.zero:
893
+
894
+ sol = DifferentialOperator(ann.listofpoly[1:], ann.parent)
895
+
896
+ if self._have_init_cond():
897
+ # if ordinary initial condition
898
+ if self.is_singularics() == False:
899
+ return HolonomicFunction(sol, self.x, self.x0, self.y0[1:])
900
+ # TODO: support for singular initial condition
901
+ return HolonomicFunction(sol, self.x)
902
+ else:
903
+ return HolonomicFunction(sol, self.x)
904
+
905
+ # the general algorithm
906
+ R = ann.parent.base
907
+ K = R.get_field()
908
+
909
+ seq_dmf = [K.new(i.rep) for i in ann.listofpoly]
910
+
911
+ # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0
912
+ rhs = [i / seq_dmf[0] for i in seq_dmf[1:]]
913
+ rhs.insert(0, K.zero)
914
+
915
+ # differentiate both lhs and rhs
916
+ sol = _derivate_diff_eq(rhs)
917
+
918
+ # add the term y' in lhs to rhs
919
+ sol = _add_lists(sol, [K.zero, K.one])
920
+
921
+ sol = _normalize(sol[1:], self.annihilator.parent, negative=False)
922
+
923
+ if not self._have_init_cond() or self.is_singularics() == True:
924
+ return HolonomicFunction(sol, self.x)
925
+
926
+ y0 = _extend_y0(self, sol.order + 1)[1:]
927
+ return HolonomicFunction(sol, self.x, self.x0, y0)
928
+
929
+ def __eq__(self, other):
930
+ if self.annihilator == other.annihilator:
931
+ if self.x == other.x:
932
+ if self._have_init_cond() and other._have_init_cond():
933
+ if self.x0 == other.x0 and self.y0 == other.y0:
934
+ return True
935
+ else:
936
+ return False
937
+ else:
938
+ return True
939
+ else:
940
+ return False
941
+ else:
942
+ return False
943
+
944
+ def __mul__(self, other):
945
+ ann_self = self.annihilator
946
+
947
+ if not isinstance(other, HolonomicFunction):
948
+ other = sympify(other)
949
+
950
+ if other.has(self.x):
951
+ raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.")
952
+
953
+ if not self._have_init_cond():
954
+ return self
955
+ else:
956
+ y0 = _extend_y0(self, ann_self.order)
957
+ y1 = []
958
+
959
+ for j in y0:
960
+ y1.append((Poly.new(j, self.x) * other).rep)
961
+
962
+ return HolonomicFunction(ann_self, self.x, self.x0, y1)
963
+
964
+ if self.annihilator.parent.base != other.annihilator.parent.base:
965
+ a, b = self.unify(other)
966
+ return a * b
967
+
968
+ ann_other = other.annihilator
969
+
970
+ list_self = []
971
+ list_other = []
972
+
973
+ a = ann_self.order
974
+ b = ann_other.order
975
+
976
+ R = ann_self.parent.base
977
+ K = R.get_field()
978
+
979
+ for j in ann_self.listofpoly:
980
+ list_self.append(K.new(j.rep))
981
+
982
+ for j in ann_other.listofpoly:
983
+ list_other.append(K.new(j.rep))
984
+
985
+ # will be used to reduce the degree
986
+ self_red = [-list_self[i] / list_self[a] for i in range(a)]
987
+
988
+ other_red = [-list_other[i] / list_other[b] for i in range(b)]
989
+
990
+ # coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g)
991
+ coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)]
992
+ coeff_mul[0][0] = K.one
993
+
994
+ # making the ansatz
995
+ lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]]
996
+ lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose()
997
+
998
+ homo_sys = DomainMatrix.zeros((a*b, 1), K)
999
+
1000
+ sol = _find_nonzero_solution(lin_sys, homo_sys)
1001
+
1002
+ # until a non trivial solution is found
1003
+ while sol.is_zero_matrix:
1004
+
1005
+ # updating the coefficients Dx^i(f).Dx^j(g) for next degree
1006
+ for i in range(a - 1, -1, -1):
1007
+ for j in range(b - 1, -1, -1):
1008
+ coeff_mul[i][j + 1] += coeff_mul[i][j]
1009
+ coeff_mul[i + 1][j] += coeff_mul[i][j]
1010
+ if isinstance(coeff_mul[i][j], K.dtype):
1011
+ coeff_mul[i][j] = DMFdiff(coeff_mul[i][j])
1012
+ else:
1013
+ coeff_mul[i][j] = coeff_mul[i][j].diff(self.x)
1014
+
1015
+ # reduce the terms to lower power using annihilators of f, g
1016
+ for i in range(a + 1):
1017
+ if not coeff_mul[i][b].is_zero:
1018
+ for j in range(b):
1019
+ coeff_mul[i][j] += other_red[j] * \
1020
+ coeff_mul[i][b]
1021
+ coeff_mul[i][b] = K.zero
1022
+
1023
+ # not d2 + 1, as that is already covered in previous loop
1024
+ for j in range(b):
1025
+ if not coeff_mul[a][j] == 0:
1026
+ for i in range(a):
1027
+ coeff_mul[i][j] += self_red[i] * \
1028
+ coeff_mul[a][j]
1029
+ coeff_mul[a][j] = K.zero
1030
+
1031
+ lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)])
1032
+ lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose()
1033
+
1034
+ sol = _find_nonzero_solution(lin_sys, homo_sys)
1035
+
1036
+ sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False)
1037
+
1038
+ if not (self._have_init_cond() and other._have_init_cond()):
1039
+ return HolonomicFunction(sol_ann, self.x)
1040
+
1041
+ if self.is_singularics() == False and other.is_singularics() == False:
1042
+
1043
+ # if both the conditions are at same point
1044
+ if self.x0 == other.x0:
1045
+
1046
+ # try to find more initial conditions
1047
+ y0_self = _extend_y0(self, sol_ann.order)
1048
+ y0_other = _extend_y0(other, sol_ann.order)
1049
+ # h(x0) = f(x0) * g(x0)
1050
+ y0 = [y0_self[0] * y0_other[0]]
1051
+
1052
+ # coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg)
1053
+ for i in range(1, min(len(y0_self), len(y0_other))):
1054
+ coeff = [[0 for i in range(i + 1)] for j in range(i + 1)]
1055
+ for j in range(i + 1):
1056
+ for k in range(i + 1):
1057
+ if j + k == i:
1058
+ coeff[j][k] = binomial(i, j)
1059
+
1060
+ sol = 0
1061
+ for j in range(i + 1):
1062
+ for k in range(i + 1):
1063
+ sol += coeff[j][k]* y0_self[j] * y0_other[k]
1064
+
1065
+ y0.append(sol)
1066
+
1067
+ return HolonomicFunction(sol_ann, self.x, self.x0, y0)
1068
+
1069
+ # if the points are different, consider one
1070
+ else:
1071
+
1072
+ selfat0 = self.annihilator.is_singular(0)
1073
+ otherat0 = other.annihilator.is_singular(0)
1074
+
1075
+ if self.x0 == 0 and not selfat0 and not otherat0:
1076
+ return self * other.change_ics(0)
1077
+
1078
+ elif other.x0 == 0 and not selfat0 and not otherat0:
1079
+ return self.change_ics(0) * other
1080
+
1081
+ else:
1082
+ selfatx0 = self.annihilator.is_singular(self.x0)
1083
+ otheratx0 = other.annihilator.is_singular(self.x0)
1084
+
1085
+ if not selfatx0 and not otheratx0:
1086
+ return self * other.change_ics(self.x0)
1087
+
1088
+ else:
1089
+ return self.change_ics(other.x0) * other
1090
+
1091
+ if self.x0 != other.x0:
1092
+ return HolonomicFunction(sol_ann, self.x)
1093
+
1094
+ # if the functions have singular_ics
1095
+ y1 = None
1096
+ y2 = None
1097
+
1098
+ if self.is_singularics() == False and other.is_singularics() == True:
1099
+ _y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
1100
+ y1 = {S.Zero: _y0}
1101
+ y2 = other.y0
1102
+ elif self.is_singularics() == True and other.is_singularics() == False:
1103
+ _y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
1104
+ y1 = self.y0
1105
+ y2 = {S.Zero: _y0}
1106
+ elif self.is_singularics() == True and other.is_singularics() == True:
1107
+ y1 = self.y0
1108
+ y2 = other.y0
1109
+
1110
+ y0 = {}
1111
+ # multiply every possible pair of the series terms
1112
+ for i in y1:
1113
+ for j in y2:
1114
+ k = min(len(y1[i]), len(y2[j]))
1115
+ c = []
1116
+ for a in range(k):
1117
+ s = S.Zero
1118
+ for b in range(a + 1):
1119
+ s += y1[i][b] * y2[j][a - b]
1120
+ c.append(s)
1121
+ if not i + j in y0:
1122
+ y0[i + j] = c
1123
+ else:
1124
+ y0[i + j] = [a + b for a, b in zip(c, y0[i + j])]
1125
+ return HolonomicFunction(sol_ann, self.x, self.x0, y0)
1126
+
1127
+ __rmul__ = __mul__
1128
+
1129
+ def __sub__(self, other):
1130
+ return self + other * -1
1131
+
1132
+ def __rsub__(self, other):
1133
+ return self * -1 + other
1134
+
1135
+ def __neg__(self):
1136
+ return -1 * self
1137
+
1138
+ def __truediv__(self, other):
1139
+ return self * (S.One / other)
1140
+
1141
+ def __pow__(self, n):
1142
+ if self.annihilator.order <= 1:
1143
+ ann = self.annihilator
1144
+ parent = ann.parent
1145
+
1146
+ if self.y0 is None:
1147
+ y0 = None
1148
+ else:
1149
+ y0 = [list(self.y0)[0] ** n]
1150
+
1151
+ p0 = ann.listofpoly[0]
1152
+ p1 = ann.listofpoly[1]
1153
+
1154
+ p0 = (Poly.new(p0, self.x) * n).rep
1155
+
1156
+ sol = [parent.base.to_sympy(i) for i in [p0, p1]]
1157
+ dd = DifferentialOperator(sol, parent)
1158
+ return HolonomicFunction(dd, self.x, self.x0, y0)
1159
+ if n < 0:
1160
+ raise NotHolonomicError("Negative Power on a Holonomic Function")
1161
+ if n == 0:
1162
+ Dx = self.annihilator.parent.derivative_operator
1163
+ return HolonomicFunction(Dx, self.x, S.Zero, [S.One])
1164
+ if n == 1:
1165
+ return self
1166
+ else:
1167
+ if n % 2 == 1:
1168
+ powreduce = self**(n - 1)
1169
+ return powreduce * self
1170
+ elif n % 2 == 0:
1171
+ powreduce = self**(n / 2)
1172
+ return powreduce * powreduce
1173
+
1174
+ def degree(self):
1175
+ """
1176
+ Returns the highest power of `x` in the annihilator.
1177
+ """
1178
+ sol = [i.degree() for i in self.annihilator.listofpoly]
1179
+ return max(sol)
1180
+
1181
+ def composition(self, expr, *args, **kwargs):
1182
+ """
1183
+ Returns function after composition of a holonomic
1184
+ function with an algebraic function. The method cannot compute
1185
+ initial conditions for the result by itself, so they can be also be
1186
+ provided.
1187
+
1188
+ Examples
1189
+ ========
1190
+
1191
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
1192
+ >>> from sympy import QQ
1193
+ >>> from sympy import symbols
1194
+ >>> x = symbols('x')
1195
+ >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
1196
+ >>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
1197
+ HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1])
1198
+ >>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0])
1199
+ HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0])
1200
+
1201
+ See Also
1202
+ ========
1203
+
1204
+ from_hyper
1205
+ """
1206
+
1207
+ R = self.annihilator.parent
1208
+ a = self.annihilator.order
1209
+ diff = expr.diff(self.x)
1210
+ listofpoly = self.annihilator.listofpoly
1211
+
1212
+ for i, j in enumerate(listofpoly):
1213
+ if isinstance(j, self.annihilator.parent.base.dtype):
1214
+ listofpoly[i] = self.annihilator.parent.base.to_sympy(j)
1215
+
1216
+ r = listofpoly[a].subs({self.x:expr})
1217
+ subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)]
1218
+ coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a))
1219
+ coeffs[0] = S.One
1220
+ system = [coeffs]
1221
+ homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose()
1222
+ while True:
1223
+ coeffs_next = [p.diff(self.x) for p in coeffs]
1224
+ for i in range(a - 1):
1225
+ coeffs_next[i + 1] += (coeffs[i] * diff)
1226
+ for i in range(a):
1227
+ coeffs_next[i] += (coeffs[-1] * subs[i] * diff)
1228
+ coeffs = coeffs_next
1229
+ # check for linear relations
1230
+ system.append(coeffs)
1231
+ sol, taus = (Matrix(system).transpose()
1232
+ ).gauss_jordan_solve(homogeneous)
1233
+ if sol.is_zero_matrix is not True:
1234
+ break
1235
+
1236
+ tau = list(taus)[0]
1237
+ sol = sol.subs(tau, 1)
1238
+ sol = _normalize(sol[0:], R, negative=False)
1239
+
1240
+ # if initial conditions are given for the resulting function
1241
+ if args:
1242
+ return HolonomicFunction(sol, self.x, args[0], args[1])
1243
+ return HolonomicFunction(sol, self.x)
1244
+
1245
+ def to_sequence(self, lb=True):
1246
+ r"""
1247
+ Finds recurrence relation for the coefficients in the series expansion
1248
+ of the function about :math:`x_0`, where :math:`x_0` is the point at
1249
+ which the initial condition is stored.
1250
+
1251
+ Explanation
1252
+ ===========
1253
+
1254
+ If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]`
1255
+ is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the
1256
+ smallest ``n`` for which the recurrence holds true.
1257
+
1258
+ If the point :math:`x_0` is regular singular, a list of solutions in
1259
+ the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`.
1260
+ Each tuple in this vector represents a recurrence relation :math:`R`
1261
+ associated with a root of the indicial equation ``p``. Conditions of
1262
+ a different format can also be provided in this case, see the
1263
+ docstring of HolonomicFunction class.
1264
+
1265
+ If it's not possible to numerically compute a initial condition,
1266
+ it is returned as a symbol :math:`C_j`, denoting the coefficient of
1267
+ :math:`(x - x_0)^j` in the power series about :math:`x_0`.
1268
+
1269
+ Examples
1270
+ ========
1271
+
1272
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
1273
+ >>> from sympy import QQ
1274
+ >>> from sympy import symbols, S
1275
+ >>> x = symbols('x')
1276
+ >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
1277
+ >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
1278
+ [(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)]
1279
+ >>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence()
1280
+ [(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)]
1281
+ >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence()
1282
+ [(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)]
1283
+
1284
+ See Also
1285
+ ========
1286
+
1287
+ HolonomicFunction.series
1288
+
1289
+ References
1290
+ ==========
1291
+
1292
+ .. [1] https://hal.inria.fr/inria-00070025/document
1293
+ .. [2] https://www3.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf
1294
+
1295
+ """
1296
+
1297
+ if self.x0 != 0:
1298
+ return self.shift_x(self.x0).to_sequence()
1299
+
1300
+ # check whether a power series exists if the point is singular
1301
+ if self.annihilator.is_singular(self.x0):
1302
+ return self._frobenius(lb=lb)
1303
+
1304
+ dict1 = {}
1305
+ n = Symbol('n', integer=True)
1306
+ dom = self.annihilator.parent.base.dom
1307
+ R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
1308
+
1309
+ # substituting each term of the form `x^k Dx^j` in the
1310
+ # annihilator, according to the formula below:
1311
+ # x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo))
1312
+ # for explanation see [2].
1313
+ for i, j in enumerate(self.annihilator.listofpoly):
1314
+
1315
+ listofdmp = j.all_coeffs()
1316
+ degree = len(listofdmp) - 1
1317
+
1318
+ for k in range(degree + 1):
1319
+ coeff = listofdmp[degree - k]
1320
+
1321
+ if coeff == 0:
1322
+ continue
1323
+
1324
+ if (i - k, k) in dict1:
1325
+ dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i))
1326
+ else:
1327
+ dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i))
1328
+
1329
+
1330
+ sol = []
1331
+ keylist = [i[0] for i in dict1]
1332
+ lower = min(keylist)
1333
+ upper = max(keylist)
1334
+ degree = self.degree()
1335
+
1336
+ # the recurrence relation holds for all values of
1337
+ # n greater than smallest_n, i.e. n >= smallest_n
1338
+ smallest_n = lower + degree
1339
+ dummys = {}
1340
+ eqs = []
1341
+ unknowns = []
1342
+
1343
+ # an appropriate shift of the recurrence
1344
+ for j in range(lower, upper + 1):
1345
+ if j in keylist:
1346
+ temp = S.Zero
1347
+ for k in dict1.keys():
1348
+ if k[0] == j:
1349
+ temp += dict1[k].subs(n, n - lower)
1350
+ sol.append(temp)
1351
+ else:
1352
+ sol.append(S.Zero)
1353
+
1354
+ # the recurrence relation
1355
+ sol = RecurrenceOperator(sol, R)
1356
+
1357
+ # computing the initial conditions for recurrence
1358
+ order = sol.order
1359
+ all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
1360
+ all_roots = all_roots.keys()
1361
+
1362
+ if all_roots:
1363
+ max_root = max(all_roots) + 1
1364
+ smallest_n = max(max_root, smallest_n)
1365
+ order += smallest_n
1366
+
1367
+ y0 = _extend_y0(self, order)
1368
+ u0 = []
1369
+
1370
+ # u(n) = y^n(0)/factorial(n)
1371
+ for i, j in enumerate(y0):
1372
+ u0.append(j / factorial(i))
1373
+
1374
+ # if sufficient conditions can't be computed then
1375
+ # try to use the series method i.e.
1376
+ # equate the coefficients of x^k in the equation formed by
1377
+ # substituting the series in differential equation, to zero.
1378
+ if len(u0) < order:
1379
+
1380
+ for i in range(degree):
1381
+ eq = S.Zero
1382
+
1383
+ for j in dict1:
1384
+
1385
+ if i + j[0] < 0:
1386
+ dummys[i + j[0]] = S.Zero
1387
+
1388
+ elif i + j[0] < len(u0):
1389
+ dummys[i + j[0]] = u0[i + j[0]]
1390
+
1391
+ elif not i + j[0] in dummys:
1392
+ dummys[i + j[0]] = Symbol('C_%s' %(i + j[0]))
1393
+ unknowns.append(dummys[i + j[0]])
1394
+
1395
+ if j[1] <= i:
1396
+ eq += dict1[j].subs(n, i) * dummys[i + j[0]]
1397
+
1398
+ eqs.append(eq)
1399
+
1400
+ # solve the system of equations formed
1401
+ soleqs = solve(eqs, *unknowns)
1402
+
1403
+ if isinstance(soleqs, dict):
1404
+
1405
+ for i in range(len(u0), order):
1406
+
1407
+ if i not in dummys:
1408
+ dummys[i] = Symbol('C_%s' %i)
1409
+
1410
+ if dummys[i] in soleqs:
1411
+ u0.append(soleqs[dummys[i]])
1412
+
1413
+ else:
1414
+ u0.append(dummys[i])
1415
+
1416
+ if lb:
1417
+ return [(HolonomicSequence(sol, u0), smallest_n)]
1418
+ return [HolonomicSequence(sol, u0)]
1419
+
1420
+ for i in range(len(u0), order):
1421
+
1422
+ if i not in dummys:
1423
+ dummys[i] = Symbol('C_%s' %i)
1424
+
1425
+ s = False
1426
+ for j in soleqs:
1427
+ if dummys[i] in j:
1428
+ u0.append(j[dummys[i]])
1429
+ s = True
1430
+ if not s:
1431
+ u0.append(dummys[i])
1432
+
1433
+ if lb:
1434
+ return [(HolonomicSequence(sol, u0), smallest_n)]
1435
+
1436
+ return [HolonomicSequence(sol, u0)]
1437
+
1438
+ def _frobenius(self, lb=True):
1439
+ # compute the roots of indicial equation
1440
+ indicialroots = self._indicial()
1441
+
1442
+ reals = []
1443
+ compl = []
1444
+ for i in ordered(indicialroots.keys()):
1445
+ if i.is_real:
1446
+ reals.extend([i] * indicialroots[i])
1447
+ else:
1448
+ a, b = i.as_real_imag()
1449
+ compl.extend([(i, a, b)] * indicialroots[i])
1450
+
1451
+ # sort the roots for a fixed ordering of solution
1452
+ compl.sort(key=lambda x : x[1])
1453
+ compl.sort(key=lambda x : x[2])
1454
+ reals.sort()
1455
+
1456
+ # grouping the roots, roots differ by an integer are put in the same group.
1457
+ grp = []
1458
+
1459
+ for i in reals:
1460
+ intdiff = False
1461
+ if len(grp) == 0:
1462
+ grp.append([i])
1463
+ continue
1464
+ for j in grp:
1465
+ if int(j[0] - i) == j[0] - i:
1466
+ j.append(i)
1467
+ intdiff = True
1468
+ break
1469
+ if not intdiff:
1470
+ grp.append([i])
1471
+
1472
+ # True if none of the roots differ by an integer i.e.
1473
+ # each element in group have only one member
1474
+ independent = True if all(len(i) == 1 for i in grp) else False
1475
+
1476
+ allpos = all(i >= 0 for i in reals)
1477
+ allint = all(int(i) == i for i in reals)
1478
+
1479
+ # if initial conditions are provided
1480
+ # then use them.
1481
+ if self.is_singularics() == True:
1482
+ rootstoconsider = []
1483
+ for i in ordered(self.y0.keys()):
1484
+ for j in ordered(indicialroots.keys()):
1485
+ if equal_valued(j, i):
1486
+ rootstoconsider.append(i)
1487
+
1488
+ elif allpos and allint:
1489
+ rootstoconsider = [min(reals)]
1490
+
1491
+ elif independent:
1492
+ rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl]
1493
+
1494
+ elif not allint:
1495
+ rootstoconsider = []
1496
+ for i in reals:
1497
+ if not int(i) == i:
1498
+ rootstoconsider.append(i)
1499
+
1500
+ elif not allpos:
1501
+
1502
+ if not self._have_init_cond() or S(self.y0[0]).is_finite == False:
1503
+ rootstoconsider = [min(reals)]
1504
+
1505
+ else:
1506
+ posroots = []
1507
+ for i in reals:
1508
+ if i >= 0:
1509
+ posroots.append(i)
1510
+ rootstoconsider = [min(posroots)]
1511
+
1512
+ n = Symbol('n', integer=True)
1513
+ dom = self.annihilator.parent.base.dom
1514
+ R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
1515
+
1516
+ finalsol = []
1517
+ char = ord('C')
1518
+
1519
+ for p in rootstoconsider:
1520
+ dict1 = {}
1521
+
1522
+ for i, j in enumerate(self.annihilator.listofpoly):
1523
+
1524
+ listofdmp = j.all_coeffs()
1525
+ degree = len(listofdmp) - 1
1526
+
1527
+ for k in range(degree + 1):
1528
+ coeff = listofdmp[degree - k]
1529
+
1530
+ if coeff == 0:
1531
+ continue
1532
+
1533
+ if (i - k, k - i) in dict1:
1534
+ dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
1535
+ else:
1536
+ dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
1537
+
1538
+ sol = []
1539
+ keylist = [i[0] for i in dict1]
1540
+ lower = min(keylist)
1541
+ upper = max(keylist)
1542
+ degree = max([i[1] for i in dict1])
1543
+ degree2 = min([i[1] for i in dict1])
1544
+
1545
+ smallest_n = lower + degree
1546
+ dummys = {}
1547
+ eqs = []
1548
+ unknowns = []
1549
+
1550
+ for j in range(lower, upper + 1):
1551
+ if j in keylist:
1552
+ temp = S.Zero
1553
+ for k in dict1.keys():
1554
+ if k[0] == j:
1555
+ temp += dict1[k].subs(n, n - lower)
1556
+ sol.append(temp)
1557
+ else:
1558
+ sol.append(S.Zero)
1559
+
1560
+ # the recurrence relation
1561
+ sol = RecurrenceOperator(sol, R)
1562
+
1563
+ # computing the initial conditions for recurrence
1564
+ order = sol.order
1565
+ all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
1566
+ all_roots = all_roots.keys()
1567
+
1568
+ if all_roots:
1569
+ max_root = max(all_roots) + 1
1570
+ smallest_n = max(max_root, smallest_n)
1571
+ order += smallest_n
1572
+
1573
+ u0 = []
1574
+
1575
+ if self.is_singularics() == True:
1576
+ u0 = self.y0[p]
1577
+
1578
+ elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1:
1579
+ y0 = _extend_y0(self, order + int(p))
1580
+ # u(n) = y^n(0)/factorial(n)
1581
+ if len(y0) > int(p):
1582
+ for i in range(int(p), len(y0)):
1583
+ u0.append(y0[i] / factorial(i))
1584
+
1585
+ if len(u0) < order:
1586
+
1587
+ for i in range(degree2, degree):
1588
+ eq = S.Zero
1589
+
1590
+ for j in dict1:
1591
+ if i + j[0] < 0:
1592
+ dummys[i + j[0]] = S.Zero
1593
+
1594
+ elif i + j[0] < len(u0):
1595
+ dummys[i + j[0]] = u0[i + j[0]]
1596
+
1597
+ elif not i + j[0] in dummys:
1598
+ letter = chr(char) + '_%s' %(i + j[0])
1599
+ dummys[i + j[0]] = Symbol(letter)
1600
+ unknowns.append(dummys[i + j[0]])
1601
+
1602
+ if j[1] <= i:
1603
+ eq += dict1[j].subs(n, i) * dummys[i + j[0]]
1604
+
1605
+ eqs.append(eq)
1606
+
1607
+ # solve the system of equations formed
1608
+ soleqs = solve(eqs, *unknowns)
1609
+
1610
+ if isinstance(soleqs, dict):
1611
+
1612
+ for i in range(len(u0), order):
1613
+
1614
+ if i not in dummys:
1615
+ letter = chr(char) + '_%s' %i
1616
+ dummys[i] = Symbol(letter)
1617
+
1618
+ if dummys[i] in soleqs:
1619
+ u0.append(soleqs[dummys[i]])
1620
+
1621
+ else:
1622
+ u0.append(dummys[i])
1623
+
1624
+ if lb:
1625
+ finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
1626
+ continue
1627
+ else:
1628
+ finalsol.append((HolonomicSequence(sol, u0), p))
1629
+ continue
1630
+
1631
+ for i in range(len(u0), order):
1632
+
1633
+ if i not in dummys:
1634
+ letter = chr(char) + '_%s' %i
1635
+ dummys[i] = Symbol(letter)
1636
+
1637
+ s = False
1638
+ for j in soleqs:
1639
+ if dummys[i] in j:
1640
+ u0.append(j[dummys[i]])
1641
+ s = True
1642
+ if not s:
1643
+ u0.append(dummys[i])
1644
+ if lb:
1645
+ finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
1646
+
1647
+ else:
1648
+ finalsol.append((HolonomicSequence(sol, u0), p))
1649
+ char += 1
1650
+ return finalsol
1651
+
1652
+ def series(self, n=6, coefficient=False, order=True, _recur=None):
1653
+ r"""
1654
+ Finds the power series expansion of given holonomic function about :math:`x_0`.
1655
+
1656
+ Explanation
1657
+ ===========
1658
+
1659
+ A list of series might be returned if :math:`x_0` is a regular point with
1660
+ multiple roots of the indicial equation.
1661
+
1662
+ Examples
1663
+ ========
1664
+
1665
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
1666
+ >>> from sympy import QQ
1667
+ >>> from sympy import symbols
1668
+ >>> x = symbols('x')
1669
+ >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
1670
+ >>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x
1671
+ 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
1672
+ >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x)
1673
+ x - x**3/6 + x**5/120 - x**7/5040 + O(x**8)
1674
+
1675
+ See Also
1676
+ ========
1677
+
1678
+ HolonomicFunction.to_sequence
1679
+ """
1680
+
1681
+ if _recur is None:
1682
+ recurrence = self.to_sequence()
1683
+ else:
1684
+ recurrence = _recur
1685
+
1686
+ if isinstance(recurrence, tuple) and len(recurrence) == 2:
1687
+ recurrence = recurrence[0]
1688
+ constantpower = 0
1689
+ elif isinstance(recurrence, tuple) and len(recurrence) == 3:
1690
+ constantpower = recurrence[1]
1691
+ recurrence = recurrence[0]
1692
+
1693
+ elif len(recurrence) == 1 and len(recurrence[0]) == 2:
1694
+ recurrence = recurrence[0][0]
1695
+ constantpower = 0
1696
+ elif len(recurrence) == 1 and len(recurrence[0]) == 3:
1697
+ constantpower = recurrence[0][1]
1698
+ recurrence = recurrence[0][0]
1699
+ else:
1700
+ sol = []
1701
+ for i in recurrence:
1702
+ sol.append(self.series(_recur=i))
1703
+ return sol
1704
+
1705
+ n = n - int(constantpower)
1706
+ l = len(recurrence.u0) - 1
1707
+ k = recurrence.recurrence.order
1708
+ x = self.x
1709
+ x0 = self.x0
1710
+ seq_dmp = recurrence.recurrence.listofpoly
1711
+ R = recurrence.recurrence.parent.base
1712
+ K = R.get_field()
1713
+ seq = []
1714
+
1715
+ for i, j in enumerate(seq_dmp):
1716
+ seq.append(K.new(j.rep))
1717
+
1718
+ sub = [-seq[i] / seq[k] for i in range(k)]
1719
+ sol = list(recurrence.u0)
1720
+
1721
+ if l + 1 >= n:
1722
+ pass
1723
+ else:
1724
+ # use the initial conditions to find the next term
1725
+ for i in range(l + 1 - k, n - k):
1726
+ coeff = S.Zero
1727
+ for j in range(k):
1728
+ if i + j >= 0:
1729
+ coeff += DMFsubs(sub[j], i) * sol[i + j]
1730
+ sol.append(coeff)
1731
+
1732
+ if coefficient:
1733
+ return sol
1734
+
1735
+ ser = S.Zero
1736
+ for i, j in enumerate(sol):
1737
+ ser += x**(i + constantpower) * j
1738
+ if order:
1739
+ ser += Order(x**(n + int(constantpower)), x)
1740
+ if x0 != 0:
1741
+ return ser.subs(x, x - x0)
1742
+ return ser
1743
+
1744
+ def _indicial(self):
1745
+ """
1746
+ Computes roots of the Indicial equation.
1747
+ """
1748
+
1749
+ if self.x0 != 0:
1750
+ return self.shift_x(self.x0)._indicial()
1751
+
1752
+ list_coeff = self.annihilator.listofpoly
1753
+ R = self.annihilator.parent.base
1754
+ x = self.x
1755
+ s = R.zero
1756
+ y = R.one
1757
+
1758
+ def _pole_degree(poly):
1759
+ root_all = roots(R.to_sympy(poly), x, filter='Z')
1760
+ if 0 in root_all.keys():
1761
+ return root_all[0]
1762
+ else:
1763
+ return 0
1764
+
1765
+ degree = [j.degree() for j in list_coeff]
1766
+ degree = max(degree)
1767
+ inf = 10 * (max(1, degree) + max(1, self.annihilator.order))
1768
+
1769
+ deg = lambda q: inf if q.is_zero else _pole_degree(q)
1770
+ b = deg(list_coeff[0])
1771
+
1772
+ for j in range(1, len(list_coeff)):
1773
+ b = min(b, deg(list_coeff[j]) - j)
1774
+
1775
+ for i, j in enumerate(list_coeff):
1776
+ listofdmp = j.all_coeffs()
1777
+ degree = len(listofdmp) - 1
1778
+ if - i - b <= 0 and degree - i - b >= 0:
1779
+ s = s + listofdmp[degree - i - b] * y
1780
+ y *= x - i
1781
+
1782
+ return roots(R.to_sympy(s), x)
1783
+
1784
+ def evalf(self, points, method='RK4', h=0.05, derivatives=False):
1785
+ r"""
1786
+ Finds numerical value of a holonomic function using numerical methods.
1787
+ (RK4 by default). A set of points (real or complex) must be provided
1788
+ which will be the path for the numerical integration.
1789
+
1790
+ Explanation
1791
+ ===========
1792
+
1793
+ The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical
1794
+ values will be computed at each point in this order
1795
+ :math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`.
1796
+
1797
+ Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list.
1798
+
1799
+ Examples
1800
+ ========
1801
+
1802
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
1803
+ >>> from sympy import QQ
1804
+ >>> from sympy import symbols
1805
+ >>> x = symbols('x')
1806
+ >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
1807
+
1808
+ A straight line on the real axis from (0 to 1)
1809
+
1810
+ >>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
1811
+
1812
+ Runge-Kutta 4th order on e^x from 0.1 to 1.
1813
+ Exact solution at 1 is 2.71828182845905
1814
+
1815
+ >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r)
1816
+ [1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069,
1817
+ 1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232,
1818
+ 2.45960141378007, 2.71827974413517]
1819
+
1820
+ Euler's method for the same
1821
+
1822
+ >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler')
1823
+ [1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881,
1824
+ 2.357947691, 2.5937424601]
1825
+
1826
+ One can also observe that the value obtained using Runge-Kutta 4th order
1827
+ is much more accurate than Euler's method.
1828
+ """
1829
+
1830
+ from sympy.holonomic.numerical import _evalf
1831
+ lp = False
1832
+
1833
+ # if a point `b` is given instead of a mesh
1834
+ if not hasattr(points, "__iter__"):
1835
+ lp = True
1836
+ b = S(points)
1837
+ if self.x0 == b:
1838
+ return _evalf(self, [b], method=method, derivatives=derivatives)[-1]
1839
+
1840
+ if not b.is_Number:
1841
+ raise NotImplementedError
1842
+
1843
+ a = self.x0
1844
+ if a > b:
1845
+ h = -h
1846
+ n = int((b - a) / h)
1847
+ points = [a + h]
1848
+ for i in range(n - 1):
1849
+ points.append(points[-1] + h)
1850
+
1851
+ for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x):
1852
+ if i == self.x0 or i in points:
1853
+ raise SingularityError(self, i)
1854
+
1855
+ if lp:
1856
+ return _evalf(self, points, method=method, derivatives=derivatives)[-1]
1857
+ return _evalf(self, points, method=method, derivatives=derivatives)
1858
+
1859
+ def change_x(self, z):
1860
+ """
1861
+ Changes only the variable of Holonomic Function, for internal
1862
+ purposes. For composition use HolonomicFunction.composition()
1863
+ """
1864
+
1865
+ dom = self.annihilator.parent.base.dom
1866
+ R = dom.old_poly_ring(z)
1867
+ parent, _ = DifferentialOperators(R, 'Dx')
1868
+ sol = []
1869
+ for j in self.annihilator.listofpoly:
1870
+ sol.append(R(j.rep))
1871
+ sol = DifferentialOperator(sol, parent)
1872
+ return HolonomicFunction(sol, z, self.x0, self.y0)
1873
+
1874
+ def shift_x(self, a):
1875
+ """
1876
+ Substitute `x + a` for `x`.
1877
+ """
1878
+
1879
+ x = self.x
1880
+ listaftershift = self.annihilator.listofpoly
1881
+ base = self.annihilator.parent.base
1882
+
1883
+ sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift]
1884
+ sol = DifferentialOperator(sol, self.annihilator.parent)
1885
+ x0 = self.x0 - a
1886
+ if not self._have_init_cond():
1887
+ return HolonomicFunction(sol, x)
1888
+ return HolonomicFunction(sol, x, x0, self.y0)
1889
+
1890
+ def to_hyper(self, as_list=False, _recur=None):
1891
+ r"""
1892
+ Returns a hypergeometric function (or linear combination of them)
1893
+ representing the given holonomic function.
1894
+
1895
+ Explanation
1896
+ ===========
1897
+
1898
+ Returns an answer of the form:
1899
+ `a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots`
1900
+
1901
+ This is very useful as one can now use ``hyperexpand`` to find the
1902
+ symbolic expressions/functions.
1903
+
1904
+ Examples
1905
+ ========
1906
+
1907
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
1908
+ >>> from sympy import ZZ
1909
+ >>> from sympy import symbols
1910
+ >>> x = symbols('x')
1911
+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
1912
+ >>> # sin(x)
1913
+ >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper()
1914
+ x*hyper((), (3/2,), -x**2/4)
1915
+ >>> # exp(x)
1916
+ >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper()
1917
+ hyper((), (), x)
1918
+
1919
+ See Also
1920
+ ========
1921
+
1922
+ from_hyper, from_meijerg
1923
+ """
1924
+
1925
+ if _recur is None:
1926
+ recurrence = self.to_sequence()
1927
+ else:
1928
+ recurrence = _recur
1929
+
1930
+ if isinstance(recurrence, tuple) and len(recurrence) == 2:
1931
+ smallest_n = recurrence[1]
1932
+ recurrence = recurrence[0]
1933
+ constantpower = 0
1934
+ elif isinstance(recurrence, tuple) and len(recurrence) == 3:
1935
+ smallest_n = recurrence[2]
1936
+ constantpower = recurrence[1]
1937
+ recurrence = recurrence[0]
1938
+ elif len(recurrence) == 1 and len(recurrence[0]) == 2:
1939
+ smallest_n = recurrence[0][1]
1940
+ recurrence = recurrence[0][0]
1941
+ constantpower = 0
1942
+ elif len(recurrence) == 1 and len(recurrence[0]) == 3:
1943
+ smallest_n = recurrence[0][2]
1944
+ constantpower = recurrence[0][1]
1945
+ recurrence = recurrence[0][0]
1946
+ else:
1947
+ sol = self.to_hyper(as_list=as_list, _recur=recurrence[0])
1948
+ for i in recurrence[1:]:
1949
+ sol += self.to_hyper(as_list=as_list, _recur=i)
1950
+ return sol
1951
+
1952
+ u0 = recurrence.u0
1953
+ r = recurrence.recurrence
1954
+ x = self.x
1955
+ x0 = self.x0
1956
+
1957
+ # order of the recurrence relation
1958
+ m = r.order
1959
+
1960
+ # when no recurrence exists, and the power series have finite terms
1961
+ if m == 0:
1962
+ nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R')
1963
+
1964
+ sol = S.Zero
1965
+ for j, i in enumerate(nonzeroterms):
1966
+
1967
+ if i < 0 or int(i) != i:
1968
+ continue
1969
+
1970
+ i = int(i)
1971
+ if i < len(u0):
1972
+ if isinstance(u0[i], (PolyElement, FracElement)):
1973
+ u0[i] = u0[i].as_expr()
1974
+ sol += u0[i] * x**i
1975
+
1976
+ else:
1977
+ sol += Symbol('C_%s' %j) * x**i
1978
+
1979
+ if isinstance(sol, (PolyElement, FracElement)):
1980
+ sol = sol.as_expr() * x**constantpower
1981
+ else:
1982
+ sol = sol * x**constantpower
1983
+ if as_list:
1984
+ if x0 != 0:
1985
+ return [(sol.subs(x, x - x0), )]
1986
+ return [(sol, )]
1987
+ if x0 != 0:
1988
+ return sol.subs(x, x - x0)
1989
+ return sol
1990
+
1991
+ if smallest_n + m > len(u0):
1992
+ raise NotImplementedError("Can't compute sufficient Initial Conditions")
1993
+
1994
+ # check if the recurrence represents a hypergeometric series
1995
+ is_hyper = True
1996
+
1997
+ for i in range(1, len(r.listofpoly)-1):
1998
+ if r.listofpoly[i] != r.parent.base.zero:
1999
+ is_hyper = False
2000
+ break
2001
+
2002
+ if not is_hyper:
2003
+ raise NotHyperSeriesError(self, self.x0)
2004
+
2005
+ a = r.listofpoly[0]
2006
+ b = r.listofpoly[-1]
2007
+
2008
+ # the constant multiple of argument of hypergeometric function
2009
+ if isinstance(a.rep[0], (PolyElement, FracElement)):
2010
+ c = - (S(a.rep[0].as_expr()) * m**(a.degree())) / (S(b.rep[0].as_expr()) * m**(b.degree()))
2011
+ else:
2012
+ c = - (S(a.rep[0]) * m**(a.degree())) / (S(b.rep[0]) * m**(b.degree()))
2013
+
2014
+ sol = 0
2015
+
2016
+ arg1 = roots(r.parent.base.to_sympy(a), recurrence.n)
2017
+ arg2 = roots(r.parent.base.to_sympy(b), recurrence.n)
2018
+
2019
+ # iterate through the initial conditions to find
2020
+ # the hypergeometric representation of the given
2021
+ # function.
2022
+ # The answer will be a linear combination
2023
+ # of different hypergeometric series which satisfies
2024
+ # the recurrence.
2025
+ if as_list:
2026
+ listofsol = []
2027
+ for i in range(smallest_n + m):
2028
+
2029
+ # if the recurrence relation doesn't hold for `n = i`,
2030
+ # then a Hypergeometric representation doesn't exist.
2031
+ # add the algebraic term a * x**i to the solution,
2032
+ # where a is u0[i]
2033
+ if i < smallest_n:
2034
+ if as_list:
2035
+ listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), ))
2036
+ else:
2037
+ sol += S(u0[i]) * x**i
2038
+ continue
2039
+
2040
+ # if the coefficient u0[i] is zero, then the
2041
+ # independent hypergeomtric series starting with
2042
+ # x**i is not a part of the answer.
2043
+ if S(u0[i]) == 0:
2044
+ continue
2045
+
2046
+ ap = []
2047
+ bq = []
2048
+
2049
+ # substitute m * n + i for n
2050
+ for k in ordered(arg1.keys()):
2051
+ ap.extend([nsimplify((i - k) / m)] * arg1[k])
2052
+
2053
+ for k in ordered(arg2.keys()):
2054
+ bq.extend([nsimplify((i - k) / m)] * arg2[k])
2055
+
2056
+ # convention of (k + 1) in the denominator
2057
+ if 1 in bq:
2058
+ bq.remove(1)
2059
+ else:
2060
+ ap.append(1)
2061
+ if as_list:
2062
+ listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0)))
2063
+ else:
2064
+ sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i
2065
+ if as_list:
2066
+ return listofsol
2067
+ sol = sol * x**constantpower
2068
+ if x0 != 0:
2069
+ return sol.subs(x, x - x0)
2070
+
2071
+ return sol
2072
+
2073
+ def to_expr(self):
2074
+ """
2075
+ Converts a Holonomic Function back to elementary functions.
2076
+
2077
+ Examples
2078
+ ========
2079
+
2080
+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
2081
+ >>> from sympy import ZZ
2082
+ >>> from sympy import symbols, S
2083
+ >>> x = symbols('x')
2084
+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
2085
+ >>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr()
2086
+ besselj(1, x)
2087
+ >>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr()
2088
+ x*log(x + 1) + log(x + 1) + 1
2089
+
2090
+ """
2091
+
2092
+ return hyperexpand(self.to_hyper()).simplify()
2093
+
2094
+ def change_ics(self, b, lenics=None):
2095
+ """
2096
+ Changes the point `x0` to ``b`` for initial conditions.
2097
+
2098
+ Examples
2099
+ ========
2100
+
2101
+ >>> from sympy.holonomic import expr_to_holonomic
2102
+ >>> from sympy import symbols, sin, exp
2103
+ >>> x = symbols('x')
2104
+
2105
+ >>> expr_to_holonomic(sin(x)).change_ics(1)
2106
+ HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)])
2107
+
2108
+ >>> expr_to_holonomic(exp(x)).change_ics(2)
2109
+ HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)])
2110
+ """
2111
+
2112
+ symbolic = True
2113
+
2114
+ if lenics is None and len(self.y0) > self.annihilator.order:
2115
+ lenics = len(self.y0)
2116
+ dom = self.annihilator.parent.base.domain
2117
+
2118
+ try:
2119
+ sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom)
2120
+ except (NotPowerSeriesError, NotHyperSeriesError):
2121
+ symbolic = False
2122
+
2123
+ if symbolic and sol.x0 == b:
2124
+ return sol
2125
+
2126
+ y0 = self.evalf(b, derivatives=True)
2127
+ return HolonomicFunction(self.annihilator, self.x, b, y0)
2128
+
2129
+ def to_meijerg(self):
2130
+ """
2131
+ Returns a linear combination of Meijer G-functions.
2132
+
2133
+ Examples
2134
+ ========
2135
+
2136
+ >>> from sympy.holonomic import expr_to_holonomic
2137
+ >>> from sympy import sin, cos, hyperexpand, log, symbols
2138
+ >>> x = symbols('x')
2139
+ >>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg())
2140
+ sin(x) + cos(x)
2141
+ >>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify()
2142
+ log(x)
2143
+
2144
+ See Also
2145
+ ========
2146
+
2147
+ to_hyper
2148
+ """
2149
+
2150
+ # convert to hypergeometric first
2151
+ rep = self.to_hyper(as_list=True)
2152
+ sol = S.Zero
2153
+
2154
+ for i in rep:
2155
+ if len(i) == 1:
2156
+ sol += i[0]
2157
+
2158
+ elif len(i) == 2:
2159
+ sol += i[0] * _hyper_to_meijerg(i[1])
2160
+
2161
+ return sol
2162
+
2163
+
2164
+ def from_hyper(func, x0=0, evalf=False):
2165
+ r"""
2166
+ Converts a hypergeometric function to holonomic.
2167
+ ``func`` is the Hypergeometric Function and ``x0`` is the point at
2168
+ which initial conditions are required.
2169
+
2170
+ Examples
2171
+ ========
2172
+
2173
+ >>> from sympy.holonomic.holonomic import from_hyper
2174
+ >>> from sympy import symbols, hyper, S
2175
+ >>> x = symbols('x')
2176
+ >>> from_hyper(hyper([], [S(3)/2], x**2/4))
2177
+ HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)])
2178
+ """
2179
+
2180
+ a = func.ap
2181
+ b = func.bq
2182
+ z = func.args[2]
2183
+ x = z.atoms(Symbol).pop()
2184
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
2185
+
2186
+ # generalized hypergeometric differential equation
2187
+ xDx = x*Dx
2188
+ r1 = 1
2189
+ for ai in a: # XXX gives sympify error if Mul is used with list of all factors
2190
+ r1 *= xDx + ai
2191
+ xDx_1 = xDx - 1
2192
+ # r2 = Mul(*([Dx] + [xDx_1 + bi for bi in b])) # XXX gives sympify error
2193
+ r2 = Dx
2194
+ for bi in b:
2195
+ r2 *= xDx_1 + bi
2196
+ sol = r1 - r2
2197
+
2198
+ simp = hyperexpand(func)
2199
+
2200
+ if simp in (Infinity, NegativeInfinity):
2201
+ return HolonomicFunction(sol, x).composition(z)
2202
+
2203
+ def _find_conditions(simp, x, x0, order, evalf=False):
2204
+ y0 = []
2205
+ for i in range(order):
2206
+ if evalf:
2207
+ val = simp.subs(x, x0).evalf()
2208
+ else:
2209
+ val = simp.subs(x, x0)
2210
+ # return None if it is Infinite or NaN
2211
+ if val.is_finite is False or isinstance(val, NaN):
2212
+ return None
2213
+ y0.append(val)
2214
+ simp = simp.diff(x)
2215
+ return y0
2216
+
2217
+ # if the function is known symbolically
2218
+ if not isinstance(simp, hyper):
2219
+ y0 = _find_conditions(simp, x, x0, sol.order)
2220
+ while not y0:
2221
+ # if values don't exist at 0, then try to find initial
2222
+ # conditions at 1. If it doesn't exist at 1 too then
2223
+ # try 2 and so on.
2224
+ x0 += 1
2225
+ y0 = _find_conditions(simp, x, x0, sol.order)
2226
+
2227
+ return HolonomicFunction(sol, x).composition(z, x0, y0)
2228
+
2229
+ if isinstance(simp, hyper):
2230
+ x0 = 1
2231
+ # use evalf if the function can't be simplified
2232
+ y0 = _find_conditions(simp, x, x0, sol.order, evalf)
2233
+ while not y0:
2234
+ x0 += 1
2235
+ y0 = _find_conditions(simp, x, x0, sol.order, evalf)
2236
+ return HolonomicFunction(sol, x).composition(z, x0, y0)
2237
+
2238
+ return HolonomicFunction(sol, x).composition(z)
2239
+
2240
+
2241
+ def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ):
2242
+ """
2243
+ Converts a Meijer G-function to Holonomic.
2244
+ ``func`` is the G-Function and ``x0`` is the point at
2245
+ which initial conditions are required.
2246
+
2247
+ Examples
2248
+ ========
2249
+
2250
+ >>> from sympy.holonomic.holonomic import from_meijerg
2251
+ >>> from sympy import symbols, meijerg, S
2252
+ >>> x = symbols('x')
2253
+ >>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4))
2254
+ HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)])
2255
+ """
2256
+
2257
+ a = func.ap
2258
+ b = func.bq
2259
+ n = len(func.an)
2260
+ m = len(func.bm)
2261
+ p = len(a)
2262
+ z = func.args[2]
2263
+ x = z.atoms(Symbol).pop()
2264
+ R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx')
2265
+
2266
+ # compute the differential equation satisfied by the
2267
+ # Meijer G-function.
2268
+ xDx = x*Dx
2269
+ xDx1 = xDx + 1
2270
+ r1 = x*(-1)**(m + n - p)
2271
+ for ai in a: # XXX gives sympify error if args given in list
2272
+ r1 *= xDx1 - ai
2273
+ # r2 = Mul(*[xDx - bi for bi in b]) # gives sympify error
2274
+ r2 = 1
2275
+ for bi in b:
2276
+ r2 *= xDx - bi
2277
+ sol = r1 - r2
2278
+
2279
+ if not initcond:
2280
+ return HolonomicFunction(sol, x).composition(z)
2281
+
2282
+ simp = hyperexpand(func)
2283
+
2284
+ if simp in (Infinity, NegativeInfinity):
2285
+ return HolonomicFunction(sol, x).composition(z)
2286
+
2287
+ def _find_conditions(simp, x, x0, order, evalf=False):
2288
+ y0 = []
2289
+ for i in range(order):
2290
+ if evalf:
2291
+ val = simp.subs(x, x0).evalf()
2292
+ else:
2293
+ val = simp.subs(x, x0)
2294
+ if val.is_finite is False or isinstance(val, NaN):
2295
+ return None
2296
+ y0.append(val)
2297
+ simp = simp.diff(x)
2298
+ return y0
2299
+
2300
+ # computing initial conditions
2301
+ if not isinstance(simp, meijerg):
2302
+ y0 = _find_conditions(simp, x, x0, sol.order)
2303
+ while not y0:
2304
+ x0 += 1
2305
+ y0 = _find_conditions(simp, x, x0, sol.order)
2306
+
2307
+ return HolonomicFunction(sol, x).composition(z, x0, y0)
2308
+
2309
+ if isinstance(simp, meijerg):
2310
+ x0 = 1
2311
+ y0 = _find_conditions(simp, x, x0, sol.order, evalf)
2312
+ while not y0:
2313
+ x0 += 1
2314
+ y0 = _find_conditions(simp, x, x0, sol.order, evalf)
2315
+
2316
+ return HolonomicFunction(sol, x).composition(z, x0, y0)
2317
+
2318
+ return HolonomicFunction(sol, x).composition(z)
2319
+
2320
+
2321
+ x_1 = Dummy('x_1')
2322
+ _lookup_table = None
2323
+ domain_for_table = None
2324
+ from sympy.integrals.meijerint import _mytype
2325
+
2326
+
2327
+ def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True):
2328
+ """
2329
+ Converts a function or an expression to a holonomic function.
2330
+
2331
+ Parameters
2332
+ ==========
2333
+
2334
+ func:
2335
+ The expression to be converted.
2336
+ x:
2337
+ variable for the function.
2338
+ x0:
2339
+ point at which initial condition must be computed.
2340
+ y0:
2341
+ One can optionally provide initial condition if the method
2342
+ is not able to do it automatically.
2343
+ lenics:
2344
+ Number of terms in the initial condition. By default it is
2345
+ equal to the order of the annihilator.
2346
+ domain:
2347
+ Ground domain for the polynomials in ``x`` appearing as coefficients
2348
+ in the annihilator.
2349
+ initcond:
2350
+ Set it false if you do not want the initial conditions to be computed.
2351
+
2352
+ Examples
2353
+ ========
2354
+
2355
+ >>> from sympy.holonomic.holonomic import expr_to_holonomic
2356
+ >>> from sympy import sin, exp, symbols
2357
+ >>> x = symbols('x')
2358
+ >>> expr_to_holonomic(sin(x))
2359
+ HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1])
2360
+ >>> expr_to_holonomic(exp(x))
2361
+ HolonomicFunction((-1) + (1)*Dx, x, 0, [1])
2362
+
2363
+ See Also
2364
+ ========
2365
+
2366
+ sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table
2367
+ """
2368
+ func = sympify(func)
2369
+ syms = func.free_symbols
2370
+
2371
+ if not x:
2372
+ if len(syms) == 1:
2373
+ x= syms.pop()
2374
+ else:
2375
+ raise ValueError("Specify the variable for the function")
2376
+ elif x in syms:
2377
+ syms.remove(x)
2378
+
2379
+ extra_syms = list(syms)
2380
+
2381
+ if domain is None:
2382
+ if func.has(Float):
2383
+ domain = RR
2384
+ else:
2385
+ domain = QQ
2386
+ if len(extra_syms) != 0:
2387
+ domain = domain[extra_syms].get_field()
2388
+
2389
+ # try to convert if the function is polynomial or rational
2390
+ solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond)
2391
+ if solpoly:
2392
+ return solpoly
2393
+
2394
+ # create the lookup table
2395
+ global _lookup_table, domain_for_table
2396
+ if not _lookup_table:
2397
+ domain_for_table = domain
2398
+ _lookup_table = {}
2399
+ _create_table(_lookup_table, domain=domain)
2400
+ elif domain != domain_for_table:
2401
+ domain_for_table = domain
2402
+ _lookup_table = {}
2403
+ _create_table(_lookup_table, domain=domain)
2404
+
2405
+ # use the table directly to convert to Holonomic
2406
+ if func.is_Function:
2407
+ f = func.subs(x, x_1)
2408
+ t = _mytype(f, x_1)
2409
+ if t in _lookup_table:
2410
+ l = _lookup_table[t]
2411
+ sol = l[0][1].change_x(x)
2412
+ else:
2413
+ sol = _convert_meijerint(func, x, initcond=False, domain=domain)
2414
+ if not sol:
2415
+ raise NotImplementedError
2416
+ if y0:
2417
+ sol.y0 = y0
2418
+ if y0 or not initcond:
2419
+ sol.x0 = x0
2420
+ return sol
2421
+ if not lenics:
2422
+ lenics = sol.annihilator.order
2423
+ _y0 = _find_conditions(func, x, x0, lenics)
2424
+ while not _y0:
2425
+ x0 += 1
2426
+ _y0 = _find_conditions(func, x, x0, lenics)
2427
+ return HolonomicFunction(sol.annihilator, x, x0, _y0)
2428
+
2429
+ if y0 or not initcond:
2430
+ sol = sol.composition(func.args[0])
2431
+ if y0:
2432
+ sol.y0 = y0
2433
+ sol.x0 = x0
2434
+ return sol
2435
+ if not lenics:
2436
+ lenics = sol.annihilator.order
2437
+
2438
+ _y0 = _find_conditions(func, x, x0, lenics)
2439
+ while not _y0:
2440
+ x0 += 1
2441
+ _y0 = _find_conditions(func, x, x0, lenics)
2442
+ return sol.composition(func.args[0], x0, _y0)
2443
+
2444
+ # iterate through the expression recursively
2445
+ args = func.args
2446
+ f = func.func
2447
+ sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain)
2448
+
2449
+ if f is Add:
2450
+ for i in range(1, len(args)):
2451
+ sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
2452
+
2453
+ elif f is Mul:
2454
+ for i in range(1, len(args)):
2455
+ sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
2456
+
2457
+ elif f is Pow:
2458
+ sol = sol**args[1]
2459
+ sol.x0 = x0
2460
+ if not sol:
2461
+ raise NotImplementedError
2462
+ if y0:
2463
+ sol.y0 = y0
2464
+ if y0 or not initcond:
2465
+ return sol
2466
+ if sol.y0:
2467
+ return sol
2468
+ if not lenics:
2469
+ lenics = sol.annihilator.order
2470
+ if sol.annihilator.is_singular(x0):
2471
+ r = sol._indicial()
2472
+ l = list(r)
2473
+ if len(r) == 1 and r[l[0]] == S.One:
2474
+ r = l[0]
2475
+ g = func / (x - x0)**r
2476
+ singular_ics = _find_conditions(g, x, x0, lenics)
2477
+ singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
2478
+ y0 = {r:singular_ics}
2479
+ return HolonomicFunction(sol.annihilator, x, x0, y0)
2480
+
2481
+ _y0 = _find_conditions(func, x, x0, lenics)
2482
+ while not _y0:
2483
+ x0 += 1
2484
+ _y0 = _find_conditions(func, x, x0, lenics)
2485
+
2486
+ return HolonomicFunction(sol.annihilator, x, x0, _y0)
2487
+
2488
+
2489
+ ## Some helper functions ##
2490
+
2491
+ def _normalize(list_of, parent, negative=True):
2492
+ """
2493
+ Normalize a given annihilator
2494
+ """
2495
+
2496
+ num = []
2497
+ denom = []
2498
+ base = parent.base
2499
+ K = base.get_field()
2500
+ lcm_denom = base.from_sympy(S.One)
2501
+ list_of_coeff = []
2502
+
2503
+ # convert polynomials to the elements of associated
2504
+ # fraction field
2505
+ for i, j in enumerate(list_of):
2506
+ if isinstance(j, base.dtype):
2507
+ list_of_coeff.append(K.new(j.rep))
2508
+ elif not isinstance(j, K.dtype):
2509
+ list_of_coeff.append(K.from_sympy(sympify(j)))
2510
+ else:
2511
+ list_of_coeff.append(j)
2512
+
2513
+ # corresponding numerators of the sequence of polynomials
2514
+ num.append(list_of_coeff[i].numer())
2515
+
2516
+ # corresponding denominators
2517
+ denom.append(list_of_coeff[i].denom())
2518
+
2519
+ # lcm of denominators in the coefficients
2520
+ for i in denom:
2521
+ lcm_denom = i.lcm(lcm_denom)
2522
+
2523
+ if negative:
2524
+ lcm_denom = -lcm_denom
2525
+
2526
+ lcm_denom = K.new(lcm_denom.rep)
2527
+
2528
+ # multiply the coefficients with lcm
2529
+ for i, j in enumerate(list_of_coeff):
2530
+ list_of_coeff[i] = j * lcm_denom
2531
+
2532
+ gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep)
2533
+
2534
+ # gcd of numerators in the coefficients
2535
+ for i in num:
2536
+ gcd_numer = i.gcd(gcd_numer)
2537
+
2538
+ gcd_numer = K.new(gcd_numer.rep)
2539
+
2540
+ # divide all the coefficients by the gcd
2541
+ for i, j in enumerate(list_of_coeff):
2542
+ frac_ans = j / gcd_numer
2543
+ list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep)
2544
+
2545
+ return DifferentialOperator(list_of_coeff, parent)
2546
+
2547
+
2548
+ def _derivate_diff_eq(listofpoly):
2549
+ """
2550
+ Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0
2551
+ where a0, a1,... are polynomials or rational functions. The function
2552
+ returns b0, b1, b2... such that the differential equation
2553
+ b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the
2554
+ former equation.
2555
+ """
2556
+
2557
+ sol = []
2558
+ a = len(listofpoly) - 1
2559
+ sol.append(DMFdiff(listofpoly[0]))
2560
+
2561
+ for i, j in enumerate(listofpoly[1:]):
2562
+ sol.append(DMFdiff(j) + listofpoly[i])
2563
+
2564
+ sol.append(listofpoly[a])
2565
+ return sol
2566
+
2567
+
2568
+ def _hyper_to_meijerg(func):
2569
+ """
2570
+ Converts a `hyper` to meijerg.
2571
+ """
2572
+ ap = func.ap
2573
+ bq = func.bq
2574
+
2575
+ ispoly = any(i <= 0 and int(i) == i for i in ap)
2576
+ if ispoly:
2577
+ return hyperexpand(func)
2578
+
2579
+ z = func.args[2]
2580
+
2581
+ # parameters of the `meijerg` function.
2582
+ an = (1 - i for i in ap)
2583
+ anp = ()
2584
+ bm = (S.Zero, )
2585
+ bmq = (1 - i for i in bq)
2586
+
2587
+ k = S.One
2588
+
2589
+ for i in bq:
2590
+ k = k * gamma(i)
2591
+
2592
+ for i in ap:
2593
+ k = k / gamma(i)
2594
+
2595
+ return k * meijerg(an, anp, bm, bmq, -z)
2596
+
2597
+
2598
+ def _add_lists(list1, list2):
2599
+ """Takes polynomial sequences of two annihilators a and b and returns
2600
+ the list of polynomials of sum of a and b.
2601
+ """
2602
+ if len(list1) <= len(list2):
2603
+ sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
2604
+ else:
2605
+ sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
2606
+ return sol
2607
+
2608
+
2609
+ def _extend_y0(Holonomic, n):
2610
+ """
2611
+ Tries to find more initial conditions by substituting the initial
2612
+ value point in the differential equation.
2613
+ """
2614
+
2615
+ if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True:
2616
+ return Holonomic.y0
2617
+
2618
+ annihilator = Holonomic.annihilator
2619
+ a = annihilator.order
2620
+
2621
+ listofpoly = []
2622
+
2623
+ y0 = Holonomic.y0
2624
+ R = annihilator.parent.base
2625
+ K = R.get_field()
2626
+
2627
+ for i, j in enumerate(annihilator.listofpoly):
2628
+ if isinstance(j, annihilator.parent.base.dtype):
2629
+ listofpoly.append(K.new(j.rep))
2630
+
2631
+ if len(y0) < a or n <= len(y0):
2632
+ return y0
2633
+ else:
2634
+ list_red = [-listofpoly[i] / listofpoly[a]
2635
+ for i in range(a)]
2636
+ if len(y0) > a:
2637
+ y1 = [y0[i] for i in range(a)]
2638
+ else:
2639
+ y1 = list(y0)
2640
+ for i in range(n - a):
2641
+ sol = 0
2642
+ for a, b in zip(y1, list_red):
2643
+ r = DMFsubs(b, Holonomic.x0)
2644
+ if not getattr(r, 'is_finite', True):
2645
+ return y0
2646
+ if isinstance(r, (PolyElement, FracElement)):
2647
+ r = r.as_expr()
2648
+ sol += a * r
2649
+ y1.append(sol)
2650
+ list_red = _derivate_diff_eq(list_red)
2651
+
2652
+ return y0 + y1[len(y0):]
2653
+
2654
+
2655
+ def DMFdiff(frac):
2656
+ # differentiate a DMF object represented as p/q
2657
+ if not isinstance(frac, DMF):
2658
+ return frac.diff()
2659
+
2660
+ K = frac.ring
2661
+ p = K.numer(frac)
2662
+ q = K.denom(frac)
2663
+ sol_num = - p * q.diff() + q * p.diff()
2664
+ sol_denom = q**2
2665
+ return K((sol_num.rep, sol_denom.rep))
2666
+
2667
+
2668
+ def DMFsubs(frac, x0, mpm=False):
2669
+ # substitute the point x0 in DMF object of the form p/q
2670
+ if not isinstance(frac, DMF):
2671
+ return frac
2672
+
2673
+ p = frac.num
2674
+ q = frac.den
2675
+ sol_p = S.Zero
2676
+ sol_q = S.Zero
2677
+
2678
+ if mpm:
2679
+ from mpmath import mp
2680
+
2681
+ for i, j in enumerate(reversed(p)):
2682
+ if mpm:
2683
+ j = sympify(j)._to_mpmath(mp.prec)
2684
+ sol_p += j * x0**i
2685
+
2686
+ for i, j in enumerate(reversed(q)):
2687
+ if mpm:
2688
+ j = sympify(j)._to_mpmath(mp.prec)
2689
+ sol_q += j * x0**i
2690
+
2691
+ if isinstance(sol_p, (PolyElement, FracElement)):
2692
+ sol_p = sol_p.as_expr()
2693
+ if isinstance(sol_q, (PolyElement, FracElement)):
2694
+ sol_q = sol_q.as_expr()
2695
+
2696
+ return sol_p / sol_q
2697
+
2698
+
2699
+ def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True):
2700
+ """
2701
+ Converts polynomials, rationals and algebraic functions to holonomic.
2702
+ """
2703
+
2704
+ ispoly = func.is_polynomial()
2705
+ if not ispoly:
2706
+ israt = func.is_rational_function()
2707
+ else:
2708
+ israt = True
2709
+
2710
+ if not (ispoly or israt):
2711
+ basepoly, ratexp = func.as_base_exp()
2712
+ if basepoly.is_polynomial() and ratexp.is_Number:
2713
+ if isinstance(ratexp, Float):
2714
+ ratexp = nsimplify(ratexp)
2715
+ m, n = ratexp.p, ratexp.q
2716
+ is_alg = True
2717
+ else:
2718
+ is_alg = False
2719
+ else:
2720
+ is_alg = True
2721
+
2722
+ if not (ispoly or israt or is_alg):
2723
+ return None
2724
+
2725
+ R = domain.old_poly_ring(x)
2726
+ _, Dx = DifferentialOperators(R, 'Dx')
2727
+
2728
+ # if the function is constant
2729
+ if not func.has(x):
2730
+ return HolonomicFunction(Dx, x, 0, [func])
2731
+
2732
+ if ispoly:
2733
+ # differential equation satisfied by polynomial
2734
+ sol = func * Dx - func.diff(x)
2735
+ sol = _normalize(sol.listofpoly, sol.parent, negative=False)
2736
+ is_singular = sol.is_singular(x0)
2737
+
2738
+ # try to compute the conditions for singular points
2739
+ if y0 is None and x0 == 0 and is_singular:
2740
+ rep = R.from_sympy(func).rep
2741
+ for i, j in enumerate(reversed(rep)):
2742
+ if j == 0:
2743
+ continue
2744
+ else:
2745
+ coeff = list(reversed(rep))[i:]
2746
+ indicial = i
2747
+ break
2748
+ for i, j in enumerate(coeff):
2749
+ if isinstance(j, (PolyElement, FracElement)):
2750
+ coeff[i] = j.as_expr()
2751
+ y0 = {indicial: S(coeff)}
2752
+
2753
+ elif israt:
2754
+ p, q = func.as_numer_denom()
2755
+ # differential equation satisfied by rational
2756
+ sol = p * q * Dx + p * q.diff(x) - q * p.diff(x)
2757
+ sol = _normalize(sol.listofpoly, sol.parent, negative=False)
2758
+
2759
+ elif is_alg:
2760
+ sol = n * (x / m) * Dx - 1
2761
+ sol = HolonomicFunction(sol, x).composition(basepoly).annihilator
2762
+ is_singular = sol.is_singular(x0)
2763
+
2764
+ # try to compute the conditions for singular points
2765
+ if y0 is None and x0 == 0 and is_singular and \
2766
+ (lenics is None or lenics <= 1):
2767
+ rep = R.from_sympy(basepoly).rep
2768
+ for i, j in enumerate(reversed(rep)):
2769
+ if j == 0:
2770
+ continue
2771
+ if isinstance(j, (PolyElement, FracElement)):
2772
+ j = j.as_expr()
2773
+
2774
+ coeff = S(j)**ratexp
2775
+ indicial = S(i) * ratexp
2776
+ break
2777
+ if isinstance(coeff, (PolyElement, FracElement)):
2778
+ coeff = coeff.as_expr()
2779
+ y0 = {indicial: S([coeff])}
2780
+
2781
+ if y0 or not initcond:
2782
+ return HolonomicFunction(sol, x, x0, y0)
2783
+
2784
+ if not lenics:
2785
+ lenics = sol.order
2786
+
2787
+ if sol.is_singular(x0):
2788
+ r = HolonomicFunction(sol, x, x0)._indicial()
2789
+ l = list(r)
2790
+ if len(r) == 1 and r[l[0]] == S.One:
2791
+ r = l[0]
2792
+ g = func / (x - x0)**r
2793
+ singular_ics = _find_conditions(g, x, x0, lenics)
2794
+ singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
2795
+ y0 = {r:singular_ics}
2796
+ return HolonomicFunction(sol, x, x0, y0)
2797
+
2798
+ y0 = _find_conditions(func, x, x0, lenics)
2799
+ while not y0:
2800
+ x0 += 1
2801
+ y0 = _find_conditions(func, x, x0, lenics)
2802
+
2803
+ return HolonomicFunction(sol, x, x0, y0)
2804
+
2805
+
2806
+ def _convert_meijerint(func, x, initcond=True, domain=QQ):
2807
+ args = meijerint._rewrite1(func, x)
2808
+
2809
+ if args:
2810
+ fac, po, g, _ = args
2811
+ else:
2812
+ return None
2813
+
2814
+ # lists for sum of meijerg functions
2815
+ fac_list = [fac * i[0] for i in g]
2816
+ t = po.as_base_exp()
2817
+ s = t[1] if t[0] == x else S.Zero
2818
+ po_list = [s + i[1] for i in g]
2819
+ G_list = [i[2] for i in g]
2820
+
2821
+ # finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z)
2822
+ def _shift(func, s):
2823
+ z = func.args[-1]
2824
+ if z.has(I):
2825
+ z = z.subs(exp_polar, exp)
2826
+
2827
+ d = z.collect(x, evaluate=False)
2828
+ b = list(d)[0]
2829
+ a = d[b]
2830
+
2831
+ t = b.as_base_exp()
2832
+ b = t[1] if t[0] == x else S.Zero
2833
+ r = s / b
2834
+ an = (i + r for i in func.args[0][0])
2835
+ ap = (i + r for i in func.args[0][1])
2836
+ bm = (i + r for i in func.args[1][0])
2837
+ bq = (i + r for i in func.args[1][1])
2838
+
2839
+ return a**-r, meijerg((an, ap), (bm, bq), z)
2840
+
2841
+ coeff, m = _shift(G_list[0], po_list[0])
2842
+ sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
2843
+
2844
+ # add all the meijerg functions after converting to holonomic
2845
+ for i in range(1, len(G_list)):
2846
+ coeff, m = _shift(G_list[i], po_list[i])
2847
+ sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
2848
+
2849
+ return sol
2850
+
2851
+
2852
+ def _create_table(table, domain=QQ):
2853
+ """
2854
+ Creates the look-up table. For a similar implementation
2855
+ see meijerint._create_lookup_table.
2856
+ """
2857
+
2858
+ def add(formula, annihilator, arg, x0=0, y0=()):
2859
+ """
2860
+ Adds a formula in the dictionary
2861
+ """
2862
+ table.setdefault(_mytype(formula, x_1), []).append((formula,
2863
+ HolonomicFunction(annihilator, arg, x0, y0)))
2864
+
2865
+ R = domain.old_poly_ring(x_1)
2866
+ _, Dx = DifferentialOperators(R, 'Dx')
2867
+
2868
+ # add some basic functions
2869
+ add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1])
2870
+ add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0])
2871
+ add(exp(x_1), Dx - 1, x_1, 0, 1)
2872
+ add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1])
2873
+
2874
+ add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
2875
+ add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)])
2876
+ add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
2877
+
2878
+ add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1])
2879
+ add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0])
2880
+
2881
+ add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1)
2882
+
2883
+ add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
2884
+ add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
2885
+
2886
+ add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
2887
+
2888
+
2889
+ def _find_conditions(func, x, x0, order):
2890
+ y0 = []
2891
+ for i in range(order):
2892
+ val = func.subs(x, x0)
2893
+ if isinstance(val, NaN):
2894
+ val = limit(func, x, x0)
2895
+ if val.is_finite is False or isinstance(val, NaN):
2896
+ return None
2897
+ y0.append(val)
2898
+ func = func.diff(x)
2899
+ return y0
venv/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Common Exceptions for `holonomic` module. """
2
+
3
+ class BaseHolonomicError(Exception):
4
+
5
+ def new(self, *args):
6
+ raise NotImplementedError("abstract base class")
7
+
8
+ class NotPowerSeriesError(BaseHolonomicError):
9
+
10
+ def __init__(self, holonomic, x0):
11
+ self.holonomic = holonomic
12
+ self.x0 = x0
13
+
14
+ def __str__(self):
15
+ s = 'A Power Series does not exists for '
16
+ s += str(self.holonomic)
17
+ s += ' about %s.' %self.x0
18
+ return s
19
+
20
+ class NotHolonomicError(BaseHolonomicError):
21
+
22
+ def __init__(self, m):
23
+ self.m = m
24
+
25
+ def __str__(self):
26
+ return self.m
27
+
28
+ class SingularityError(BaseHolonomicError):
29
+
30
+ def __init__(self, holonomic, x0):
31
+ self.holonomic = holonomic
32
+ self.x0 = x0
33
+
34
+ def __str__(self):
35
+ s = str(self.holonomic)
36
+ s += ' has a singularity at %s.' %self.x0
37
+ return s
38
+
39
+ class NotHyperSeriesError(BaseHolonomicError):
40
+
41
+ def __init__(self, holonomic, x0):
42
+ self.holonomic = holonomic
43
+ self.x0 = x0
44
+
45
+ def __str__(self):
46
+ s = 'Power series expansion of '
47
+ s += str(self.holonomic)
48
+ s += ' about %s is not hypergeometric' %self.x0
49
+ return s
venv/lib/python3.10/site-packages/sympy/holonomic/numerical.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numerical Methods for Holonomic Functions"""
2
+
3
+ from sympy.core.sympify import sympify
4
+ from sympy.holonomic.holonomic import DMFsubs
5
+
6
+ from mpmath import mp
7
+
8
+
9
+ def _evalf(func, points, derivatives=False, method='RK4'):
10
+ """
11
+ Numerical methods for numerical integration along a given set of
12
+ points in the complex plane.
13
+ """
14
+
15
+ ann = func.annihilator
16
+ a = ann.order
17
+ R = ann.parent.base
18
+ K = R.get_field()
19
+
20
+ if method == 'Euler':
21
+ meth = _euler
22
+ else:
23
+ meth = _rk4
24
+
25
+ dmf = []
26
+ for j in ann.listofpoly:
27
+ dmf.append(K.new(j.rep))
28
+
29
+ red = [-dmf[i] / dmf[a] for i in range(a)]
30
+
31
+ y0 = func.y0
32
+ if len(y0) < a:
33
+ raise TypeError("Not Enough Initial Conditions")
34
+ x0 = func.x0
35
+ sol = [meth(red, x0, points[0], y0, a)]
36
+
37
+ for i, j in enumerate(points[1:]):
38
+ sol.append(meth(red, points[i], j, sol[-1], a))
39
+
40
+ if not derivatives:
41
+ return [sympify(i[0]) for i in sol]
42
+ else:
43
+ return sympify(sol)
44
+
45
+
46
+ def _euler(red, x0, x1, y0, a):
47
+ """
48
+ Euler's method for numerical integration.
49
+ From x0 to x1 with initial values given at x0 as vector y0.
50
+ """
51
+
52
+ A = sympify(x0)._to_mpmath(mp.prec)
53
+ B = sympify(x1)._to_mpmath(mp.prec)
54
+ y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
55
+ h = B - A
56
+ f_0 = y_0[1:]
57
+ f_0_n = 0
58
+
59
+ for i in range(a):
60
+ f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
61
+ f_0.append(f_0_n)
62
+
63
+ sol = []
64
+ for i in range(a):
65
+ sol.append(y_0[i] + h * f_0[i])
66
+
67
+ return sol
68
+
69
+
70
+ def _rk4(red, x0, x1, y0, a):
71
+ """
72
+ Runge-Kutta 4th order numerical method.
73
+ """
74
+
75
+ A = sympify(x0)._to_mpmath(mp.prec)
76
+ B = sympify(x1)._to_mpmath(mp.prec)
77
+ y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
78
+ h = B - A
79
+
80
+ f_0_n = 0
81
+ f_1_n = 0
82
+ f_2_n = 0
83
+ f_3_n = 0
84
+
85
+ f_0 = y_0[1:]
86
+ for i in range(a):
87
+ f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
88
+ f_0.append(f_0_n)
89
+
90
+ f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)]
91
+ for i in range(a):
92
+ f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)
93
+ f_1.append(f_1_n)
94
+
95
+ f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)]
96
+ for i in range(a):
97
+ f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)
98
+ f_2.append(f_2_n)
99
+
100
+ f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)]
101
+ for i in range(a):
102
+ f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h)
103
+ f_3.append(f_3_n)
104
+
105
+ sol = []
106
+ for i in range(a):
107
+ sol.append(y_0[i] + h * (f_0[i]+2*f_1[i]+2*f_2[i]+f_3[i])/6)
108
+
109
+ return sol
venv/lib/python3.10/site-packages/sympy/holonomic/recurrence.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recurrence Operators"""
2
+
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.printing import sstr
6
+ from sympy.core.sympify import sympify
7
+
8
+
9
+ def RecurrenceOperators(base, generator):
10
+ """
11
+ Returns an Algebra of Recurrence Operators and the operator for
12
+ shifting i.e. the `Sn` operator.
13
+ The first argument needs to be the base polynomial ring for the algebra
14
+ and the second argument must be a generator which can be either a
15
+ noncommutative Symbol or a string.
16
+
17
+ Examples
18
+ ========
19
+
20
+ >>> from sympy import ZZ
21
+ >>> from sympy import symbols
22
+ >>> from sympy.holonomic.recurrence import RecurrenceOperators
23
+ >>> n = symbols('n', integer=True)
24
+ >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
25
+ """
26
+
27
+ ring = RecurrenceOperatorAlgebra(base, generator)
28
+ return (ring, ring.shift_operator)
29
+
30
+
31
+ class RecurrenceOperatorAlgebra:
32
+ """
33
+ A Recurrence Operator Algebra is a set of noncommutative polynomials
34
+ in intermediate `Sn` and coefficients in a base ring A. It follows the
35
+ commutation rule:
36
+ Sn * a(n) = a(n + 1) * Sn
37
+
38
+ This class represents a Recurrence Operator Algebra and serves as the parent ring
39
+ for Recurrence Operators.
40
+
41
+ Examples
42
+ ========
43
+
44
+ >>> from sympy import ZZ
45
+ >>> from sympy import symbols
46
+ >>> from sympy.holonomic.recurrence import RecurrenceOperators
47
+ >>> n = symbols('n', integer=True)
48
+ >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
49
+ >>> R
50
+ Univariate Recurrence Operator Algebra in intermediate Sn over the base ring
51
+ ZZ[n]
52
+
53
+ See Also
54
+ ========
55
+
56
+ RecurrenceOperator
57
+ """
58
+
59
+ def __init__(self, base, generator):
60
+ # the base ring for the algebra
61
+ self.base = base
62
+ # the operator representing shift i.e. `Sn`
63
+ self.shift_operator = RecurrenceOperator(
64
+ [base.zero, base.one], self)
65
+
66
+ if generator is None:
67
+ self.gen_symbol = symbols('Sn', commutative=False)
68
+ else:
69
+ if isinstance(generator, str):
70
+ self.gen_symbol = symbols(generator, commutative=False)
71
+ elif isinstance(generator, Symbol):
72
+ self.gen_symbol = generator
73
+
74
+ def __str__(self):
75
+ string = 'Univariate Recurrence Operator Algebra in intermediate '\
76
+ + sstr(self.gen_symbol) + ' over the base ring ' + \
77
+ (self.base).__str__()
78
+
79
+ return string
80
+
81
+ __repr__ = __str__
82
+
83
+ def __eq__(self, other):
84
+ if self.base == other.base and self.gen_symbol == other.gen_symbol:
85
+ return True
86
+ else:
87
+ return False
88
+
89
+
90
+ def _add_lists(list1, list2):
91
+ if len(list1) <= len(list2):
92
+ sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
93
+ else:
94
+ sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
95
+ return sol
96
+
97
+
98
+ class RecurrenceOperator:
99
+ """
100
+ The Recurrence Operators are defined by a list of polynomials
101
+ in the base ring and the parent ring of the Operator.
102
+
103
+ Explanation
104
+ ===========
105
+
106
+ Takes a list of polynomials for each power of Sn and the
107
+ parent ring which must be an instance of RecurrenceOperatorAlgebra.
108
+
109
+ A Recurrence Operator can be created easily using
110
+ the operator `Sn`. See examples below.
111
+
112
+ Examples
113
+ ========
114
+
115
+ >>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators
116
+ >>> from sympy import ZZ
117
+ >>> from sympy import symbols
118
+ >>> n = symbols('n', integer=True)
119
+ >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn')
120
+
121
+ >>> RecurrenceOperator([0, 1, n**2], R)
122
+ (1)Sn + (n**2)Sn**2
123
+
124
+ >>> Sn*n
125
+ (n + 1)Sn
126
+
127
+ >>> n*Sn*n + 1 - Sn**2*n
128
+ (1) + (n**2 + n)Sn + (-n - 2)Sn**2
129
+
130
+ See Also
131
+ ========
132
+
133
+ DifferentialOperatorAlgebra
134
+ """
135
+
136
+ _op_priority = 20
137
+
138
+ def __init__(self, list_of_poly, parent):
139
+ # the parent ring for this operator
140
+ # must be an RecurrenceOperatorAlgebra object
141
+ self.parent = parent
142
+ # sequence of polynomials in n for each power of Sn
143
+ # represents the operator
144
+ # convert the expressions into ring elements using from_sympy
145
+ if isinstance(list_of_poly, list):
146
+ for i, j in enumerate(list_of_poly):
147
+ if isinstance(j, int):
148
+ list_of_poly[i] = self.parent.base.from_sympy(S(j))
149
+ elif not isinstance(j, self.parent.base.dtype):
150
+ list_of_poly[i] = self.parent.base.from_sympy(j)
151
+
152
+ self.listofpoly = list_of_poly
153
+ self.order = len(self.listofpoly) - 1
154
+
155
+ def __mul__(self, other):
156
+ """
157
+ Multiplies two Operators and returns another
158
+ RecurrenceOperator instance using the commutation rule
159
+ Sn * a(n) = a(n + 1) * Sn
160
+ """
161
+
162
+ listofself = self.listofpoly
163
+ base = self.parent.base
164
+
165
+ if not isinstance(other, RecurrenceOperator):
166
+ if not isinstance(other, self.parent.base.dtype):
167
+ listofother = [self.parent.base.from_sympy(sympify(other))]
168
+
169
+ else:
170
+ listofother = [other]
171
+ else:
172
+ listofother = other.listofpoly
173
+ # multiply a polynomial `b` with a list of polynomials
174
+
175
+ def _mul_dmp_diffop(b, listofother):
176
+ if isinstance(listofother, list):
177
+ sol = []
178
+ for i in listofother:
179
+ sol.append(i * b)
180
+ return sol
181
+ else:
182
+ return [b * listofother]
183
+
184
+ sol = _mul_dmp_diffop(listofself[0], listofother)
185
+
186
+ # compute Sn^i * b
187
+ def _mul_Sni_b(b):
188
+ sol = [base.zero]
189
+
190
+ if isinstance(b, list):
191
+ for i in b:
192
+ j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One)
193
+ sol.append(base.from_sympy(j))
194
+
195
+ else:
196
+ j = b.subs(base.gens[0], base.gens[0] + S.One)
197
+ sol.append(base.from_sympy(j))
198
+
199
+ return sol
200
+
201
+ for i in range(1, len(listofself)):
202
+ # find Sn^i * b in ith iteration
203
+ listofother = _mul_Sni_b(listofother)
204
+ # solution = solution + listofself[i] * (Sn^i * b)
205
+ sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
206
+
207
+ return RecurrenceOperator(sol, self.parent)
208
+
209
+ def __rmul__(self, other):
210
+ if not isinstance(other, RecurrenceOperator):
211
+
212
+ if isinstance(other, int):
213
+ other = S(other)
214
+
215
+ if not isinstance(other, self.parent.base.dtype):
216
+ other = (self.parent.base).from_sympy(other)
217
+
218
+ sol = []
219
+ for j in self.listofpoly:
220
+ sol.append(other * j)
221
+
222
+ return RecurrenceOperator(sol, self.parent)
223
+
224
+ def __add__(self, other):
225
+ if isinstance(other, RecurrenceOperator):
226
+
227
+ sol = _add_lists(self.listofpoly, other.listofpoly)
228
+ return RecurrenceOperator(sol, self.parent)
229
+
230
+ else:
231
+
232
+ if isinstance(other, int):
233
+ other = S(other)
234
+ list_self = self.listofpoly
235
+ if not isinstance(other, self.parent.base.dtype):
236
+ list_other = [((self.parent).base).from_sympy(other)]
237
+ else:
238
+ list_other = [other]
239
+ sol = []
240
+ sol.append(list_self[0] + list_other[0])
241
+ sol += list_self[1:]
242
+
243
+ return RecurrenceOperator(sol, self.parent)
244
+
245
+ __radd__ = __add__
246
+
247
+ def __sub__(self, other):
248
+ return self + (-1) * other
249
+
250
+ def __rsub__(self, other):
251
+ return (-1) * self + other
252
+
253
+ def __pow__(self, n):
254
+ if n == 1:
255
+ return self
256
+ if n == 0:
257
+ return RecurrenceOperator([self.parent.base.one], self.parent)
258
+ # if self is `Sn`
259
+ if self.listofpoly == self.parent.shift_operator.listofpoly:
260
+ sol = []
261
+ for i in range(0, n):
262
+ sol.append(self.parent.base.zero)
263
+ sol.append(self.parent.base.one)
264
+
265
+ return RecurrenceOperator(sol, self.parent)
266
+
267
+ else:
268
+ if n % 2 == 1:
269
+ powreduce = self**(n - 1)
270
+ return powreduce * self
271
+ elif n % 2 == 0:
272
+ powreduce = self**(n / 2)
273
+ return powreduce * powreduce
274
+
275
+ def __str__(self):
276
+ listofpoly = self.listofpoly
277
+ print_str = ''
278
+
279
+ for i, j in enumerate(listofpoly):
280
+ if j == self.parent.base.zero:
281
+ continue
282
+
283
+ if i == 0:
284
+ print_str += '(' + sstr(j) + ')'
285
+ continue
286
+
287
+ if print_str:
288
+ print_str += ' + '
289
+
290
+ if i == 1:
291
+ print_str += '(' + sstr(j) + ')Sn'
292
+ continue
293
+
294
+ print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i)
295
+
296
+ return print_str
297
+
298
+ __repr__ = __str__
299
+
300
+ def __eq__(self, other):
301
+ if isinstance(other, RecurrenceOperator):
302
+ if self.listofpoly == other.listofpoly and self.parent == other.parent:
303
+ return True
304
+ else:
305
+ return False
306
+ else:
307
+ if self.listofpoly[0] == other:
308
+ for i in self.listofpoly[1:]:
309
+ if i is not self.parent.base.zero:
310
+ return False
311
+ return True
312
+ else:
313
+ return False
314
+
315
+
316
+ class HolonomicSequence:
317
+ """
318
+ A Holonomic Sequence is a type of sequence satisfying a linear homogeneous
319
+ recurrence relation with Polynomial coefficients. Alternatively, A sequence
320
+ is Holonomic if and only if its generating function is a Holonomic Function.
321
+ """
322
+
323
+ def __init__(self, recurrence, u0=[]):
324
+ self.recurrence = recurrence
325
+ if not isinstance(u0, list):
326
+ self.u0 = [u0]
327
+ else:
328
+ self.u0 = u0
329
+
330
+ if len(self.u0) == 0:
331
+ self._have_init_cond = False
332
+ else:
333
+ self._have_init_cond = True
334
+ self.n = recurrence.parent.base.gens[0]
335
+
336
+ def __repr__(self):
337
+ str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n))
338
+ if not self._have_init_cond:
339
+ return str_sol
340
+ else:
341
+ cond_str = ''
342
+ seq_str = 0
343
+ for i in self.u0:
344
+ cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i))
345
+ seq_str += 1
346
+
347
+ sol = str_sol + cond_str
348
+ return sol
349
+
350
+ __str__ = __repr__
351
+
352
+ def __eq__(self, other):
353
+ if self.recurrence == other.recurrence:
354
+ if self.n == other.n:
355
+ if self._have_init_cond and other._have_init_cond:
356
+ if self.u0 == other.u0:
357
+ return True
358
+ else:
359
+ return False
360
+ else:
361
+ return True
362
+ else:
363
+ return False
364
+ else:
365
+ return False
venv/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (189 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc ADDED
Binary file (31.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.holonomic import (DifferentialOperator, HolonomicFunction,
2
+ DifferentialOperators, from_hyper,
3
+ from_meijerg, expr_to_holonomic)
4
+ from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence
5
+ from sympy.core import EulerGamma
6
+ from sympy.core.numbers import (I, Rational, pi)
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import (Symbol, symbols)
9
+ from sympy.functions.elementary.exponential import (exp, log)
10
+ from sympy.functions.elementary.hyperbolic import (asinh, cosh)
11
+ from sympy.functions.elementary.miscellaneous import sqrt
12
+ from sympy.functions.elementary.trigonometric import (cos, sin)
13
+ from sympy.functions.special.bessel import besselj
14
+ from sympy.functions.special.beta_functions import beta
15
+ from sympy.functions.special.error_functions import (Ci, Si, erf, erfc)
16
+ from sympy.functions.special.gamma_functions import gamma
17
+ from sympy.functions.special.hyper import (hyper, meijerg)
18
+ from sympy.printing.str import sstr
19
+ from sympy.series.order import O
20
+ from sympy.simplify.hyperexpand import hyperexpand
21
+ from sympy.polys.domains.integerring import ZZ
22
+ from sympy.polys.domains.rationalfield import QQ
23
+ from sympy.polys.domains.realfield import RR
24
+
25
+
26
+ def test_DifferentialOperator():
27
+ x = symbols('x')
28
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
29
+ assert Dx == R.derivative_operator
30
+ assert Dx == DifferentialOperator([R.base.zero, R.base.one], R)
31
+ assert x * Dx + x**2 * Dx**2 == DifferentialOperator([0, x, x**2], R)
32
+ assert (x**2 + 1) + Dx + x * \
33
+ Dx**5 == DifferentialOperator([x**2 + 1, 1, 0, 0, 0, x], R)
34
+ assert (x * Dx + x**2 + 1 - Dx * (x**3 + x))**3 == (-48 * x**6) + \
35
+ (-57 * x**7) * Dx + (-15 * x**8) * Dx**2 + (-x**9) * Dx**3
36
+ p = (x * Dx**2 + (x**2 + 3) * Dx**5) * (Dx + x**2)
37
+ q = (2 * x) + (4 * x**2) * Dx + (x**3) * Dx**2 + \
38
+ (20 * x**2 + x + 60) * Dx**3 + (10 * x**3 + 30 * x) * Dx**4 + \
39
+ (x**4 + 3 * x**2) * Dx**5 + (x**2 + 3) * Dx**6
40
+ assert p == q
41
+
42
+
43
+ def test_HolonomicFunction_addition():
44
+ x = symbols('x')
45
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
46
+ p = HolonomicFunction(Dx**2 * x, x)
47
+ q = HolonomicFunction((2) * Dx + (x) * Dx**2, x)
48
+ assert p == q
49
+ p = HolonomicFunction(x * Dx + 1, x)
50
+ q = HolonomicFunction(Dx + 1, x)
51
+ r = HolonomicFunction((x - 2) + (x**2 - 2) * Dx + (x**2 - x) * Dx**2, x)
52
+ assert p + q == r
53
+ p = HolonomicFunction(x * Dx + Dx**2 * (x**2 + 2), x)
54
+ q = HolonomicFunction(Dx - 3, x)
55
+ r = HolonomicFunction((-54 * x**2 - 126 * x - 150) + (-135 * x**3 - 252 * x**2 - 270 * x + 140) * Dx +\
56
+ (-27 * x**4 - 24 * x**2 + 14 * x - 150) * Dx**2 + \
57
+ (9 * x**4 + 15 * x**3 + 38 * x**2 + 30 * x +40) * Dx**3, x)
58
+ assert p + q == r
59
+ p = HolonomicFunction(Dx**5 - 1, x)
60
+ q = HolonomicFunction(x**3 + Dx, x)
61
+ r = HolonomicFunction((-x**18 + 45*x**14 - 525*x**10 + 1575*x**6 - x**3 - 630*x**2) + \
62
+ (-x**15 + 30*x**11 - 195*x**7 + 210*x**3 - 1)*Dx + (x**18 - 45*x**14 + 525*x**10 - \
63
+ 1575*x**6 + x**3 + 630*x**2)*Dx**5 + (x**15 - 30*x**11 + 195*x**7 - 210*x**3 + \
64
+ 1)*Dx**6, x)
65
+ assert p+q == r
66
+
67
+ p = x**2 + 3*x + 8
68
+ q = x**3 - 7*x + 5
69
+ p = p*Dx - p.diff()
70
+ q = q*Dx - q.diff()
71
+ r = HolonomicFunction(p, x) + HolonomicFunction(q, x)
72
+ s = HolonomicFunction((6*x**2 + 18*x + 14) + (-4*x**3 - 18*x**2 - 62*x + 10)*Dx +\
73
+ (x**4 + 6*x**3 + 31*x**2 - 10*x - 71)*Dx**2, x)
74
+ assert r == s
75
+
76
+
77
+ def test_HolonomicFunction_multiplication():
78
+ x = symbols('x')
79
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
80
+ p = HolonomicFunction(Dx+x+x*Dx**2, x)
81
+ q = HolonomicFunction(x*Dx+Dx*x+Dx**2, x)
82
+ r = HolonomicFunction((8*x**6 + 4*x**4 + 6*x**2 + 3) + (24*x**5 - 4*x**3 + 24*x)*Dx + \
83
+ (8*x**6 + 20*x**4 + 12*x**2 + 2)*Dx**2 + (8*x**5 + 4*x**3 + 4*x)*Dx**3 + \
84
+ (2*x**4 + x**2)*Dx**4, x)
85
+ assert p*q == r
86
+ p = HolonomicFunction(Dx**2+1, x)
87
+ q = HolonomicFunction(Dx-1, x)
88
+ r = HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x)
89
+ assert p*q == r
90
+ p = HolonomicFunction(Dx**2+1+x+Dx, x)
91
+ q = HolonomicFunction((Dx*x-1)**2, x)
92
+ r = HolonomicFunction((4*x**7 + 11*x**6 + 16*x**5 + 4*x**4 - 6*x**3 - 7*x**2 - 8*x - 2) + \
93
+ (8*x**6 + 26*x**5 + 24*x**4 - 3*x**3 - 11*x**2 - 6*x - 2)*Dx + \
94
+ (8*x**6 + 18*x**5 + 15*x**4 - 3*x**3 - 6*x**2 - 6*x - 2)*Dx**2 + (8*x**5 + \
95
+ 10*x**4 + 6*x**3 - 2*x**2 - 4*x)*Dx**3 + (4*x**5 + 3*x**4 - x**2)*Dx**4, x)
96
+ assert p*q == r
97
+ p = HolonomicFunction(x*Dx**2-1, x)
98
+ q = HolonomicFunction(Dx*x-x, x)
99
+ r = HolonomicFunction((x - 3) + (-2*x + 2)*Dx + (x)*Dx**2, x)
100
+ assert p*q == r
101
+
102
+
103
+ def test_addition_initial_condition():
104
+ x = symbols('x')
105
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
106
+ p = HolonomicFunction(Dx-1, x, 0, [3])
107
+ q = HolonomicFunction(Dx**2+1, x, 0, [1, 0])
108
+ r = HolonomicFunction(-1 + Dx - Dx**2 + Dx**3, x, 0, [4, 3, 2])
109
+ assert p + q == r
110
+ p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2])
111
+ q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])
112
+ r = HolonomicFunction((-x**4 - x**3/4 - x**2 + Rational(1, 4)) + (x**3 + x**2/4 + x*Rational(3, 4) + 1)*Dx + \
113
+ (x*Rational(-3, 2) + Rational(7, 4))*Dx**2 + (x**2 - x*Rational(7, 4) + Rational(1, 4))*Dx**3 + (x**2 + x/4 + S.Half)*Dx**4, x, 0, [2, 2, -2, 2])
114
+ assert p + q == r
115
+ p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4])
116
+ q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])
117
+ r = HolonomicFunction((x**6 + 2*x**4 - 5*x**2 - 6) + (4*x**5 + 36*x**3 - 32*x)*Dx + \
118
+ (x**6 + 3*x**4 + 5*x**2 - 9)*Dx**2 + (4*x**5 + 36*x**3 - 32*x)*Dx**3 + (x**4 + \
119
+ 10*x**2 - 3)*Dx**4, x, 0, [4, 5, -1, -17])
120
+ assert p + q == r
121
+ q = HolonomicFunction(Dx**3 + x, x, 2, [3, 0, 1])
122
+ p = HolonomicFunction(Dx - 1, x, 2, [1])
123
+ r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \
124
+ (x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ])
125
+ assert p + q == r
126
+ p = expr_to_holonomic(sin(x))
127
+ q = expr_to_holonomic(1/x, x0=1)
128
+ r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \
129
+ x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2])
130
+ assert p + q == r
131
+ C_1 = symbols('C_1')
132
+ p = expr_to_holonomic(sqrt(x))
133
+ q = expr_to_holonomic(sqrt(x**2-x))
134
+ r = (p + q).to_expr().subs(C_1, -I/2).expand()
135
+ assert r == I*sqrt(x)*sqrt(-x + 1) + sqrt(x)
136
+
137
+
138
+ def test_multiplication_initial_condition():
139
+ x = symbols('x')
140
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
141
+ p = HolonomicFunction(Dx**2 + x*Dx - 1, x, 0, [3, 1])
142
+ q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])
143
+ r = HolonomicFunction((x**4 + 14*x**2 + 60) + 4*x*Dx + (x**4 + 9*x**2 + 20)*Dx**2 + \
144
+ (2*x**3 + 18*x)*Dx**3 + (x**2 + 10)*Dx**4, x, 0, [3, 4, 2, 3])
145
+ assert p * q == r
146
+ p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])
147
+ q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3])
148
+ r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \
149
+ 160*x**3/27 + 404*x**2/9 + 8*x + Rational(40, 3)) + (6*x**7 - 128*x**6/9 - 98*x**5/9 - 28*x**4/9 + \
150
+ 8*x**3/9 + 28*x**2 + x*Rational(40, 9) - 40)*Dx + (3*x**6 - 82*x**5/9 + 76*x**4/9 + 4*x**3/3 + \
151
+ 220*x**2/9 - x*Rational(80, 3))*Dx**2 + (-2*x**6 + 128*x**5/27 - 2*x**4/3 -80*x**2/9 + Rational(200, 9))*Dx**3 + \
152
+ (3*x**5 - 64*x**4/9 - 28*x**3/9 + 6*x**2 - x*Rational(20, 9) - Rational(20, 3))*Dx**4 + (-4*x**3 + 64*x**2/9 + \
153
+ x*Rational(8, 3))*Dx**5 + (x**4 - 64*x**3/27 - 4*x**2/3 + Rational(20, 9))*Dx**6, x, 0, [3, 3, 3, -3, -12, -24])
154
+ assert p * q == r
155
+ p = HolonomicFunction(Dx - 1, x, 0, [2])
156
+ q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
157
+ r = HolonomicFunction(2 -2*Dx + Dx**2, x, 0, [0, 2])
158
+ assert p * q == r
159
+ q = HolonomicFunction(x*Dx**2 + 1 + 2*Dx, x, 0,[0, 1])
160
+ r = HolonomicFunction((x - 1) + (-2*x + 2)*Dx + x*Dx**2, x, 0, [0, 2])
161
+ assert p * q == r
162
+ p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 3])
163
+ q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1])
164
+ r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2])
165
+ assert p * q == r
166
+ p = expr_to_holonomic(sin(x))
167
+ q = expr_to_holonomic(1/x, x0=1)
168
+ r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)])
169
+ assert p * q == r
170
+ p = expr_to_holonomic(sqrt(x))
171
+ q = expr_to_holonomic(sqrt(x**2-x))
172
+ r = (p * q).to_expr()
173
+ assert r == I*x*sqrt(-x + 1)
174
+
175
+
176
+ def test_HolonomicFunction_composition():
177
+ x = symbols('x')
178
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
179
+ p = HolonomicFunction(Dx-1, x).composition(x**2+x)
180
+ r = HolonomicFunction((-2*x - 1) + Dx, x)
181
+ assert p == r
182
+ p = HolonomicFunction(Dx**2+1, x).composition(x**5+x**2+1)
183
+ r = HolonomicFunction((125*x**12 + 150*x**9 + 60*x**6 + 8*x**3) + (-20*x**3 - 2)*Dx + \
184
+ (5*x**4 + 2*x)*Dx**2, x)
185
+ assert p == r
186
+ p = HolonomicFunction(Dx**2*x+x, x).composition(2*x**3+x**2+1)
187
+ r = HolonomicFunction((216*x**9 + 324*x**8 + 180*x**7 + 152*x**6 + 112*x**5 + \
188
+ 36*x**4 + 4*x**3) + (24*x**4 + 16*x**3 + 3*x**2 - 6*x - 1)*Dx + (6*x**5 + 5*x**4 + \
189
+ x**3 + 3*x**2 + x)*Dx**2, x)
190
+ assert p == r
191
+ p = HolonomicFunction(Dx**2+1, x).composition(1-x**2)
192
+ r = HolonomicFunction((4*x**3) - Dx + x*Dx**2, x)
193
+ assert p == r
194
+ p = HolonomicFunction(Dx**2+1, x).composition(x - 2/(x**2 + 1))
195
+ r = HolonomicFunction((x**12 + 6*x**10 + 12*x**9 + 15*x**8 + 48*x**7 + 68*x**6 + \
196
+ 72*x**5 + 111*x**4 + 112*x**3 + 54*x**2 + 12*x + 1) + (12*x**8 + 32*x**6 + \
197
+ 24*x**4 - 4)*Dx + (x**12 + 6*x**10 + 4*x**9 + 15*x**8 + 16*x**7 + 20*x**6 + 24*x**5+ \
198
+ 15*x**4 + 16*x**3 + 6*x**2 + 4*x + 1)*Dx**2, x)
199
+ assert p == r
200
+
201
+
202
+ def test_from_hyper():
203
+ x = symbols('x')
204
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
205
+ p = hyper([1, 1], [Rational(3, 2)], x**2/4)
206
+ q = HolonomicFunction((4*x) + (5*x**2 - 8)*Dx + (x**3 - 4*x)*Dx**2, x, 1, [2*sqrt(3)*pi/9, -4*sqrt(3)*pi/27 + Rational(4, 3)])
207
+ r = from_hyper(p)
208
+ assert r == q
209
+ p = from_hyper(hyper([1], [Rational(3, 2)], x**2/4))
210
+ q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x)
211
+ # x0 = 1
212
+ y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]'
213
+ assert sstr(p.y0) == y0
214
+ assert q.annihilator == p.annihilator
215
+
216
+
217
+ def test_from_meijerg():
218
+ x = symbols('x')
219
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
220
+ p = from_meijerg(meijerg(([], [Rational(3, 2)]), ([S.Half], [S.Half, 1]), x))
221
+ q = HolonomicFunction(x/2 - Rational(1, 4) + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \
222
+ [1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))])
223
+ assert p == q
224
+ p = from_meijerg(meijerg(([], []), ([0], []), x))
225
+ q = HolonomicFunction(1 + Dx, x, 0, [1])
226
+ assert p == q
227
+ p = from_meijerg(meijerg(([1], []), ([S.Half], [0]), x))
228
+ q = HolonomicFunction((x + S.Half)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)])
229
+ assert p == q
230
+ p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2))
231
+ q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(Rational(-1, 2)) + 1, -exp(Rational(-1, 2))])
232
+ assert p == q
233
+
234
+
235
+ def test_to_Sequence():
236
+ x = symbols('x')
237
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
238
+ n = symbols('n', integer=True)
239
+ _, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
240
+ p = HolonomicFunction(x**2*Dx**4 + x + Dx, x).to_sequence()
241
+ q = [(HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 0, 1)]
242
+ assert p == q
243
+ p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence()
244
+ q = [(HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0, 0)]
245
+ assert p == q
246
+ p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence()
247
+ q = [(HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 0, 0)]
248
+ assert p == q
249
+ p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence()
250
+ q = [(HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2), 0, 1)]
251
+ assert p == q
252
+
253
+
254
+ def test_to_Sequence_Initial_Coniditons():
255
+ x = symbols('x')
256
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
257
+ n = symbols('n', integer=True)
258
+ _, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
259
+ p = HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
260
+ q = [(HolonomicSequence(-1 + (n + 1)*Sn, 1), 0)]
261
+ assert p == q
262
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_sequence()
263
+ q = [(HolonomicSequence(1 + (n**2 + 3*n + 2)*Sn**2, [0, 1]), 0)]
264
+ assert p == q
265
+ p = HolonomicFunction(Dx**2 + 1 + x**3*Dx, x, 0, [2, 3]).to_sequence()
266
+ q = [(HolonomicSequence(n + Sn**2 + (n**2 + 7*n + 12)*Sn**4, [2, 3, -1, Rational(-1, 2), Rational(1, 12)]), 1)]
267
+ assert p == q
268
+ p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence()
269
+ q = [(HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 0, 3)]
270
+ assert p == q
271
+ C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
272
+ p = expr_to_holonomic(log(1+x**2))
273
+ q = [(HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2]), 0, 1)]
274
+ assert p.to_sequence() == q
275
+ p = p.diff()
276
+ q = [(HolonomicSequence((n + 2) + (n + 2)*Sn**2, [C_0, 0]), 1, 0)]
277
+ assert p.to_sequence() == q
278
+ p = expr_to_holonomic(erf(x) + x).to_sequence()
279
+ q = [(HolonomicSequence((2*n**2 - 2*n) + (n**3 + 2*n**2 - n - 2)*Sn**2, [0, 1 + 2/sqrt(pi), 0, C_3]), 0, 2)]
280
+ assert p == q
281
+
282
+ def test_series():
283
+ x = symbols('x')
284
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
285
+ p = HolonomicFunction(Dx**2 + 2*x*Dx, x, 0, [0, 1]).series(n=10)
286
+ q = x - x**3/3 + x**5/10 - x**7/42 + x**9/216 + O(x**10)
287
+ assert p == q
288
+ p = HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
289
+ q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # cos(x)
290
+ r = (p * q).series(n=10) # expansion of cos(x) * exp(x**2)
291
+ s = 1 + x**2/2 + x**4/24 - 31*x**6/720 - 179*x**8/8064 + O(x**10)
292
+ assert r == s
293
+ t = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # log(1 + x)
294
+ r = (p * t + q).series(n=10)
295
+ s = 1 + x - x**2 + 4*x**3/3 - 17*x**4/24 + 31*x**5/30 - 481*x**6/720 +\
296
+ 71*x**7/105 - 20159*x**8/40320 + 379*x**9/840 + O(x**10)
297
+ assert r == s
298
+ p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \
299
+ (4-6*x**3+2*x**4)*Dx**2, x, 0, [0, 1]).series(n=7)
300
+ q = x + x**3/6 - 3*x**4/16 + x**5/20 - 23*x**6/960 + O(x**7)
301
+ assert p == q
302
+ p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \
303
+ (4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7)
304
+ q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7)
305
+ assert p == q
306
+ p = expr_to_holonomic(erf(x) + x).series(n=10)
307
+ C_3 = symbols('C_3')
308
+ q = (erf(x) + x).series(n=10)
309
+ assert p.subs(C_3, -2/(3*sqrt(pi))) == q
310
+ assert expr_to_holonomic(sqrt(x**3 + x)).series(n=10) == sqrt(x**3 + x).series(n=10)
311
+ assert expr_to_holonomic((2*x - 3*x**2)**Rational(1, 3)).series() == ((2*x - 3*x**2)**Rational(1, 3)).series()
312
+ assert expr_to_holonomic(sqrt(x**2-x)).series() == (sqrt(x**2-x)).series()
313
+ assert expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).series(n=10) == (cos(x)**2/x**2).series(n=10)
314
+ assert expr_to_holonomic(cos(x)**2/x**2, x0=1).series(n=10).together() == (cos(x)**2/x**2).series(n=10, x0=1).together()
315
+ assert expr_to_holonomic(cos(x-1)**2/(x-1)**2, x0=1, y0={-2: [1, 0, -1]}).series(n=10) \
316
+ == (cos(x-1)**2/(x-1)**2).series(x0=1, n=10)
317
+
318
+ def test_evalf_euler():
319
+ x = symbols('x')
320
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
321
+
322
+ # log(1+x)
323
+ p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1])
324
+
325
+ # path taken is a straight line from 0 to 1, on the real axis
326
+ r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
327
+ s = '0.699525841805253' # approx. equal to log(2) i.e. 0.693147180559945
328
+ assert sstr(p.evalf(r, method='Euler')[-1]) == s
329
+
330
+ # path taken is a triangle 0-->1+i-->2
331
+ r = [0.1 + 0.1*I]
332
+ for i in range(9):
333
+ r.append(r[-1]+0.1+0.1*I)
334
+ for i in range(10):
335
+ r.append(r[-1]+0.1-0.1*I)
336
+
337
+ # close to the exact solution 1.09861228866811
338
+ # imaginary part also close to zero
339
+ s = '1.07530466271334 - 0.0251200594793912*I'
340
+ assert sstr(p.evalf(r, method='Euler')[-1]) == s
341
+
342
+ # sin(x)
343
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
344
+ s = '0.905546532085401 - 6.93889390390723e-18*I'
345
+ assert sstr(p.evalf(r, method='Euler')[-1]) == s
346
+
347
+ # computing sin(pi/2) using this method
348
+ # using a linear path from 0 to pi/2
349
+ r = [0.1]
350
+ for i in range(14):
351
+ r.append(r[-1] + 0.1)
352
+ r.append(pi/2)
353
+ s = '1.08016557252834' # close to 1.0 (exact solution)
354
+ assert sstr(p.evalf(r, method='Euler')[-1]) == s
355
+
356
+ # trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2)
357
+ # computing the same value sin(pi/2) using different path
358
+ r = [0.1*I]
359
+ for i in range(9):
360
+ r.append(r[-1]+0.1*I)
361
+ for i in range(15):
362
+ r.append(r[-1]+0.1)
363
+ r.append(pi/2+I)
364
+ for i in range(10):
365
+ r.append(r[-1]-0.1*I)
366
+
367
+ # close to 1.0
368
+ s = '0.976882381836257 - 1.65557671738537e-16*I'
369
+ assert sstr(p.evalf(r, method='Euler')[-1]) == s
370
+
371
+ # cos(x)
372
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0])
373
+ # compute cos(pi) along 0-->pi
374
+ r = [0.05]
375
+ for i in range(61):
376
+ r.append(r[-1]+0.05)
377
+ r.append(pi)
378
+ # close to -1 (exact answer)
379
+ s = '-1.08140824719196'
380
+ assert sstr(p.evalf(r, method='Euler')[-1]) == s
381
+
382
+ # a rectangular path (0 -> i -> 2+i -> 2)
383
+ r = [0.1*I]
384
+ for i in range(9):
385
+ r.append(r[-1]+0.1*I)
386
+ for i in range(20):
387
+ r.append(r[-1]+0.1)
388
+ for i in range(10):
389
+ r.append(r[-1]-0.1*I)
390
+
391
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r, method='Euler')
392
+ s = '0.501421652861245 - 3.88578058618805e-16*I'
393
+ assert sstr(p[-1]) == s
394
+
395
+ def test_evalf_rk4():
396
+ x = symbols('x')
397
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
398
+
399
+ # log(1+x)
400
+ p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1])
401
+
402
+ # path taken is a straight line from 0 to 1, on the real axis
403
+ r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
404
+ s = '0.693146363174626' # approx. equal to log(2) i.e. 0.693147180559945
405
+ assert sstr(p.evalf(r)[-1]) == s
406
+
407
+ # path taken is a triangle 0-->1+i-->2
408
+ r = [0.1 + 0.1*I]
409
+ for i in range(9):
410
+ r.append(r[-1]+0.1+0.1*I)
411
+ for i in range(10):
412
+ r.append(r[-1]+0.1-0.1*I)
413
+
414
+ # close to the exact solution 1.09861228866811
415
+ # imaginary part also close to zero
416
+ s = '1.098616 + 1.36083e-7*I'
417
+ assert sstr(p.evalf(r)[-1].n(7)) == s
418
+
419
+ # sin(x)
420
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
421
+ s = '0.90929463522785 + 1.52655665885959e-16*I'
422
+ assert sstr(p.evalf(r)[-1]) == s
423
+
424
+ # computing sin(pi/2) using this method
425
+ # using a linear path from 0 to pi/2
426
+ r = [0.1]
427
+ for i in range(14):
428
+ r.append(r[-1] + 0.1)
429
+ r.append(pi/2)
430
+ s = '0.999999895088917' # close to 1.0 (exact solution)
431
+ assert sstr(p.evalf(r)[-1]) == s
432
+
433
+ # trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2)
434
+ # computing the same value sin(pi/2) using different path
435
+ r = [0.1*I]
436
+ for i in range(9):
437
+ r.append(r[-1]+0.1*I)
438
+ for i in range(15):
439
+ r.append(r[-1]+0.1)
440
+ r.append(pi/2+I)
441
+ for i in range(10):
442
+ r.append(r[-1]-0.1*I)
443
+
444
+ # close to 1.0
445
+ s = '1.00000003415141 + 6.11940487991086e-16*I'
446
+ assert sstr(p.evalf(r)[-1]) == s
447
+
448
+ # cos(x)
449
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0])
450
+ # compute cos(pi) along 0-->pi
451
+ r = [0.05]
452
+ for i in range(61):
453
+ r.append(r[-1]+0.05)
454
+ r.append(pi)
455
+ # close to -1 (exact answer)
456
+ s = '-0.999999993238714'
457
+ assert sstr(p.evalf(r)[-1]) == s
458
+
459
+ # a rectangular path (0 -> i -> 2+i -> 2)
460
+ r = [0.1*I]
461
+ for i in range(9):
462
+ r.append(r[-1]+0.1*I)
463
+ for i in range(20):
464
+ r.append(r[-1]+0.1)
465
+ for i in range(10):
466
+ r.append(r[-1]-0.1*I)
467
+
468
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r)
469
+ s = '0.493152791638442 - 1.41553435639707e-15*I'
470
+ assert sstr(p[-1]) == s
471
+
472
+
473
+ def test_expr_to_holonomic():
474
+ x = symbols('x')
475
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
476
+ p = expr_to_holonomic((sin(x)/x)**2)
477
+ q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \
478
+ [1, 0, Rational(-2, 3)])
479
+ assert p == q
480
+ p = expr_to_holonomic(1/(1+x**2)**2)
481
+ q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, [1])
482
+ assert p == q
483
+ p = expr_to_holonomic(exp(x)*sin(x)+x*log(1+x))
484
+ q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \
485
+ - 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \
486
+ (-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \
487
+ 7*x**2/2 + x + Rational(5, 2))*Dx**4, x, 0, [0, 1, 4, -1])
488
+ assert p == q
489
+ p = expr_to_holonomic(x*exp(x)+cos(x)+1)
490
+ q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \
491
+ 0, [2, 1, 1, 3])
492
+ assert p == q
493
+ assert (x*exp(x)+cos(x)+1).series(n=10) == p.series(n=10)
494
+ p = expr_to_holonomic(log(1 + x)**2 + 1)
495
+ q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2])
496
+ assert p == q
497
+ p = expr_to_holonomic(erf(x)**2 + x)
498
+ q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \
499
+ (x**2+ Rational(1, 4))*Dx**4, x, 0, [0, 1, 8/pi, 0])
500
+ assert p == q
501
+ p = expr_to_holonomic(cosh(x)*x)
502
+ q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1])
503
+ assert p == q
504
+ p = expr_to_holonomic(besselj(2, x))
505
+ q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0])
506
+ assert p == q
507
+ p = expr_to_holonomic(besselj(0, x) + exp(x))
508
+ q = HolonomicFunction((-x**2 - x/2 + S.Half) + (x**2 - x/2 - Rational(3, 2))*Dx + (-x**2 + x/2 + 1)*Dx**2 +\
509
+ (x**2 + x/2)*Dx**3, x, 0, [2, 1, S.Half])
510
+ assert p == q
511
+ p = expr_to_holonomic(sin(x)**2/x)
512
+ q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0])
513
+ assert p == q
514
+ p = expr_to_holonomic(sin(x)**2/x, x0=2)
515
+ q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2,
516
+ sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)])
517
+ assert p == q
518
+ p = expr_to_holonomic(log(x)/2 - Ci(2*x)/2 + Ci(2)/2)
519
+ q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \
520
+ [-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0])
521
+ assert p == q
522
+ p = p.to_expr()
523
+ q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2
524
+ assert p == q
525
+ p = expr_to_holonomic(x**S.Half, x0=1)
526
+ q = HolonomicFunction(x*Dx - S.Half, x, 1, [1])
527
+ assert p == q
528
+ p = expr_to_holonomic(sqrt(1 + x**2))
529
+ q = HolonomicFunction((-x) + (x**2 + 1)*Dx, x, 0, [1])
530
+ assert p == q
531
+ assert (expr_to_holonomic(sqrt(x) + sqrt(2*x)).to_expr()-\
532
+ (sqrt(x) + sqrt(2*x))).simplify() == 0
533
+ assert expr_to_holonomic(3*x+2*sqrt(x)).to_expr() == 3*x+2*sqrt(x)
534
+ p = expr_to_holonomic((x**4+x**3+5*x**2+3*x+2)/x**2, lenics=3)
535
+ q = HolonomicFunction((-2*x**4 - x**3 + 3*x + 4) + (x**5 + x**4 + 5*x**3 + 3*x**2 + \
536
+ 2*x)*Dx, x, 0, {-2: [2, 3, 5]})
537
+ assert p == q
538
+ p = expr_to_holonomic(1/(x-1)**2, lenics=3, x0=1)
539
+ q = HolonomicFunction((2) + (x - 1)*Dx, x, 1, {-2: [1, 0, 0]})
540
+ assert p == q
541
+ a = symbols("a")
542
+ p = expr_to_holonomic(sqrt(a*x), x=x)
543
+ assert p.to_expr() == sqrt(a)*sqrt(x)
544
+
545
+ def test_to_hyper():
546
+ x = symbols('x')
547
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
548
+ p = HolonomicFunction(Dx - 2, x, 0, [3]).to_hyper()
549
+ q = 3 * hyper([], [], 2*x)
550
+ assert p == q
551
+ p = hyperexpand(HolonomicFunction((1 + x) * Dx - 3, x, 0, [2]).to_hyper()).expand()
552
+ q = 2*x**3 + 6*x**2 + 6*x + 2
553
+ assert p == q
554
+ p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_hyper()
555
+ q = -x**2*hyper((2, 2, 1), (3, 2), -x)/2 + x
556
+ assert p == q
557
+ p = HolonomicFunction(2*x*Dx + Dx**2, x, 0, [0, 2/sqrt(pi)]).to_hyper()
558
+ q = 2*x*hyper((S.Half,), (Rational(3, 2),), -x**2)/sqrt(pi)
559
+ assert p == q
560
+ p = hyperexpand(HolonomicFunction(2*x*Dx + Dx**2, x, 0, [1, -2/sqrt(pi)]).to_hyper())
561
+ q = erfc(x)
562
+ assert p.rewrite(erfc) == q
563
+ p = hyperexpand(HolonomicFunction((x**2 - 1) + x*Dx + x**2*Dx**2,
564
+ x, 0, [0, S.Half]).to_hyper())
565
+ q = besselj(1, x)
566
+ assert p == q
567
+ p = hyperexpand(HolonomicFunction(x*Dx**2 + Dx + x, x, 0, [1, 0]).to_hyper())
568
+ q = besselj(0, x)
569
+ assert p == q
570
+
571
+ def test_to_expr():
572
+ x = symbols('x')
573
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
574
+ p = HolonomicFunction(Dx - 1, x, 0, [1]).to_expr()
575
+ q = exp(x)
576
+ assert p == q
577
+ p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).to_expr()
578
+ q = cos(x)
579
+ assert p == q
580
+ p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]).to_expr()
581
+ q = cosh(x)
582
+ assert p == q
583
+ p = HolonomicFunction(2 + (4*x - 1)*Dx + \
584
+ (x**2 - x)*Dx**2, x, 0, [1, 2]).to_expr().expand()
585
+ q = 1/(x**2 - 2*x + 1)
586
+ assert p == q
587
+ p = expr_to_holonomic(sin(x)**2/x).integrate((x, 0, x)).to_expr()
588
+ q = (sin(x)**2/x).integrate((x, 0, x))
589
+ assert p == q
590
+ C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
591
+ p = expr_to_holonomic(log(1+x**2)).to_expr()
592
+ q = C_2*log(x**2 + 1)
593
+ assert p == q
594
+ p = expr_to_holonomic(log(1+x**2)).diff().to_expr()
595
+ q = C_0*x/(x**2 + 1)
596
+ assert p == q
597
+ p = expr_to_holonomic(erf(x) + x).to_expr()
598
+ q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi)
599
+ assert p == q
600
+ p = expr_to_holonomic(sqrt(x), x0=1).to_expr()
601
+ assert p == sqrt(x)
602
+ assert expr_to_holonomic(sqrt(x)).to_expr() == sqrt(x)
603
+ p = expr_to_holonomic(sqrt(1 + x**2)).to_expr()
604
+ assert p == sqrt(1+x**2)
605
+ p = expr_to_holonomic((2*x**2 + 1)**Rational(2, 3)).to_expr()
606
+ assert p == (2*x**2 + 1)**Rational(2, 3)
607
+ p = expr_to_holonomic(sqrt(-x**2+2*x)).to_expr()
608
+ assert p == sqrt(x)*sqrt(-x + 2)
609
+ p = expr_to_holonomic((-2*x**3+7*x)**Rational(2, 3)).to_expr()
610
+ q = x**Rational(2, 3)*(-2*x**2 + 7)**Rational(2, 3)
611
+ assert p == q
612
+ p = from_hyper(hyper((-2, -3), (S.Half, ), x))
613
+ s = hyperexpand(hyper((-2, -3), (S.Half, ), x))
614
+ D_0 = Symbol('D_0')
615
+ C_0 = Symbol('C_0')
616
+ assert (p.to_expr().subs({C_0:1, D_0:0}) - s).simplify() == 0
617
+ p.y0 = {0: [1], S.Half: [0]}
618
+ assert p.to_expr() == s
619
+ assert expr_to_holonomic(x**5).to_expr() == x**5
620
+ assert expr_to_holonomic(2*x**3-3*x**2).to_expr().expand() == \
621
+ 2*x**3-3*x**2
622
+ a = symbols("a")
623
+ p = (expr_to_holonomic(1.4*x)*expr_to_holonomic(a*x, x)).to_expr()
624
+ q = 1.4*a*x**2
625
+ assert p == q
626
+ p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(a*x, x)).to_expr()
627
+ q = x*(a + 1.4)
628
+ assert p == q
629
+ p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(x)).to_expr()
630
+ assert p == 2.4*x
631
+
632
+
633
+ def test_integrate():
634
+ x = symbols('x')
635
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
636
+ p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 2, 3))
637
+ q = '0.166270406994788'
638
+ assert sstr(p) == q
639
+ p = expr_to_holonomic(sin(x)).integrate((x, 0, x)).to_expr()
640
+ q = 1 - cos(x)
641
+ assert p == q
642
+ p = expr_to_holonomic(sin(x)).integrate((x, 0, 3))
643
+ q = 1 - cos(3)
644
+ assert p == q
645
+ p = expr_to_holonomic(sin(x)/x, x0=1).integrate((x, 1, 2))
646
+ q = '0.659329913368450'
647
+ assert sstr(p) == q
648
+ p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 1, 0))
649
+ q = '-0.423690480850035'
650
+ assert sstr(p) == q
651
+ p = expr_to_holonomic(sin(x)/x)
652
+ assert p.integrate(x).to_expr() == Si(x)
653
+ assert p.integrate((x, 0, 2)) == Si(2)
654
+ p = expr_to_holonomic(sin(x)**2/x)
655
+ q = p.to_expr()
656
+ assert p.integrate(x).to_expr() == q.integrate((x, 0, x))
657
+ assert p.integrate((x, 0, 1)) == q.integrate((x, 0, 1))
658
+ assert expr_to_holonomic(1/x, x0=1).integrate(x).to_expr() == log(x)
659
+ p = expr_to_holonomic((x + 1)**3*exp(-x), x0=-1).integrate(x).to_expr()
660
+ q = (-x**3 - 6*x**2 - 15*x + 6*exp(x + 1) - 16)*exp(-x)
661
+ assert p == q
662
+ p = expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).integrate(x).to_expr()
663
+ q = -Si(2*x) - cos(x)**2/x
664
+ assert p == q
665
+ p = expr_to_holonomic(sqrt(x**2+x)).integrate(x).to_expr()
666
+ q = (x**Rational(3, 2)*(2*x**2 + 3*x + 1) - x*sqrt(x + 1)*asinh(sqrt(x)))/(4*x*sqrt(x + 1))
667
+ assert p == q
668
+ p = expr_to_holonomic(sqrt(x**2+1)).integrate(x).to_expr()
669
+ q = (sqrt(x**2+1)).integrate(x)
670
+ assert (p-q).simplify() == 0
671
+ p = expr_to_holonomic(1/x**2, y0={-2:[1, 0, 0]})
672
+ r = expr_to_holonomic(1/x**2, lenics=3)
673
+ assert p == r
674
+ q = expr_to_holonomic(cos(x)**2)
675
+ assert (r*q).integrate(x).to_expr() == -Si(2*x) - cos(x)**2/x
676
+
677
+
678
+ def test_diff():
679
+ x, y = symbols('x, y')
680
+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
681
+ p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1])
682
+ assert p.diff().to_expr() == p.to_expr().diff().simplify()
683
+ p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0])
684
+ assert p.diff(x, 2).to_expr() == p.to_expr()
685
+ p = expr_to_holonomic(Si(x))
686
+ assert p.diff().to_expr() == sin(x)/x
687
+ assert p.diff(y) == 0
688
+ C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
689
+ q = Si(x)
690
+ assert p.diff(x).to_expr() == q.diff()
691
+ assert p.diff(x, 2).to_expr().subs(C_0, Rational(-1, 3)).cancel() == q.diff(x, 2).cancel()
692
+ assert p.diff(x, 3).series().subs({C_3: Rational(-1, 3), C_0: 0}) == q.diff(x, 3).series()
693
+
694
+
695
+ def test_extended_domain_in_expr_to_holonomic():
696
+ x = symbols('x')
697
+ p = expr_to_holonomic(1.2*cos(3.1*x))
698
+ assert p.to_expr() == 1.2*cos(3.1*x)
699
+ assert sstr(p.integrate(x).to_expr()) == '0.387096774193548*sin(3.1*x)'
700
+ _, Dx = DifferentialOperators(RR.old_poly_ring(x), 'Dx')
701
+ p = expr_to_holonomic(1.1329138213*x)
702
+ q = HolonomicFunction((-1.1329138213) + (1.1329138213*x)*Dx, x, 0, {1: [1.1329138213]})
703
+ assert p == q
704
+ assert p.to_expr() == 1.1329138213*x
705
+ assert sstr(p.integrate((x, 1, 2))) == sstr((1.1329138213*x).integrate((x, 1, 2)))
706
+ y, z = symbols('y, z')
707
+ p = expr_to_holonomic(sin(x*y*z), x=x)
708
+ assert p.to_expr() == sin(x*y*z)
709
+ assert p.integrate(x).to_expr() == (-cos(x*y*z) + 1)/(y*z)
710
+ p = expr_to_holonomic(sin(x*y + z), x=x).integrate(x).to_expr()
711
+ q = (cos(z) - cos(x*y + z))/y
712
+ assert p == q
713
+ a = symbols('a')
714
+ p = expr_to_holonomic(a*x, x)
715
+ assert p.to_expr() == a*x
716
+ assert p.integrate(x).to_expr() == a*x**2/2
717
+ D_2, C_1 = symbols("D_2, C_1")
718
+ p = expr_to_holonomic(x) + expr_to_holonomic(1.2*cos(x))
719
+ p = p.to_expr().subs(D_2, 0)
720
+ assert p - x - 1.2*cos(1.0*x) == 0
721
+ p = expr_to_holonomic(x) * expr_to_holonomic(1.2*cos(x))
722
+ p = p.to_expr().subs(C_1, 0)
723
+ assert p - 1.2*x*cos(1.0*x) == 0
724
+
725
+
726
+ def test_to_meijerg():
727
+ x = symbols('x')
728
+ assert hyperexpand(expr_to_holonomic(sin(x)).to_meijerg()) == sin(x)
729
+ assert hyperexpand(expr_to_holonomic(cos(x)).to_meijerg()) == cos(x)
730
+ assert hyperexpand(expr_to_holonomic(exp(x)).to_meijerg()) == exp(x)
731
+ assert hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() == log(x)
732
+ assert expr_to_holonomic(4*x**2/3 + 7).to_meijerg() == 4*x**2/3 + 7
733
+ assert hyperexpand(expr_to_holonomic(besselj(2, x), lenics=3).to_meijerg()) == besselj(2, x)
734
+ p = hyper((Rational(-1, 2), -3), (), x)
735
+ assert from_hyper(p).to_meijerg() == hyperexpand(p)
736
+ p = hyper((S.One, S(3)), (S(2), ), x)
737
+ assert (hyperexpand(from_hyper(p).to_meijerg()) - hyperexpand(p)).expand() == 0
738
+ p = from_hyper(hyper((-2, -3), (S.Half, ), x))
739
+ s = hyperexpand(hyper((-2, -3), (S.Half, ), x))
740
+ C_0 = Symbol('C_0')
741
+ C_1 = Symbol('C_1')
742
+ D_0 = Symbol('D_0')
743
+ assert (hyperexpand(p.to_meijerg()).subs({C_0:1, D_0:0}) - s).simplify() == 0
744
+ p.y0 = {0: [1], S.Half: [0]}
745
+ assert (hyperexpand(p.to_meijerg()) - s).simplify() == 0
746
+ p = expr_to_holonomic(besselj(S.Half, x), initcond=False)
747
+ assert (p.to_expr() - (D_0*sin(x) + C_0*cos(x) + C_1*sin(x))/sqrt(x)).simplify() == 0
748
+ p = expr_to_holonomic(besselj(S.Half, x), y0={Rational(-1, 2): [sqrt(2)/sqrt(pi), sqrt(2)/sqrt(pi)]})
749
+ assert (p.to_expr() - besselj(S.Half, x) - besselj(Rational(-1, 2), x)).simplify() == 0
750
+
751
+
752
+ def test_gaussian():
753
+ mu, x = symbols("mu x")
754
+ sd = symbols("sd", positive=True)
755
+ Q = QQ[mu, sd].get_field()
756
+ e = sqrt(2)*exp(-(-mu + x)**2/(2*sd**2))/(2*sqrt(pi)*sd)
757
+ h1 = expr_to_holonomic(e, x, domain=Q)
758
+
759
+ _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
760
+ h2 = HolonomicFunction((-mu/sd**2 + x/sd**2) + (1)*Dx, x)
761
+
762
+ assert h1 == h2
763
+
764
+
765
+ def test_beta():
766
+ a, b, x = symbols("a b x", positive=True)
767
+ e = x**(a - 1)*(-x + 1)**(b - 1)/beta(a, b)
768
+ Q = QQ[a, b].get_field()
769
+ h1 = expr_to_holonomic(e, x, domain=Q)
770
+
771
+ _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
772
+ h2 = HolonomicFunction((a + x*(-a - b + 2) - 1) + (x**2 - x)*Dx, x)
773
+
774
+ assert h1 == h2
775
+
776
+
777
+ def test_gamma():
778
+ a, b, x = symbols("a b x", positive=True)
779
+ e = b**(-a)*x**(a - 1)*exp(-x/b)/gamma(a)
780
+ Q = QQ[a, b].get_field()
781
+ h1 = expr_to_holonomic(e, x, domain=Q)
782
+
783
+ _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
784
+ h2 = HolonomicFunction((-a + 1 + x/b) + (x)*Dx, x)
785
+
786
+ assert h1 == h2
787
+
788
+
789
+ def test_symbolic_power():
790
+ x, n = symbols("x n")
791
+ Q = QQ[n].get_field()
792
+ _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
793
+ h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -n
794
+ h2 = HolonomicFunction((n) + (x)*Dx, x)
795
+
796
+ assert h1 == h2
797
+
798
+
799
+ def test_negative_power():
800
+ x = symbols("x")
801
+ _, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
802
+ h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -2
803
+ h2 = HolonomicFunction((2) + (x)*Dx, x)
804
+
805
+ assert h1 == h2
806
+
807
+
808
+ def test_expr_in_power():
809
+ x, n = symbols("x n")
810
+ Q = QQ[n].get_field()
811
+ _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
812
+ h1 = HolonomicFunction((-1) + (x)*Dx, x) ** (n - 3)
813
+ h2 = HolonomicFunction((-n + 3) + (x)*Dx, x)
814
+
815
+ assert h1 == h2
816
+
817
+ def test_DifferentialOperatorEqPoly():
818
+ x = symbols('x', integer=True)
819
+ R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
820
+ do = DifferentialOperator([x**2, R.base.zero, R.base.zero], R)
821
+ do2 = DifferentialOperator([x**2, 1, x], R)
822
+ assert not do == do2
823
+
824
+ # polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799
825
+ # should work once that is solved
826
+ # p = do.listofpoly[0]
827
+ # assert do == p
828
+
829
+ p2 = do2.listofpoly[0]
830
+ assert not do2 == p2
venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.holonomic.recurrence import RecurrenceOperators, RecurrenceOperator
2
+ from sympy.core.symbol import symbols
3
+ from sympy.polys.domains.rationalfield import QQ
4
+
5
+ def test_RecurrenceOperator():
6
+ n = symbols('n', integer=True)
7
+ R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
8
+ assert Sn*n == (n + 1)*Sn
9
+ assert Sn*n**2 == (n**2+1+2*n)*Sn
10
+ assert Sn**2*n**2 == (n**2 + 4*n + 4)*Sn**2
11
+ p = (Sn**3*n**2 + Sn*n)**2
12
+ q = (n**2 + 3*n + 2)*Sn**2 + (2*n**3 + 19*n**2 + 57*n + 52)*Sn**4 + (n**4 + 18*n**3 + \
13
+ 117*n**2 + 324*n + 324)*Sn**6
14
+ assert p == q
15
+
16
+ def test_RecurrenceOperatorEqPoly():
17
+ n = symbols('n', integer=True)
18
+ R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
19
+ rr = RecurrenceOperator([n**2, 0, 0], R)
20
+ rr2 = RecurrenceOperator([n**2, 1, n], R)
21
+ assert not rr == rr2
22
+
23
+ # polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799
24
+ # should work once that is solved
25
+ # d = rr.listofpoly[0]
26
+ # assert rr == d
27
+
28
+ d2 = rr2.listofpoly[0]
29
+ assert not rr2 == d2
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc ADDED
Binary file (7.62 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc ADDED
Binary file (42.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc ADDED
Binary file (8.44 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/setexpr.cpython-310.pyc ADDED
Binary file (3.41 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc ADDED
Binary file (81.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc ADDED
Binary file (6.88 kB). View file