diff --git a/ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt b/ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..8e3feb5b63ee4e0ab6c0f560d1aa788975fe40b3 --- /dev/null +++ b/ckpts/universal/global_step80/zero/10.mlp.dense_4h_to_h.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4586809e8477531c1be667ed9f40288eae4f575c7b55deea0fe8d345feb3f76e +size 33555627 diff --git a/ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/fp32.pt b/ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..eb15a45470dd5981ac983412c3213b044cf3a3a9 --- /dev/null +++ b/ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2392581b4eb4d1171c6475b42694faef618df8fc29305229fc81673dd2b0083 +size 50332749 diff --git a/ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/exp_avg.pt b/ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..2d8aab8bb2f0d21e9eced2ac51897072f74fd032 --- /dev/null +++ b/ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08708ef57b0072b691d4f8166bac6c0c0ae15dd6b88bda166f219b73053d5324 +size 50332828 diff --git a/ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg_sq.pt b/ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..6fefae3b10c047ca253b7211f70ecbdda2f8f188 --- /dev/null +++ b/ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac2ec226fa03c790b2817a0f76128b0342851bc719449d17039b576a38fdec97 +size 33555627 diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/__init__.py b/venv/lib/python3.10/site-packages/sympy/discrete/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..968c4caa0d4562b71285f414bfb70f43d0b35111 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/__init__.py @@ -0,0 +1,20 @@ +"""This module contains functions which operate on discrete sequences. + +Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``, + ``mobius_transform``, ``inverse_mobius_transform`` + +Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``, + ``convolution_fwht``, ``convolution_subset``, + ``covering_product``, ``intersecting_product`` +""" + +from .transforms import (fft, ifft, ntt, intt, fwht, ifwht, + mobius_transform, inverse_mobius_transform) +from .convolutions import convolution, covering_product, intersecting_product + +__all__ = [ + 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform', + 'inverse_mobius_transform', + + 'convolution', 'covering_product', 'intersecting_product', +] diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39a3daf1a0d3cf153e78069e28f3c10fc43c4765 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5eba3d1fcaab593c381b41ee5ee3f32c2befac10 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..318739610bd5b1f90192c5776c8be49d654c4643 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b2605ad33342879a2482584ff789fcbae13dba4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py b/venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py new file mode 100644 index 0000000000000000000000000000000000000000..42b3d799f301dba129af3a7838f2475fc7db8e4e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py @@ -0,0 +1,488 @@ +""" +Convolution (using **FFT**, **NTT**, **FWHT**), Subset Convolution, +Covering Product, Intersecting Product +""" + +from sympy.core import S, sympify +from sympy.core.function import expand_mul +from sympy.discrete.transforms import ( + fft, ifft, ntt, intt, fwht, ifwht, + mobius_transform, inverse_mobius_transform) +from sympy.utilities.iterables import iterable +from sympy.utilities.misc import as_int + + +def convolution(a, b, cycle=0, dps=None, prime=None, dyadic=None, subset=None): + """ + Performs convolution by determining the type of desired + convolution using hints. + + Exactly one of ``dps``, ``prime``, ``dyadic``, ``subset`` arguments + should be specified explicitly for identifying the type of convolution, + and the argument ``cycle`` can be specified optionally. + + For the default arguments, linear convolution is performed using **FFT**. + + Parameters + ========== + + a, b : iterables + The sequences for which convolution is performed. + cycle : Integer + Specifies the length for doing cyclic convolution. + dps : Integer + Specifies the number of decimal digits for precision for + performing **FFT** on the sequence. + prime : Integer + Prime modulus of the form `(m 2^k + 1)` to be used for + performing **NTT** on the sequence. + dyadic : bool + Identifies the convolution type as dyadic (*bitwise-XOR*) + convolution, which is performed using **FWHT**. + subset : bool + Identifies the convolution type as subset convolution. + + Examples + ======== + + >>> from sympy import convolution, symbols, S, I + >>> u, v, w, x, y, z = symbols('u v w x y z') + + >>> convolution([1 + 2*I, 4 + 3*I], [S(5)/4, 6], dps=3) + [1.25 + 2.5*I, 11.0 + 15.8*I, 24.0 + 18.0*I] + >>> convolution([1, 2, 3], [4, 5, 6], cycle=3) + [31, 31, 28] + + >>> convolution([111, 777], [888, 444], prime=19*2**10 + 1) + [1283, 19351, 14219] + >>> convolution([111, 777], [888, 444], prime=19*2**10 + 1, cycle=2) + [15502, 19351] + + >>> convolution([u, v], [x, y, z], dyadic=True) + [u*x + v*y, u*y + v*x, u*z, v*z] + >>> convolution([u, v], [x, y, z], dyadic=True, cycle=2) + [u*x + u*z + v*y, u*y + v*x + v*z] + + >>> convolution([u, v, w], [x, y, z], subset=True) + [u*x, u*y + v*x, u*z + w*x, v*z + w*y] + >>> convolution([u, v, w], [x, y, z], subset=True, cycle=3) + [u*x + v*z + w*y, u*y + v*x, u*z + w*x] + + """ + + c = as_int(cycle) + if c < 0: + raise ValueError("The length for cyclic convolution " + "must be non-negative") + + dyadic = True if dyadic else None + subset = True if subset else None + if sum(x is not None for x in (prime, dps, dyadic, subset)) > 1: + raise TypeError("Ambiguity in determining the type of convolution") + + if prime is not None: + ls = convolution_ntt(a, b, prime=prime) + return ls if not c else [sum(ls[i::c]) % prime for i in range(c)] + + if dyadic: + ls = convolution_fwht(a, b) + elif subset: + ls = convolution_subset(a, b) + else: + ls = convolution_fft(a, b, dps=dps) + + return ls if not c else [sum(ls[i::c]) for i in range(c)] + + +#----------------------------------------------------------------------------# +# # +# Convolution for Complex domain # +# # +#----------------------------------------------------------------------------# + +def convolution_fft(a, b, dps=None): + """ + Performs linear convolution using Fast Fourier Transform. + + Parameters + ========== + + a, b : iterables + The sequences for which convolution is performed. + dps : Integer + Specifies the number of decimal digits for precision. + + Examples + ======== + + >>> from sympy import S, I + >>> from sympy.discrete.convolutions import convolution_fft + + >>> convolution_fft([2, 3], [4, 5]) + [8, 22, 15] + >>> convolution_fft([2, 5], [6, 7, 3]) + [12, 44, 41, 15] + >>> convolution_fft([1 + 2*I, 4 + 3*I], [S(5)/4, 6]) + [5/4 + 5*I/2, 11 + 63*I/4, 24 + 18*I] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Convolution_theorem + .. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29 + + """ + + a, b = a[:], b[:] + n = m = len(a) + len(b) - 1 # convolution size + + if n > 0 and n&(n - 1): # not a power of 2 + n = 2**n.bit_length() + + # padding with zeros + a += [S.Zero]*(n - len(a)) + b += [S.Zero]*(n - len(b)) + + a, b = fft(a, dps), fft(b, dps) + a = [expand_mul(x*y) for x, y in zip(a, b)] + a = ifft(a, dps)[:m] + + return a + + +#----------------------------------------------------------------------------# +# # +# Convolution for GF(p) # +# # +#----------------------------------------------------------------------------# + +def convolution_ntt(a, b, prime): + """ + Performs linear convolution using Number Theoretic Transform. + + Parameters + ========== + + a, b : iterables + The sequences for which convolution is performed. + prime : Integer + Prime modulus of the form `(m 2^k + 1)` to be used for performing + **NTT** on the sequence. + + Examples + ======== + + >>> from sympy.discrete.convolutions import convolution_ntt + >>> convolution_ntt([2, 3], [4, 5], prime=19*2**10 + 1) + [8, 22, 15] + >>> convolution_ntt([2, 5], [6, 7, 3], prime=19*2**10 + 1) + [12, 44, 41, 15] + >>> convolution_ntt([333, 555], [222, 666], prime=19*2**10 + 1) + [15555, 14219, 19404] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Convolution_theorem + .. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29 + + """ + + a, b, p = a[:], b[:], as_int(prime) + n = m = len(a) + len(b) - 1 # convolution size + + if n > 0 and n&(n - 1): # not a power of 2 + n = 2**n.bit_length() + + # padding with zeros + a += [0]*(n - len(a)) + b += [0]*(n - len(b)) + + a, b = ntt(a, p), ntt(b, p) + a = [x*y % p for x, y in zip(a, b)] + a = intt(a, p)[:m] + + return a + + +#----------------------------------------------------------------------------# +# # +# Convolution for 2**n-group # +# # +#----------------------------------------------------------------------------# + +def convolution_fwht(a, b): + """ + Performs dyadic (*bitwise-XOR*) convolution using Fast Walsh Hadamard + Transform. + + The convolution is automatically padded to the right with zeros, as the + *radix-2 FWHT* requires the number of sample points to be a power of 2. + + Parameters + ========== + + a, b : iterables + The sequences for which convolution is performed. + + Examples + ======== + + >>> from sympy import symbols, S, I + >>> from sympy.discrete.convolutions import convolution_fwht + + >>> u, v, x, y = symbols('u v x y') + >>> convolution_fwht([u, v], [x, y]) + [u*x + v*y, u*y + v*x] + + >>> convolution_fwht([2, 3], [4, 5]) + [23, 22] + >>> convolution_fwht([2, 5 + 4*I, 7], [6*I, 7, 3 + 4*I]) + [56 + 68*I, -10 + 30*I, 6 + 50*I, 48 + 32*I] + + >>> convolution_fwht([S(33)/7, S(55)/6, S(7)/4], [S(2)/3, 5]) + [2057/42, 1870/63, 7/6, 35/4] + + References + ========== + + .. [1] https://www.radioeng.cz/fulltexts/2002/02_03_40_42.pdf + .. [2] https://en.wikipedia.org/wiki/Hadamard_transform + + """ + + if not a or not b: + return [] + + a, b = a[:], b[:] + n = max(len(a), len(b)) + + if n&(n - 1): # not a power of 2 + n = 2**n.bit_length() + + # padding with zeros + a += [S.Zero]*(n - len(a)) + b += [S.Zero]*(n - len(b)) + + a, b = fwht(a), fwht(b) + a = [expand_mul(x*y) for x, y in zip(a, b)] + a = ifwht(a) + + return a + + +#----------------------------------------------------------------------------# +# # +# Subset Convolution # +# # +#----------------------------------------------------------------------------# + +def convolution_subset(a, b): + """ + Performs Subset Convolution of given sequences. + + The indices of each argument, considered as bit strings, correspond to + subsets of a finite set. + + The sequence is automatically padded to the right with zeros, as the + definition of subset based on bitmasks (indices) requires the size of + sequence to be a power of 2. + + Parameters + ========== + + a, b : iterables + The sequences for which convolution is performed. + + Examples + ======== + + >>> from sympy import symbols, S + >>> from sympy.discrete.convolutions import convolution_subset + >>> u, v, x, y, z = symbols('u v x y z') + + >>> convolution_subset([u, v], [x, y]) + [u*x, u*y + v*x] + >>> convolution_subset([u, v, x], [y, z]) + [u*y, u*z + v*y, x*y, x*z] + + >>> convolution_subset([1, S(2)/3], [3, 4]) + [3, 6] + >>> convolution_subset([1, 3, S(5)/7], [7]) + [7, 21, 5, 0] + + References + ========== + + .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf + + """ + + if not a or not b: + return [] + + if not iterable(a) or not iterable(b): + raise TypeError("Expected a sequence of coefficients for convolution") + + a = [sympify(arg) for arg in a] + b = [sympify(arg) for arg in b] + n = max(len(a), len(b)) + + if n&(n - 1): # not a power of 2 + n = 2**n.bit_length() + + # padding with zeros + a += [S.Zero]*(n - len(a)) + b += [S.Zero]*(n - len(b)) + + c = [S.Zero]*n + + for mask in range(n): + smask = mask + while smask > 0: + c[mask] += expand_mul(a[smask] * b[mask^smask]) + smask = (smask - 1)&mask + + c[mask] += expand_mul(a[smask] * b[mask^smask]) + + return c + + +#----------------------------------------------------------------------------# +# # +# Covering Product # +# # +#----------------------------------------------------------------------------# + +def covering_product(a, b): + """ + Returns the covering product of given sequences. + + The indices of each argument, considered as bit strings, correspond to + subsets of a finite set. + + The covering product of given sequences is a sequence which contains + the sum of products of the elements of the given sequences grouped by + the *bitwise-OR* of the corresponding indices. + + The sequence is automatically padded to the right with zeros, as the + definition of subset based on bitmasks (indices) requires the size of + sequence to be a power of 2. + + Parameters + ========== + + a, b : iterables + The sequences for which covering product is to be obtained. + + Examples + ======== + + >>> from sympy import symbols, S, I, covering_product + >>> u, v, x, y, z = symbols('u v x y z') + + >>> covering_product([u, v], [x, y]) + [u*x, u*y + v*x + v*y] + >>> covering_product([u, v, x], [y, z]) + [u*y, u*z + v*y + v*z, x*y, x*z] + + >>> covering_product([1, S(2)/3], [3, 4 + 5*I]) + [3, 26/3 + 25*I/3] + >>> covering_product([1, 3, S(5)/7], [7, 8]) + [7, 53, 5, 40/7] + + References + ========== + + .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf + + """ + + if not a or not b: + return [] + + a, b = a[:], b[:] + n = max(len(a), len(b)) + + if n&(n - 1): # not a power of 2 + n = 2**n.bit_length() + + # padding with zeros + a += [S.Zero]*(n - len(a)) + b += [S.Zero]*(n - len(b)) + + a, b = mobius_transform(a), mobius_transform(b) + a = [expand_mul(x*y) for x, y in zip(a, b)] + a = inverse_mobius_transform(a) + + return a + + +#----------------------------------------------------------------------------# +# # +# Intersecting Product # +# # +#----------------------------------------------------------------------------# + +def intersecting_product(a, b): + """ + Returns the intersecting product of given sequences. + + The indices of each argument, considered as bit strings, correspond to + subsets of a finite set. + + The intersecting product of given sequences is the sequence which + contains the sum of products of the elements of the given sequences + grouped by the *bitwise-AND* of the corresponding indices. + + The sequence is automatically padded to the right with zeros, as the + definition of subset based on bitmasks (indices) requires the size of + sequence to be a power of 2. + + Parameters + ========== + + a, b : iterables + The sequences for which intersecting product is to be obtained. + + Examples + ======== + + >>> from sympy import symbols, S, I, intersecting_product + >>> u, v, x, y, z = symbols('u v x y z') + + >>> intersecting_product([u, v], [x, y]) + [u*x + u*y + v*x, v*y] + >>> intersecting_product([u, v, x], [y, z]) + [u*y + u*z + v*y + x*y + x*z, v*z, 0, 0] + + >>> intersecting_product([1, S(2)/3], [3, 4 + 5*I]) + [9 + 5*I, 8/3 + 10*I/3] + >>> intersecting_product([1, 3, S(5)/7], [7, 8]) + [327/7, 24, 0, 0] + + References + ========== + + .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf + + """ + + if not a or not b: + return [] + + a, b = a[:], b[:] + n = max(len(a), len(b)) + + if n&(n - 1): # not a power of 2 + n = 2**n.bit_length() + + # padding with zeros + a += [S.Zero]*(n - len(a)) + b += [S.Zero]*(n - len(b)) + + a, b = mobius_transform(a, subset=False), mobius_transform(b, subset=False) + a = [expand_mul(x*y) for x, y in zip(a, b)] + a = inverse_mobius_transform(a, subset=False) + + return a diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py b/venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py new file mode 100644 index 0000000000000000000000000000000000000000..0b0ed80d304161cf9ca298321aedc094c8cae1b3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py @@ -0,0 +1,166 @@ +""" +Recurrences +""" + +from sympy.core import S, sympify +from sympy.utilities.iterables import iterable +from sympy.utilities.misc import as_int + + +def linrec(coeffs, init, n): + r""" + Evaluation of univariate linear recurrences of homogeneous type + having coefficients independent of the recurrence variable. + + Parameters + ========== + + coeffs : iterable + Coefficients of the recurrence + init : iterable + Initial values of the recurrence + n : Integer + Point of evaluation for the recurrence + + Notes + ===== + + Let `y(n)` be the recurrence of given type, ``c`` be the sequence + of coefficients, ``b`` be the sequence of initial/base values of the + recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence. + Then, + + .. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\ + c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k + \end{cases} + + Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation + that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is + replaced by the corresponding value `x_i`. The sequence is then a solution + of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where + `p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic + polynomial. + + Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear + combination of powers `x^i`). Now, if `x^n` is congruent to + `g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then + `T(x^n) = x_n` is equal to + `T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`. + + Computation of `x^n`, + given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}` + is performed using exponentiation by squaring (refer to [1_]) with + an additional reduction step performed to retain only first `k` powers + of `x` in the representation of `x^n`. + + Examples + ======== + + >>> from sympy.discrete.recurrences import linrec + >>> from sympy.abc import x, y, z + + >>> linrec(coeffs=[1, 1], init=[0, 1], n=10) + 55 + + >>> linrec(coeffs=[1, 1], init=[x, y], n=10) + 34*x + 55*y + + >>> linrec(coeffs=[x, y], init=[0, 1], n=5) + x**2*y + x*(x**3 + 2*x*y) + y**2 + + >>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16) + 13576*x + 5676*y + 2356*z + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring + .. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation§ion=6#Matrices + + See Also + ======== + + sympy.polys.agca.extensions.ExtensionElement.__pow__ + + """ + + if not coeffs: + return S.Zero + + if not iterable(coeffs): + raise TypeError("Expected a sequence of coefficients for" + " the recurrence") + + if not iterable(init): + raise TypeError("Expected a sequence of values for the initialization" + " of the recurrence") + + n = as_int(n) + if n < 0: + raise ValueError("Point of evaluation of recurrence must be a " + "non-negative integer") + + c = [sympify(arg) for arg in coeffs] + b = [sympify(arg) for arg in init] + k = len(c) + + if len(b) > k: + raise TypeError("Count of initial values should not exceed the " + "order of the recurrence") + else: + b += [S.Zero]*(k - len(b)) # remaining initial values default to zero + + if n < k: + return b[n] + terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)] + return sum(terms[:-1], terms[-1]) + + +def linrec_coeffs(c, n): + r""" + Compute the coefficients of n'th term in linear recursion + sequence defined by c. + + `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`. + + It computes the coefficients by using binary exponentiation. + This function is used by `linrec` and `_eval_pow_by_cayley`. + + Parameters + ========== + + c = coefficients of the divisor polynomial + n = exponent of x, so dividend is x^n + + """ + + k = len(c) + + def _square_and_reduce(u, offset): + # squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and + # multiplies by `x` if offset is 1) and reduces the above result of + # length upto `2k` to `k` using the characteristic equation of the + # recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}` + + w = [S.Zero]*(2*len(u) - 1 + offset) + for i, p in enumerate(u): + for j, q in enumerate(u): + w[offset + i + j] += p*q + + for j in range(len(w) - 1, k - 1, -1): + for i in range(k): + w[j - i - 1] += w[j]*c[i] + + return w[:k] + + def _final_coeffs(n): + # computes the final coefficient list - `cf` corresponding to the + # point at which recurrence is to be evalauted - `n`, such that, + # `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)` + + if n < k: + return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1) + else: + return _square_and_reduce(_final_coeffs(n // 2), n % 2) + + return _final_coeffs(n) diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdeec164df91159dd132f239a0b72f71c923f9a2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..292e35e47c952cf10f006b909f8e1c93f12b07b1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2bbc4ff93cf8da552f5cdc082d6f932c5746ef7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84e2c7b11a4ce8beb1f02b622fa5088874fe0286 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py b/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py new file mode 100644 index 0000000000000000000000000000000000000000..0c125f21a26a9e6df8ba7743c9d90e3480d06531 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py @@ -0,0 +1,365 @@ +from sympy.core.numbers import (E, Rational, pi) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.core import S, symbols, I +from sympy.discrete.convolutions import ( + convolution, convolution_fft, convolution_ntt, convolution_fwht, + convolution_subset, covering_product, intersecting_product) +from sympy.testing.pytest import raises +from sympy.abc import x, y + +def test_convolution(): + # fft + a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] + b = [9, 5, 5, 4, 3, 2] + c = [3, 5, 3, 7, 8] + d = [1422, 6572, 3213, 5552] + + assert convolution(a, b) == convolution_fft(a, b) + assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9) + assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7) + assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3) + + # prime moduli of the form (m*2**k + 1), sequence length + # should be a divisor of 2**k + p = 7*17*2**23 + 1 + q = 19*2**10 + 1 + + # ntt + assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q) + assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p) + assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p) + raises(TypeError, lambda: convolution(b, d, dps=5, prime=q)) + raises(TypeError, lambda: convolution(b, d, dps=6, prime=q)) + + # fwht + assert convolution(a, b, dyadic=True) == convolution_fwht(a, b) + assert convolution(a, b, dyadic=False) == convolution(a, b) + raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True)) + raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True)) + raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True)) + raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True)) + + # subset + assert convolution(a, b, subset=True) == convolution_subset(a, b) == \ + convolution(a, b, subset=True, dyadic=False) == \ + convolution(a, b, subset=True) + assert convolution(a, b, subset=False) == convolution(a, b) + raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True)) + raises(TypeError, lambda: convolution(c, d, subset=True, dps=6)) + raises(TypeError, lambda: convolution(a, c, subset=True, prime=q)) + + +def test_cyclic_convolution(): + # fft + a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] + b = [9, 5, 5, 4, 3, 2] + + assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \ + convolution([1, 2, 3], [4, 5, 6], cycle=5) == \ + convolution([1, 2, 3], [4, 5, 6]) + + assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28] + + a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)] + b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)] + + assert convolution(a, b, cycle=0) == \ + convolution(a, b, cycle=len(a) + len(b) - 1) + + assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340), + Rational(11125, 4032), Rational(3653, 1080)] + + assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24), + Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)] + + assert convolution(a, b, cycle=9) == \ + convolution(a, b, cycle=0) + [S.Zero] + + # ntt + a = [2313, 5323532, S(3232), 42142, 42242421] + b = [S(33456), 56757, 45754, 432423] + + assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \ + convolution(a, b, prime=19*2**10 + 1, cycle=8) == \ + convolution(a, b, prime=19*2**10 + 1) + + assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664, + 15534, 3517] + + assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260, + 15534, 3517, 16314, 13688] + + assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \ + convolution(a, b, prime=19*2**10 + 1) + [0] + + # fwht + u, v, w, x, y = symbols('u v w x y') + p, q, r, s, t = symbols('p q r s t') + c = [u, v, w, x, y] + d = [p, q, r, s, t] + + assert convolution(a, b, dyadic=True, cycle=3) == \ + [2499522285783, 19861417974796, 4702176579021] + + assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143, + 2114320852171, 20571217906407, 246166418903, 1413262436976] + + assert convolution(c, d, dyadic=True, cycle=4) == \ + [p*u + p*y + q*v + r*w + s*x + t*u + t*y, + p*v + q*u + q*y + r*x + s*w + t*v, + p*w + q*x + r*u + r*y + s*v + t*w, + p*x + q*w + r*v + s*u + s*y + t*x] + + assert convolution(c, d, dyadic=True, cycle=6) == \ + [p*u + q*v + r*w + r*y + s*x + t*w + t*y, + p*v + q*u + r*x + s*w + s*y + t*x, + p*w + q*x + r*u + s*v, + p*x + q*w + r*v + s*u, + p*y + t*u, + q*y + t*v] + + # subset + assert convolution(a, b, subset=True, cycle=7) == [18266671799811, + 178235365533, 213958794, 246166418903, 1413262436976, + 2397553088697, 1932759730434] + + assert convolution(a[1:], b, subset=True, cycle=4) == \ + [178104086592, 302255835516, 244982785880, 3717819845434] + + assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162, + 178235365533, 213958794, 245166224504, 1413262436976, 2397553088697] + + assert convolution(c, d, subset=True, cycle=3) == \ + [p*u + p*x + q*w + r*v + r*y + s*u + t*w, + p*v + p*y + q*u + s*y + t*u + t*x, + p*w + q*y + r*u + t*v] + + assert convolution(c, d, subset=True, cycle=5) == \ + [p*u + q*y + t*v, + p*v + q*u + r*y + t*w, + p*w + r*u + s*y + t*x, + p*x + q*w + r*v + s*u, + p*y + t*u] + + raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1)) + + +def test_convolution_fft(): + assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3)) + assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18] + assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7] + assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21] + + assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I] + assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \ + [Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175] + + assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \ + [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)] + + assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \ + [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)] + + assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \ + [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6), + sqrt(2)/pi + 1, sqrt(2)*exp(-1)] + + assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \ + [12350041, 190918524, 374911166, 2362431729] + + assert convolution_fft([312313, 31278232], [32139631, 319631]) == \ + [10037624576503, 1005370659728895, 9997492572392] + + raises(TypeError, lambda: convolution_fft(x, y)) + raises(ValueError, lambda: convolution_fft([x, y], [y, x])) + + +def test_convolution_ntt(): + # prime moduli of the form (m*2**k + 1), sequence length + # should be a divisor of 2**k + p = 7*17*2**23 + 1 + q = 19*2**10 + 1 + r = 2*500000003 + 1 # only for sequences of length 1 or 2 + # s = 2*3*5*7 # composite modulus + + assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r)) + assert convolution_ntt([2], [3], r) == [6] + assert convolution_ntt([2, 3], [4], r) == [8, 12] + + assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619, + 459741727, 79180879, 831885249, 381344700, 369993322] + assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \ + [8158, 3065, 3682, 7090, 1239, 2232, 3744] + + assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \ + convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q) + assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \ + convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q) + + raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r)) + raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q)) + raises(TypeError, lambda: convolution_ntt(x, y, p)) + + +def test_convolution_fwht(): + assert convolution_fwht([], []) == [] + assert convolution_fwht([], [1]) == [] + assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27] + + assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \ + [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)] + + a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I] + b = [94, 51, 53, 45, 31, 27, 13] + c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8] + + assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I, + 45*sqrt(3) + Rational(5848, 15) + 135*I, + 94*sqrt(3) + Rational(1257, 5) + 65*I, + 51*sqrt(3) + Rational(3974, 15), + 13*sqrt(3) + 452 + 470*I, + Rational(4513, 15) + 255*I, + 31*sqrt(3) + Rational(1314, 5) + 265*I, + 27*sqrt(3) + Rational(3676, 15) + 225*I] + + assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I, + Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I, + Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I] + + assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5, + Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0] + + u, v, w, x, y, z = symbols('u v w x y z') + + assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x] + + assert convolution_fwht([u, v, w], [x, y]) == \ + [u*x + v*y, u*y + v*x, w*x, w*y] + + assert convolution_fwht([u, v, w], [x, y, z]) == \ + [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y] + + raises(TypeError, lambda: convolution_fwht(x, y)) + raises(TypeError, lambda: convolution_fwht(x*y, u + v)) + + +def test_convolution_subset(): + assert convolution_subset([], []) == [] + assert convolution_subset([], [Rational(1, 3)]) == [] + assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7] + + a = [1, Rational(5, 3), sqrt(3), 4 + 5*I] + b = [64, 71, 55, 47, 33, 29, 15] + c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9] + + assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3), + 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84, + 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I] + + assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3, + 613 + I*110/3, Rational(5013, 5) + I*1249/3, + 675 + 22*I, 891 + I*751/3, + 771 + 10*I, Rational(3736, 5) + 105*I] + + assert convolution_subset(a, c) == convolution_subset(c, a) + assert convolution_subset(a[:2], b) == \ + [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25] + + assert convolution_subset(a[:2], c) == \ + [3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0] + + u, v, w, x, y, z = symbols('u v w x y z') + + assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y] + assert convolution_subset([u, v, w, x], [y, z]) == \ + [u*y, u*z + v*y, w*y, w*z + x*y] + + assert convolution_subset([u, v], [x, y, z]) == \ + convolution_subset([x, y, z], [u, v]) + + raises(TypeError, lambda: convolution_subset(x, z)) + raises(TypeError, lambda: convolution_subset(Rational(7, 3), u)) + + +def test_covering_product(): + assert covering_product([], []) == [] + assert covering_product([], [Rational(1, 3)]) == [] + assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7] + + a = [1, Rational(5, 8), sqrt(7), 4 + 9*I] + b = [66, 81, 95, 49, 37, 89, 17] + c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91] + + assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7), + 130*sqrt(7) + 1303 + 2619*I, 37, + Rational(671, 4), 17 + 54*sqrt(7), + 89*sqrt(7) + Rational(4661, 8) + 1287*I] + + assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I, + 1412 + I*190/3, Rational(42684, 5) + I*31202/3, + 9484 + I*74/3, 22163 + I*27394/3, + 10621 + I*34/3, Rational(90236, 15) + 1224*I] + + assert covering_product(a, c) == covering_product(c, a) + assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I, + 1412 + I*190/3, Rational(42684, 5) + I*31202/3, + 111 + I*74/3, 6693 + I*27394/3, + 429 + I*34/3, Rational(23351, 15) + 1224*I] + + assert covering_product(a, c[:-1]) == [3 + I*2/3, + Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3, + -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15] + + u, v, w, x, y, z = symbols('u v w x y z') + + assert covering_product([u, v, w], [x, y]) == \ + [u*x, u*y + v*x + v*y, w*x, w*y] + + assert covering_product([u, v, w, x], [y, z]) == \ + [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z] + + assert covering_product([u, v], [x, y, z]) == \ + covering_product([x, y, z], [u, v]) + + raises(TypeError, lambda: covering_product(x, z)) + raises(TypeError, lambda: covering_product(Rational(7, 3), u)) + + +def test_intersecting_product(): + assert intersecting_product([], []) == [] + assert intersecting_product([], [Rational(1, 3)]) == [] + assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7] + + a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I] + b = [67, 51, 65, 48, 36, 79, 27] + c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13] + + assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I, + 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I, + 192 + 336*I, 0, 0, 0, 0] + + assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5, + Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0] + + assert intersecting_product(a, c) == intersecting_product(c, a) + assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5, + Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0] + + assert intersecting_product(a, c[:-2]) == \ + [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40, + -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0] + + u, v, w, x, y, z = symbols('u v w x y z') + + assert intersecting_product([u, v, w], [x, y]) == \ + [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0] + + assert intersecting_product([u, v, w, x], [y, z]) == \ + [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0] + + assert intersecting_product([u, v], [x, y, z]) == \ + intersecting_product([x, y, z], [u, v]) + + raises(TypeError, lambda: intersecting_product(x, z)) + raises(TypeError, lambda: intersecting_product(u, Rational(8, 3))) diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py b/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2186ca525b6680350a03edbe44ca88f8f95c3c --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py @@ -0,0 +1,59 @@ +from sympy.core.numbers import Rational +from sympy.functions.combinatorial.numbers import fibonacci +from sympy.core import S, symbols +from sympy.testing.pytest import raises +from sympy.discrete.recurrences import linrec + +def test_linrec(): + assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946 + assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040 + assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384 + assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165 + assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \ + 56889923441670659718376223533331214868804815612050381493741233489928913241 + assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \ + 702633573874937994980598979769135096432444135301118916539 + + assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4) + assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5) + + assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n) + for n in range(95, 115)) + + assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1) + for n in range(595, 615)) + + a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)] + b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6] + x, y, z = symbols('x y z') + + assert linrec(coeffs=a[:5], init=b[:4], n=80) == \ + Rational(1726244235456268979436592226626304376013002142588105090705187189, + 1960143456748895967474334873705475211264) + + assert linrec(coeffs=a[:4], init=b[:4], n=50) == \ + Rational(368949940033050147080268092104304441, 504857282956046106624) + + assert linrec(coeffs=a[3:], init=b[:3], n=35) == \ + Rational(97409272177295731943657945116791049305244422833125109, + 814315512679031689453125) + + assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \ + Rational(26777668739896791448594650497024, 48084516708184142230517578125) + + raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1)) + raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000)) + raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000)) + raises(TypeError, lambda: linrec(x, b, n=10000)) + raises(TypeError, lambda: linrec(a, y, n=10000)) + + assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \ + x**2 + x*y + x*z + y + z + assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \ + 269542*x + 664575*y + 578949*z + assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \ + 58516436*x + 56372788*y + assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \ + 11477135884896*x + 25999077948732*y + 41975630244216*z + assert linrec(coeffs=[], init=[1, 1], n=20) == 0 + assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3 diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py b/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..385514be4cdec2f19cf3a750bdbe0f4f6e21cc6e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py @@ -0,0 +1,154 @@ +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.core import S, Symbol, symbols, I, Rational +from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht, + mobius_transform, inverse_mobius_transform) +from sympy.testing.pytest import raises + + +def test_fft_ifft(): + assert all(tf(ls) == ls for tf in (fft, ifft) + for ls in ([], [Rational(5, 3)])) + + ls = list(range(6)) + fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I, + -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3, + -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I, + 2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2] + + assert fft(ls) == fls + assert ifft(fls) == ls + [S.Zero]*2 + + ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] + ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4] + + assert ifft(ls) == ifls + assert fft(ifls) == ls + [S.Zero] + + x = Symbol('x', real=True) + raises(TypeError, lambda: fft(x)) + raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3])) + + +def test_ntt_intt(): + # prime moduli of the form (m*2**k + 1), sequence length + # should be a divisor of 2**k + p = 7*17*2**23 + 1 + q = 2*500000003 + 1 # only for sequences of length 1 or 2 + r = 2*3*5*7 # composite modulus + + assert all(tf(ls, p) == ls for tf in (ntt, intt) + for ls in ([], [5])) + + ls = list(range(6)) + nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224, + 259751156, 12232587] + + assert ntt(ls, p) == nls + assert intt(nls, p) == ls + [0]*2 + + ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] + x = Symbol('x', integer=True) + + raises(TypeError, lambda: ntt(x, p)) + raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p)) + raises(ValueError, lambda: intt(ls, p)) + raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p)) + raises(ValueError, lambda: ntt([3, 5, 6], q)) + raises(ValueError, lambda: ntt([4, 5, 7], r)) + raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p)) + + +def test_fwht_ifwht(): + assert all(tf(ls) == ls for tf in (fwht, ifwht) \ + for ls in ([], [Rational(7, 4)])) + + ls = [213, 321, 43235, 5325, 312, 53] + fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277] + + assert fwht(ls) == fls + assert ifwht(fls) == ls + [S.Zero]*2 + + ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)] + ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I, + Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I] + + assert ifwht(ls) == ifls + assert fwht(ifls) == ls + [S.Zero]*3 + + x, y = symbols('x y') + + raises(TypeError, lambda: fwht(x)) + + ls = [x, 2*x, 3*x**2, 4*x**3] + ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4), + -x**3 + 3*x**2/4 - x/4, + -x**3 - 3*x**2/4 + x*Rational(3, 4), + x**3 - 3*x**2/4 - x/4] + + assert ifwht(ls) == ifls + assert fwht(ifls) == ls + + ls = [x, y, x**2, y**2, x*y] + fls = [x**2 + x*y + x + y**2 + y, + x**2 + x*y + x - y**2 - y, + -x**2 + x*y + x - y**2 + y, + -x**2 + x*y + x + y**2 - y, + x**2 - x*y + x + y**2 + y, + x**2 - x*y + x - y**2 - y, + -x**2 - x*y + x - y**2 + y, + -x**2 - x*y + x + y**2 - y] + + assert fwht(ls) == fls + assert ifwht(fls) == ls + [S.Zero]*3 + + ls = list(range(6)) + + assert fwht(ls) == [x*8 for x in ifwht(ls)] + + +def test_mobius_transform(): + assert all(tf(ls, subset=subset) == ls + for ls in ([], [Rational(7, 4)]) for subset in (True, False) + for tf in (mobius_transform, inverse_mobius_transform)) + + w, x, y, z = symbols('w x y z') + + assert mobius_transform([x, y]) == [x, x + y] + assert inverse_mobius_transform([x, x + y]) == [x, y] + assert mobius_transform([x, y], subset=False) == [x + y, y] + assert inverse_mobius_transform([x + y, y], subset=False) == [x, y] + + assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z] + assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \ + [w, x, y, z] + assert mobius_transform([w, x, y, z], subset=False) == \ + [w + x + y + z, x + z, y + z, z] + assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \ + [w, x, y, z] + + ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I] + mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168), + Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I, + Rational(2153, 168) + 7*I] + + assert mobius_transform(ls) == mls + assert inverse_mobius_transform(mls) == ls + [S.Zero]*3 + + mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0] + + assert mobius_transform(ls, subset=False) == mls + assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3 + + ls = ls[:-1] + mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)] + + assert mobius_transform(ls) == mls + assert inverse_mobius_transform(mls) == ls + + mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9] + + assert mobius_transform(ls, subset=False) == mls + assert inverse_mobius_transform(mls, subset=False) == ls + + raises(TypeError, lambda: mobius_transform(x, subset=True)) + raises(TypeError, lambda: inverse_mobius_transform(y, subset=False)) diff --git a/venv/lib/python3.10/site-packages/sympy/discrete/transforms.py b/venv/lib/python3.10/site-packages/sympy/discrete/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3550837021a4cf99e38c6b15f89ce8bb69b25a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/discrete/transforms.py @@ -0,0 +1,425 @@ +""" +Discrete Fourier Transform, Number Theoretic Transform, +Walsh Hadamard Transform, Mobius Transform +""" + +from sympy.core import S, Symbol, sympify +from sympy.core.function import expand_mul +from sympy.core.numbers import pi, I +from sympy.functions.elementary.trigonometric import sin, cos +from sympy.ntheory import isprime, primitive_root +from sympy.utilities.iterables import ibin, iterable +from sympy.utilities.misc import as_int + + +#----------------------------------------------------------------------------# +# # +# Discrete Fourier Transform # +# # +#----------------------------------------------------------------------------# + +def _fourier_transform(seq, dps, inverse=False): + """Utility function for the Discrete Fourier Transform""" + + if not iterable(seq): + raise TypeError("Expected a sequence of numeric coefficients " + "for Fourier Transform") + + a = [sympify(arg) for arg in seq] + if any(x.has(Symbol) for x in a): + raise ValueError("Expected non-symbolic coefficients") + + n = len(a) + if n < 2: + return a + + b = n.bit_length() - 1 + if n&(n - 1): # not a power of 2 + b += 1 + n = 2**b + + a += [S.Zero]*(n - len(a)) + for i in range(1, n): + j = int(ibin(i, b, str=True)[::-1], 2) + if i < j: + a[i], a[j] = a[j], a[i] + + ang = -2*pi/n if inverse else 2*pi/n + + if dps is not None: + ang = ang.evalf(dps + 2) + + w = [cos(ang*i) + I*sin(ang*i) for i in range(n // 2)] + + h = 2 + while h <= n: + hf, ut = h // 2, n // h + for i in range(0, n, h): + for j in range(hf): + u, v = a[i + j], expand_mul(a[i + j + hf]*w[ut * j]) + a[i + j], a[i + j + hf] = u + v, u - v + h *= 2 + + if inverse: + a = [(x/n).evalf(dps) for x in a] if dps is not None \ + else [x/n for x in a] + + return a + + +def fft(seq, dps=None): + r""" + Performs the Discrete Fourier Transform (**DFT**) in the complex domain. + + The sequence is automatically padded to the right with zeros, as the + *radix-2 FFT* requires the number of sample points to be a power of 2. + + This method should be used with default arguments only for short sequences + as the complexity of expressions increases with the size of the sequence. + + Parameters + ========== + + seq : iterable + The sequence on which **DFT** is to be applied. + dps : Integer + Specifies the number of decimal digits for precision. + + Examples + ======== + + >>> from sympy import fft, ifft + + >>> fft([1, 2, 3, 4]) + [10, -2 - 2*I, -2, -2 + 2*I] + >>> ifft(_) + [1, 2, 3, 4] + + >>> ifft([1, 2, 3, 4]) + [5/2, -1/2 + I/2, -1/2, -1/2 - I/2] + >>> fft(_) + [1, 2, 3, 4] + + >>> ifft([1, 7, 3, 4], dps=15) + [3.75, -0.5 - 0.75*I, -1.75, -0.5 + 0.75*I] + >>> fft(_) + [1.0, 7.0, 3.0, 4.0] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm + .. [2] https://mathworld.wolfram.com/FastFourierTransform.html + + """ + + return _fourier_transform(seq, dps=dps) + + +def ifft(seq, dps=None): + return _fourier_transform(seq, dps=dps, inverse=True) + +ifft.__doc__ = fft.__doc__ + + +#----------------------------------------------------------------------------# +# # +# Number Theoretic Transform # +# # +#----------------------------------------------------------------------------# + +def _number_theoretic_transform(seq, prime, inverse=False): + """Utility function for the Number Theoretic Transform""" + + if not iterable(seq): + raise TypeError("Expected a sequence of integer coefficients " + "for Number Theoretic Transform") + + p = as_int(prime) + if not isprime(p): + raise ValueError("Expected prime modulus for " + "Number Theoretic Transform") + + a = [as_int(x) % p for x in seq] + + n = len(a) + if n < 1: + return a + + b = n.bit_length() - 1 + if n&(n - 1): + b += 1 + n = 2**b + + if (p - 1) % n: + raise ValueError("Expected prime modulus of the form (m*2**k + 1)") + + a += [0]*(n - len(a)) + for i in range(1, n): + j = int(ibin(i, b, str=True)[::-1], 2) + if i < j: + a[i], a[j] = a[j], a[i] + + pr = primitive_root(p) + + rt = pow(pr, (p - 1) // n, p) + if inverse: + rt = pow(rt, p - 2, p) + + w = [1]*(n // 2) + for i in range(1, n // 2): + w[i] = w[i - 1]*rt % p + + h = 2 + while h <= n: + hf, ut = h // 2, n // h + for i in range(0, n, h): + for j in range(hf): + u, v = a[i + j], a[i + j + hf]*w[ut * j] + a[i + j], a[i + j + hf] = (u + v) % p, (u - v) % p + h *= 2 + + if inverse: + rv = pow(n, p - 2, p) + a = [x*rv % p for x in a] + + return a + + +def ntt(seq, prime): + r""" + Performs the Number Theoretic Transform (**NTT**), which specializes the + Discrete Fourier Transform (**DFT**) over quotient ring `Z/pZ` for prime + `p` instead of complex numbers `C`. + + The sequence is automatically padded to the right with zeros, as the + *radix-2 NTT* requires the number of sample points to be a power of 2. + + Parameters + ========== + + seq : iterable + The sequence on which **DFT** is to be applied. + prime : Integer + Prime modulus of the form `(m 2^k + 1)` to be used for performing + **NTT** on the sequence. + + Examples + ======== + + >>> from sympy import ntt, intt + >>> ntt([1, 2, 3, 4], prime=3*2**8 + 1) + [10, 643, 767, 122] + >>> intt(_, 3*2**8 + 1) + [1, 2, 3, 4] + >>> intt([1, 2, 3, 4], prime=3*2**8 + 1) + [387, 415, 384, 353] + >>> ntt(_, prime=3*2**8 + 1) + [1, 2, 3, 4] + + References + ========== + + .. [1] http://www.apfloat.org/ntt.html + .. [2] https://mathworld.wolfram.com/NumberTheoreticTransform.html + .. [3] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29 + + """ + + return _number_theoretic_transform(seq, prime=prime) + + +def intt(seq, prime): + return _number_theoretic_transform(seq, prime=prime, inverse=True) + +intt.__doc__ = ntt.__doc__ + + +#----------------------------------------------------------------------------# +# # +# Walsh Hadamard Transform # +# # +#----------------------------------------------------------------------------# + +def _walsh_hadamard_transform(seq, inverse=False): + """Utility function for the Walsh Hadamard Transform""" + + if not iterable(seq): + raise TypeError("Expected a sequence of coefficients " + "for Walsh Hadamard Transform") + + a = [sympify(arg) for arg in seq] + n = len(a) + if n < 2: + return a + + if n&(n - 1): + n = 2**n.bit_length() + + a += [S.Zero]*(n - len(a)) + h = 2 + while h <= n: + hf = h // 2 + for i in range(0, n, h): + for j in range(hf): + u, v = a[i + j], a[i + j + hf] + a[i + j], a[i + j + hf] = u + v, u - v + h *= 2 + + if inverse: + a = [x/n for x in a] + + return a + + +def fwht(seq): + r""" + Performs the Walsh Hadamard Transform (**WHT**), and uses Hadamard + ordering for the sequence. + + The sequence is automatically padded to the right with zeros, as the + *radix-2 FWHT* requires the number of sample points to be a power of 2. + + Parameters + ========== + + seq : iterable + The sequence on which WHT is to be applied. + + Examples + ======== + + >>> from sympy import fwht, ifwht + >>> fwht([4, 2, 2, 0, 0, 2, -2, 0]) + [8, 0, 8, 0, 8, 8, 0, 0] + >>> ifwht(_) + [4, 2, 2, 0, 0, 2, -2, 0] + + >>> ifwht([19, -1, 11, -9, -7, 13, -15, 5]) + [2, 0, 4, 0, 3, 10, 0, 0] + >>> fwht(_) + [19, -1, 11, -9, -7, 13, -15, 5] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Hadamard_transform + .. [2] https://en.wikipedia.org/wiki/Fast_Walsh%E2%80%93Hadamard_transform + + """ + + return _walsh_hadamard_transform(seq) + + +def ifwht(seq): + return _walsh_hadamard_transform(seq, inverse=True) + +ifwht.__doc__ = fwht.__doc__ + + +#----------------------------------------------------------------------------# +# # +# Mobius Transform for Subset Lattice # +# # +#----------------------------------------------------------------------------# + +def _mobius_transform(seq, sgn, subset): + r"""Utility function for performing Mobius Transform using + Yate's Dynamic Programming method""" + + if not iterable(seq): + raise TypeError("Expected a sequence of coefficients") + + a = [sympify(arg) for arg in seq] + + n = len(a) + if n < 2: + return a + + if n&(n - 1): + n = 2**n.bit_length() + + a += [S.Zero]*(n - len(a)) + + if subset: + i = 1 + while i < n: + for j in range(n): + if j & i: + a[j] += sgn*a[j ^ i] + i *= 2 + + else: + i = 1 + while i < n: + for j in range(n): + if j & i: + continue + a[j] += sgn*a[j ^ i] + i *= 2 + + return a + + +def mobius_transform(seq, subset=True): + r""" + Performs the Mobius Transform for subset lattice with indices of + sequence as bitmasks. + + The indices of each argument, considered as bit strings, correspond + to subsets of a finite set. + + The sequence is automatically padded to the right with zeros, as the + definition of subset/superset based on bitmasks (indices) requires + the size of sequence to be a power of 2. + + Parameters + ========== + + seq : iterable + The sequence on which Mobius Transform is to be applied. + subset : bool + Specifies if Mobius Transform is applied by enumerating subsets + or supersets of the given set. + + Examples + ======== + + >>> from sympy import symbols + >>> from sympy import mobius_transform, inverse_mobius_transform + >>> x, y, z = symbols('x y z') + + >>> mobius_transform([x, y, z]) + [x, x + y, x + z, x + y + z] + >>> inverse_mobius_transform(_) + [x, y, z, 0] + + >>> mobius_transform([x, y, z], subset=False) + [x + y + z, y, z, 0] + >>> inverse_mobius_transform(_, subset=False) + [x, y, z, 0] + + >>> mobius_transform([1, 2, 3, 4]) + [1, 3, 4, 10] + >>> inverse_mobius_transform(_) + [1, 2, 3, 4] + >>> mobius_transform([1, 2, 3, 4], subset=False) + [10, 6, 7, 4] + >>> inverse_mobius_transform(_, subset=False) + [1, 2, 3, 4] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula + .. [2] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf + .. [3] https://arxiv.org/pdf/1211.0189.pdf + + """ + + return _mobius_transform(seq, sgn=+1, subset=subset) + +def inverse_mobius_transform(seq, subset=True): + return _mobius_transform(seq, sgn=-1, subset=subset) + +inverse_mobius_transform.__doc__ = mobius_transform.__doc__ diff --git a/venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..703e74481ad609fe2692b7f8fd5068992975b63c Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/__init__.py b/venv/lib/python3.10/site-packages/sympy/holonomic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45412acad0ab9e5c7424b1888648a638ef208142 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/__init__.py @@ -0,0 +1,18 @@ +r""" +The :py:mod:`~sympy.holonomic` module is intended to deal with holonomic functions along +with various operations on them like addition, multiplication, composition, +integration and differentiation. The module also implements various kinds of +conversions such as converting holonomic functions to a different form and the +other way around. +""" + +from .holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators, + from_hyper, from_meijerg, expr_to_holonomic) +from .recurrence import RecurrenceOperators, RecurrenceOperator, HolonomicSequence + +__all__ = [ + 'DifferentialOperator', 'HolonomicFunction', 'DifferentialOperators', + 'from_hyper', 'from_meijerg', 'expr_to_holonomic', + + 'RecurrenceOperators', 'RecurrenceOperator', 'HolonomicSequence', +] diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80086ea5c4ae0293f6151a558a7f13c9afa33ef6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85745a79691ee22821fcd150ff4bfb78559a27ba Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ce413ee0993bf814ac4c4c16d6a294c2cf044b7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fd8240dcd93f49c6681bd34fc940ff79e5b3a07 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a9c089fe4e52821f0592b184dadc24d8dc87ea9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/holonomic.py b/venv/lib/python3.10/site-packages/sympy/holonomic/holonomic.py new file mode 100644 index 0000000000000000000000000000000000000000..0065f9e02a607c202f35db960540996f034ff40b --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/holonomic.py @@ -0,0 +1,2899 @@ +""" +This module implements Holonomic Functions and +various operations on them. +""" + +from sympy.core import Add, Mul, Pow +from sympy.core.numbers import (NaN, Infinity, NegativeInfinity, Float, I, pi, + equal_valued) +from sympy.core.singleton import S +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, Symbol +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import binomial, factorial, rf +from sympy.functions.elementary.exponential import exp_polar, exp, log +from sympy.functions.elementary.hyperbolic import (cosh, sinh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin, sinc) +from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi) +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import hyper, meijerg +from sympy.integrals import meijerint +from sympy.matrices import Matrix +from sympy.polys.rings import PolyElement +from sympy.polys.fields import FracElement +from sympy.polys.domains import QQ, RR +from sympy.polys.polyclasses import DMF +from sympy.polys.polyroots import roots +from sympy.polys.polytools import Poly +from sympy.polys.matrices import DomainMatrix +from sympy.printing import sstr +from sympy.series.limits import limit +from sympy.series.order import Order +from sympy.simplify.hyperexpand import hyperexpand +from sympy.simplify.simplify import nsimplify +from sympy.solvers.solvers import solve + +from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators +from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError, + SingularityError, NotHolonomicError) + + +def _find_nonzero_solution(r, homosys): + ones = lambda shape: DomainMatrix.ones(shape, r.domain) + particular, nullspace = r._solve(homosys) + nullity = nullspace.shape[0] + nullpart = ones((1, nullity)) * nullspace + sol = (particular + nullpart).transpose() + return sol + + + +def DifferentialOperators(base, generator): + r""" + This function is used to create annihilators using ``Dx``. + + Explanation + =========== + + Returns an Algebra of Differential Operators also called Weyl Algebra + and the operator for differentiation i.e. the ``Dx`` operator. + + Parameters + ========== + + base: + Base polynomial ring for the algebra. + The base polynomial ring is the ring of polynomials in :math:`x` that + will appear as coefficients in the operators. + generator: + Generator of the algebra which can + be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D". + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.abc import x + >>> from sympy.holonomic.holonomic import DifferentialOperators + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + >>> R + Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x] + >>> Dx*x + (1) + (x)*Dx + """ + + ring = DifferentialOperatorAlgebra(base, generator) + return (ring, ring.derivative_operator) + + +class DifferentialOperatorAlgebra: + r""" + An Ore Algebra is a set of noncommutative polynomials in the + intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`. + It follows the commutation rule: + + .. math :: + Dxa = \sigma(a)Dx + \delta(a) + + for :math:`a \subset A`. + + Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A` + is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`. + + If one takes the sigma as identity map and delta as the standard derivation + then it becomes the algebra of Differential Operators also called + a Weyl Algebra i.e. an algebra whose elements are Differential Operators. + + This class represents a Weyl Algebra and serves as the parent ring for + Differential Operators. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy import symbols + >>> from sympy.holonomic.holonomic import DifferentialOperators + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + >>> R + Univariate Differential Operator Algebra in intermediate Dx over the base ring + ZZ[x] + + See Also + ======== + + DifferentialOperator + """ + + def __init__(self, base, generator): + # the base polynomial ring for the algebra + self.base = base + # the operator representing differentiation i.e. `Dx` + self.derivative_operator = DifferentialOperator( + [base.zero, base.one], self) + + if generator is None: + self.gen_symbol = Symbol('Dx', commutative=False) + else: + if isinstance(generator, str): + self.gen_symbol = Symbol(generator, commutative=False) + elif isinstance(generator, Symbol): + self.gen_symbol = generator + + def __str__(self): + string = 'Univariate Differential Operator Algebra in intermediate '\ + + sstr(self.gen_symbol) + ' over the base ring ' + \ + (self.base).__str__() + + return string + + __repr__ = __str__ + + def __eq__(self, other): + if self.base == other.base and self.gen_symbol == other.gen_symbol: + return True + else: + return False + + +class DifferentialOperator: + """ + Differential Operators are elements of Weyl Algebra. The Operators + are defined by a list of polynomials in the base ring and the + parent ring of the Operator i.e. the algebra it belongs to. + + Explanation + =========== + + Takes a list of polynomials for each power of ``Dx`` and the + parent ring which must be an instance of DifferentialOperatorAlgebra. + + A Differential Operator can be created easily using + the operator ``Dx``. See examples below. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + + >>> DifferentialOperator([0, 1, x**2], R) + (1)*Dx + (x**2)*Dx**2 + + >>> (x*Dx*x + 1 - Dx**2)**2 + (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 + + See Also + ======== + + DifferentialOperatorAlgebra + """ + + _op_priority = 20 + + def __init__(self, list_of_poly, parent): + """ + Parameters + ========== + + list_of_poly: + List of polynomials belonging to the base ring of the algebra. + parent: + Parent algebra of the operator. + """ + + # the parent ring for this operator + # must be an DifferentialOperatorAlgebra object + self.parent = parent + base = self.parent.base + self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0] + # sequence of polynomials in x for each power of Dx + # the list should not have trailing zeroes + # represents the operator + # convert the expressions into ring elements using from_sympy + for i, j in enumerate(list_of_poly): + if not isinstance(j, base.dtype): + list_of_poly[i] = base.from_sympy(sympify(j)) + else: + list_of_poly[i] = base.from_sympy(base.to_sympy(j)) + + self.listofpoly = list_of_poly + # highest power of `Dx` + self.order = len(self.listofpoly) - 1 + + def __mul__(self, other): + """ + Multiplies two DifferentialOperator and returns another + DifferentialOperator instance using the commutation rule + Dx*a = a*Dx + a' + """ + + listofself = self.listofpoly + + if not isinstance(other, DifferentialOperator): + if not isinstance(other, self.parent.base.dtype): + listofother = [self.parent.base.from_sympy(sympify(other))] + + else: + listofother = [other] + else: + listofother = other.listofpoly + + # multiplies a polynomial `b` with a list of polynomials + def _mul_dmp_diffop(b, listofother): + if isinstance(listofother, list): + sol = [] + for i in listofother: + sol.append(i * b) + return sol + else: + return [b * listofother] + + sol = _mul_dmp_diffop(listofself[0], listofother) + + # compute Dx^i * b + def _mul_Dxi_b(b): + sol1 = [self.parent.base.zero] + sol2 = [] + + if isinstance(b, list): + for i in b: + sol1.append(i) + sol2.append(i.diff()) + else: + sol1.append(self.parent.base.from_sympy(b)) + sol2.append(self.parent.base.from_sympy(b).diff()) + + return _add_lists(sol1, sol2) + + for i in range(1, len(listofself)): + # find Dx^i * b in ith iteration + listofother = _mul_Dxi_b(listofother) + # solution = solution + listofself[i] * (Dx^i * b) + sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) + + return DifferentialOperator(sol, self.parent) + + def __rmul__(self, other): + if not isinstance(other, DifferentialOperator): + + if not isinstance(other, self.parent.base.dtype): + other = (self.parent.base).from_sympy(sympify(other)) + + sol = [] + for j in self.listofpoly: + sol.append(other * j) + + return DifferentialOperator(sol, self.parent) + + def __add__(self, other): + if isinstance(other, DifferentialOperator): + + sol = _add_lists(self.listofpoly, other.listofpoly) + return DifferentialOperator(sol, self.parent) + + else: + list_self = self.listofpoly + if not isinstance(other, self.parent.base.dtype): + list_other = [((self.parent).base).from_sympy(sympify(other))] + else: + list_other = [other] + sol = [] + sol.append(list_self[0] + list_other[0]) + sol += list_self[1:] + + return DifferentialOperator(sol, self.parent) + + __radd__ = __add__ + + def __sub__(self, other): + return self + (-1) * other + + def __rsub__(self, other): + return (-1) * self + other + + def __neg__(self): + return -1 * self + + def __truediv__(self, other): + return self * (S.One / other) + + def __pow__(self, n): + if n == 1: + return self + if n == 0: + return DifferentialOperator([self.parent.base.one], self.parent) + + # if self is `Dx` + if self.listofpoly == self.parent.derivative_operator.listofpoly: + sol = [self.parent.base.zero]*n + sol.append(self.parent.base.one) + return DifferentialOperator(sol, self.parent) + + # the general case + else: + if n % 2 == 1: + powreduce = self**(n - 1) + return powreduce * self + elif n % 2 == 0: + powreduce = self**(n / 2) + return powreduce * powreduce + + def __str__(self): + listofpoly = self.listofpoly + print_str = '' + + for i, j in enumerate(listofpoly): + if j == self.parent.base.zero: + continue + + if i == 0: + print_str += '(' + sstr(j) + ')' + continue + + if print_str: + print_str += ' + ' + + if i == 1: + print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol) + continue + + print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i) + + return print_str + + __repr__ = __str__ + + def __eq__(self, other): + if isinstance(other, DifferentialOperator): + if self.listofpoly == other.listofpoly and self.parent == other.parent: + return True + else: + return False + else: + if self.listofpoly[0] == other: + for i in self.listofpoly[1:]: + if i is not self.parent.base.zero: + return False + return True + else: + return False + + def is_singular(self, x0): + """ + Checks if the differential equation is singular at x0. + """ + + base = self.parent.base + return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x) + + +class HolonomicFunction: + r""" + A Holonomic Function is a solution to a linear homogeneous ordinary + differential equation with polynomial coefficients. This differential + equation can also be represented by an annihilator i.e. a Differential + Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions, + initial conditions can also be provided along with the annihilator. + + Explanation + =========== + + Holonomic functions have closure properties and thus forms a ring. + Given two Holonomic Functions f and g, their sum, product, + integral and derivative is also a Holonomic Function. + + For ordinary points initial condition should be a vector of values of + the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`. + + For regular singular points initial conditions can also be provided in this + format: + :math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}` + where s0, s1, ... are the roots of indicial equation and vectors + :math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial + terms of the associated power series. See Examples below. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols, S + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + + >>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x + >>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x) + + >>> p + q # annihilator of e^x + sin(x) + HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1]) + + >>> p * q # annihilator of e^x * sin(x) + HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1]) + + An example of initial conditions for regular singular points, + the indicial equation has only one root `1/2`. + + >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}) + HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]}) + + >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr() + sqrt(x) + + To plot a Holonomic Function, one can use `.evalf()` for numerical + computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib. + + >>> import sympy.holonomic # doctest: +SKIP + >>> from sympy import var, sin # doctest: +SKIP + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> import numpy as np # doctest: +SKIP + >>> var("x") # doctest: +SKIP + >>> r = np.linspace(1, 5, 100) # doctest: +SKIP + >>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP + >>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + + """ + + _op_priority = 20 + + def __init__(self, annihilator, x, x0=0, y0=None): + """ + + Parameters + ========== + + annihilator: + Annihilator of the Holonomic Function, represented by a + `DifferentialOperator` object. + x: + Variable of the function. + x0: + The point at which initial conditions are stored. + Generally an integer. + y0: + The initial condition. The proper format for the initial condition + is described in class docstring. To make the function unique, + length of the vector `y0` should be equal to or greater than the + order of differential equation. + """ + + # initial condition + self.y0 = y0 + # the point for initial conditions, default is zero. + self.x0 = x0 + # differential operator L such that L.f = 0 + self.annihilator = annihilator + self.x = x + + def __str__(self): + if self._have_init_cond(): + str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\ + sstr(self.x), sstr(self.x0), sstr(self.y0)) + else: + str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\ + sstr(self.x)) + + return str_sol + + __repr__ = __str__ + + def unify(self, other): + """ + Unifies the base polynomial ring of a given two Holonomic + Functions. + """ + + R1 = self.annihilator.parent.base + R2 = other.annihilator.parent.base + + dom1 = R1.dom + dom2 = R2.dom + + if R1 == R2: + return (self, other) + + R = (dom1.unify(dom2)).old_poly_ring(self.x) + + newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol)) + + sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly] + sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly] + + sol1 = DifferentialOperator(sol1, newparent) + sol2 = DifferentialOperator(sol2, newparent) + + sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0) + sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0) + + return (sol1, sol2) + + def is_singularics(self): + """ + Returns True if the function have singular initial condition + in the dictionary format. + + Returns False if the function have ordinary initial condition + in the list format. + + Returns None for all other cases. + """ + + if isinstance(self.y0, dict): + return True + elif isinstance(self.y0, list): + return False + + def _have_init_cond(self): + """ + Checks if the function have initial condition. + """ + return bool(self.y0) + + def _singularics_to_ord(self): + """ + Converts a singular initial condition to ordinary if possible. + """ + a = list(self.y0)[0] + b = self.y0[a] + + if len(self.y0) == 1 and a == int(a) and a > 0: + y0 = [] + a = int(a) + for i in range(a): + y0.append(S.Zero) + y0 += [j * factorial(a + i) for i, j in enumerate(b)] + + return HolonomicFunction(self.annihilator, self.x, self.x0, y0) + + def __add__(self, other): + # if the ground domains are different + if self.annihilator.parent.base != other.annihilator.parent.base: + a, b = self.unify(other) + return a + b + + deg1 = self.annihilator.order + deg2 = other.annihilator.order + dim = max(deg1, deg2) + R = self.annihilator.parent.base + K = R.get_field() + + rowsself = [self.annihilator] + rowsother = [other.annihilator] + gen = self.annihilator.parent.derivative_operator + + # constructing annihilators up to order dim + for i in range(dim - deg1): + diff1 = (gen * rowsself[-1]) + rowsself.append(diff1) + + for i in range(dim - deg2): + diff2 = (gen * rowsother[-1]) + rowsother.append(diff2) + + row = rowsself + rowsother + + # constructing the matrix of the ansatz + r = [] + + for expr in row: + p = [] + for i in range(dim + 1): + if i >= len(expr.listofpoly): + p.append(K.zero) + else: + p.append(K.new(expr.listofpoly[i].rep)) + r.append(p) + + # solving the linear system using gauss jordan solver + r = DomainMatrix(r, (len(row), dim+1), K).transpose() + homosys = DomainMatrix.zeros((dim+1, 1), K) + sol = _find_nonzero_solution(r, homosys) + + # if a solution is not obtained then increasing the order by 1 in each + # iteration + while sol.is_zero_matrix: + dim += 1 + + diff1 = (gen * rowsself[-1]) + rowsself.append(diff1) + + diff2 = (gen * rowsother[-1]) + rowsother.append(diff2) + + row = rowsself + rowsother + r = [] + + for expr in row: + p = [] + for i in range(dim + 1): + if i >= len(expr.listofpoly): + p.append(K.zero) + else: + p.append(K.new(expr.listofpoly[i].rep)) + r.append(p) + + # solving the linear system using gauss jordan solver + r = DomainMatrix(r, (len(row), dim+1), K).transpose() + homosys = DomainMatrix.zeros((dim+1, 1), K) + sol = _find_nonzero_solution(r, homosys) + + # taking only the coefficients needed to multiply with `self` + # can be also be done the other way by taking R.H.S and multiplying with + # `other` + sol = sol.flat()[:dim + 1 - deg1] + sol1 = _normalize(sol, self.annihilator.parent) + # annihilator of the solution + sol = sol1 * (self.annihilator) + sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False) + + if not (self._have_init_cond() and other._have_init_cond()): + return HolonomicFunction(sol, self.x) + + # both the functions have ordinary initial conditions + if self.is_singularics() == False and other.is_singularics() == False: + + # directly add the corresponding value + if self.x0 == other.x0: + # try to extended the initial conditions + # using the annihilator + y1 = _extend_y0(self, sol.order) + y2 = _extend_y0(other, sol.order) + y0 = [a + b for a, b in zip(y1, y2)] + return HolonomicFunction(sol, self.x, self.x0, y0) + + else: + # change the initial conditions to a same point + selfat0 = self.annihilator.is_singular(0) + otherat0 = other.annihilator.is_singular(0) + + if self.x0 == 0 and not selfat0 and not otherat0: + return self + other.change_ics(0) + + elif other.x0 == 0 and not selfat0 and not otherat0: + return self.change_ics(0) + other + + else: + selfatx0 = self.annihilator.is_singular(self.x0) + otheratx0 = other.annihilator.is_singular(self.x0) + + if not selfatx0 and not otheratx0: + return self + other.change_ics(self.x0) + + else: + return self.change_ics(other.x0) + other + + if self.x0 != other.x0: + return HolonomicFunction(sol, self.x) + + # if the functions have singular_ics + y1 = None + y2 = None + + if self.is_singularics() == False and other.is_singularics() == True: + # convert the ordinary initial condition to singular. + _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] + y1 = {S.Zero: _y0} + y2 = other.y0 + elif self.is_singularics() == True and other.is_singularics() == False: + _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] + y1 = self.y0 + y2 = {S.Zero: _y0} + elif self.is_singularics() == True and other.is_singularics() == True: + y1 = self.y0 + y2 = other.y0 + + # computing singular initial condition for the result + # taking union of the series terms of both functions + y0 = {} + for i in y1: + # add corresponding initial terms if the power + # on `x` is same + if i in y2: + y0[i] = [a + b for a, b in zip(y1[i], y2[i])] + else: + y0[i] = y1[i] + for i in y2: + if i not in y1: + y0[i] = y2[i] + return HolonomicFunction(sol, self.x, self.x0, y0) + + def integrate(self, limits, initcond=False): + """ + Integrates the given holonomic function. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1 + HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1]) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x)) + HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0]) + """ + + # to get the annihilator, just multiply by Dx from right + D = self.annihilator.parent.derivative_operator + + # if the function have initial conditions of the series format + if self.is_singularics() == True: + + r = self._singularics_to_ord() + if r: + return r.integrate(limits, initcond=initcond) + + # computing singular initial condition for the function + # produced after integration. + y0 = {} + for i in self.y0: + c = self.y0[i] + c2 = [] + for j, cj in enumerate(c): + if cj == 0: + c2.append(S.Zero) + + # if power on `x` is -1, the integration becomes log(x) + # TODO: Implement this case + elif i + j + 1 == 0: + raise NotImplementedError("logarithmic terms in the series are not supported") + else: + c2.append(cj / S(i + j + 1)) + y0[i + 1] = c2 + + if hasattr(limits, "__iter__"): + raise NotImplementedError("Definite integration for singular initial conditions") + + return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) + + # if no initial conditions are available for the function + if not self._have_init_cond(): + if initcond: + return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero]) + return HolonomicFunction(self.annihilator * D, self.x) + + # definite integral + # initial conditions for the answer will be stored at point `a`, + # where `a` is the lower limit of the integrand + if hasattr(limits, "__iter__"): + + if len(limits) == 3 and limits[0] == self.x: + x0 = self.x0 + a = limits[1] + b = limits[2] + definite = True + + else: + definite = False + + y0 = [S.Zero] + y0 += self.y0 + + indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) + + if not definite: + return indefinite_integral + + # use evalf to get the values at `a` + if x0 != a: + try: + indefinite_expr = indefinite_integral.to_expr() + except (NotHyperSeriesError, NotPowerSeriesError): + indefinite_expr = None + + if indefinite_expr: + lower = indefinite_expr.subs(self.x, a) + if isinstance(lower, NaN): + lower = indefinite_expr.limit(self.x, a) + else: + lower = indefinite_integral.evalf(a) + + if b == self.x: + y0[0] = y0[0] - lower + return HolonomicFunction(self.annihilator * D, self.x, x0, y0) + + elif S(b).is_Number: + if indefinite_expr: + upper = indefinite_expr.subs(self.x, b) + if isinstance(upper, NaN): + upper = indefinite_expr.limit(self.x, b) + else: + upper = indefinite_integral.evalf(b) + + return upper - lower + + + # if the upper limit is `x`, the answer will be a function + if b == self.x: + return HolonomicFunction(self.annihilator * D, self.x, a, y0) + + # if the upper limits is a Number, a numerical value will be returned + elif S(b).is_Number: + try: + s = HolonomicFunction(self.annihilator * D, self.x, a,\ + y0).to_expr() + indefinite = s.subs(self.x, b) + if not isinstance(indefinite, NaN): + return indefinite + else: + return s.limit(self.x, b) + except (NotHyperSeriesError, NotPowerSeriesError): + return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b) + + return HolonomicFunction(self.annihilator * D, self.x) + + def diff(self, *args, **kwargs): + r""" + Differentiation of the given Holonomic function. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr() + cos(x) + >>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr() + 2*exp(2*x) + + See Also + ======== + + integrate + """ + kwargs.setdefault('evaluate', True) + if args: + if args[0] != self.x: + return S.Zero + elif len(args) == 2: + sol = self + for i in range(args[1]): + sol = sol.diff(args[0]) + return sol + + ann = self.annihilator + + # if the function is constant. + if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1: + return S.Zero + + # if the coefficient of y in the differential equation is zero. + # a shifting is done to compute the answer in this case. + elif ann.listofpoly[0] == ann.parent.base.zero: + + sol = DifferentialOperator(ann.listofpoly[1:], ann.parent) + + if self._have_init_cond(): + # if ordinary initial condition + if self.is_singularics() == False: + return HolonomicFunction(sol, self.x, self.x0, self.y0[1:]) + # TODO: support for singular initial condition + return HolonomicFunction(sol, self.x) + else: + return HolonomicFunction(sol, self.x) + + # the general algorithm + R = ann.parent.base + K = R.get_field() + + seq_dmf = [K.new(i.rep) for i in ann.listofpoly] + + # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0 + rhs = [i / seq_dmf[0] for i in seq_dmf[1:]] + rhs.insert(0, K.zero) + + # differentiate both lhs and rhs + sol = _derivate_diff_eq(rhs) + + # add the term y' in lhs to rhs + sol = _add_lists(sol, [K.zero, K.one]) + + sol = _normalize(sol[1:], self.annihilator.parent, negative=False) + + if not self._have_init_cond() or self.is_singularics() == True: + return HolonomicFunction(sol, self.x) + + y0 = _extend_y0(self, sol.order + 1)[1:] + return HolonomicFunction(sol, self.x, self.x0, y0) + + def __eq__(self, other): + if self.annihilator == other.annihilator: + if self.x == other.x: + if self._have_init_cond() and other._have_init_cond(): + if self.x0 == other.x0 and self.y0 == other.y0: + return True + else: + return False + else: + return True + else: + return False + else: + return False + + def __mul__(self, other): + ann_self = self.annihilator + + if not isinstance(other, HolonomicFunction): + other = sympify(other) + + if other.has(self.x): + raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.") + + if not self._have_init_cond(): + return self + else: + y0 = _extend_y0(self, ann_self.order) + y1 = [] + + for j in y0: + y1.append((Poly.new(j, self.x) * other).rep) + + return HolonomicFunction(ann_self, self.x, self.x0, y1) + + if self.annihilator.parent.base != other.annihilator.parent.base: + a, b = self.unify(other) + return a * b + + ann_other = other.annihilator + + list_self = [] + list_other = [] + + a = ann_self.order + b = ann_other.order + + R = ann_self.parent.base + K = R.get_field() + + for j in ann_self.listofpoly: + list_self.append(K.new(j.rep)) + + for j in ann_other.listofpoly: + list_other.append(K.new(j.rep)) + + # will be used to reduce the degree + self_red = [-list_self[i] / list_self[a] for i in range(a)] + + other_red = [-list_other[i] / list_other[b] for i in range(b)] + + # coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g) + coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)] + coeff_mul[0][0] = K.one + + # making the ansatz + lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]] + lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose() + + homo_sys = DomainMatrix.zeros((a*b, 1), K) + + sol = _find_nonzero_solution(lin_sys, homo_sys) + + # until a non trivial solution is found + while sol.is_zero_matrix: + + # updating the coefficients Dx^i(f).Dx^j(g) for next degree + for i in range(a - 1, -1, -1): + for j in range(b - 1, -1, -1): + coeff_mul[i][j + 1] += coeff_mul[i][j] + coeff_mul[i + 1][j] += coeff_mul[i][j] + if isinstance(coeff_mul[i][j], K.dtype): + coeff_mul[i][j] = DMFdiff(coeff_mul[i][j]) + else: + coeff_mul[i][j] = coeff_mul[i][j].diff(self.x) + + # reduce the terms to lower power using annihilators of f, g + for i in range(a + 1): + if not coeff_mul[i][b].is_zero: + for j in range(b): + coeff_mul[i][j] += other_red[j] * \ + coeff_mul[i][b] + coeff_mul[i][b] = K.zero + + # not d2 + 1, as that is already covered in previous loop + for j in range(b): + if not coeff_mul[a][j] == 0: + for i in range(a): + coeff_mul[i][j] += self_red[i] * \ + coeff_mul[a][j] + coeff_mul[a][j] = K.zero + + lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)]) + lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose() + + sol = _find_nonzero_solution(lin_sys, homo_sys) + + sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False) + + if not (self._have_init_cond() and other._have_init_cond()): + return HolonomicFunction(sol_ann, self.x) + + if self.is_singularics() == False and other.is_singularics() == False: + + # if both the conditions are at same point + if self.x0 == other.x0: + + # try to find more initial conditions + y0_self = _extend_y0(self, sol_ann.order) + y0_other = _extend_y0(other, sol_ann.order) + # h(x0) = f(x0) * g(x0) + y0 = [y0_self[0] * y0_other[0]] + + # coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg) + for i in range(1, min(len(y0_self), len(y0_other))): + coeff = [[0 for i in range(i + 1)] for j in range(i + 1)] + for j in range(i + 1): + for k in range(i + 1): + if j + k == i: + coeff[j][k] = binomial(i, j) + + sol = 0 + for j in range(i + 1): + for k in range(i + 1): + sol += coeff[j][k]* y0_self[j] * y0_other[k] + + y0.append(sol) + + return HolonomicFunction(sol_ann, self.x, self.x0, y0) + + # if the points are different, consider one + else: + + selfat0 = self.annihilator.is_singular(0) + otherat0 = other.annihilator.is_singular(0) + + if self.x0 == 0 and not selfat0 and not otherat0: + return self * other.change_ics(0) + + elif other.x0 == 0 and not selfat0 and not otherat0: + return self.change_ics(0) * other + + else: + selfatx0 = self.annihilator.is_singular(self.x0) + otheratx0 = other.annihilator.is_singular(self.x0) + + if not selfatx0 and not otheratx0: + return self * other.change_ics(self.x0) + + else: + return self.change_ics(other.x0) * other + + if self.x0 != other.x0: + return HolonomicFunction(sol_ann, self.x) + + # if the functions have singular_ics + y1 = None + y2 = None + + if self.is_singularics() == False and other.is_singularics() == True: + _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] + y1 = {S.Zero: _y0} + y2 = other.y0 + elif self.is_singularics() == True and other.is_singularics() == False: + _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] + y1 = self.y0 + y2 = {S.Zero: _y0} + elif self.is_singularics() == True and other.is_singularics() == True: + y1 = self.y0 + y2 = other.y0 + + y0 = {} + # multiply every possible pair of the series terms + for i in y1: + for j in y2: + k = min(len(y1[i]), len(y2[j])) + c = [] + for a in range(k): + s = S.Zero + for b in range(a + 1): + s += y1[i][b] * y2[j][a - b] + c.append(s) + if not i + j in y0: + y0[i + j] = c + else: + y0[i + j] = [a + b for a, b in zip(c, y0[i + j])] + return HolonomicFunction(sol_ann, self.x, self.x0, y0) + + __rmul__ = __mul__ + + def __sub__(self, other): + return self + other * -1 + + def __rsub__(self, other): + return self * -1 + other + + def __neg__(self): + return -1 * self + + def __truediv__(self, other): + return self * (S.One / other) + + def __pow__(self, n): + if self.annihilator.order <= 1: + ann = self.annihilator + parent = ann.parent + + if self.y0 is None: + y0 = None + else: + y0 = [list(self.y0)[0] ** n] + + p0 = ann.listofpoly[0] + p1 = ann.listofpoly[1] + + p0 = (Poly.new(p0, self.x) * n).rep + + sol = [parent.base.to_sympy(i) for i in [p0, p1]] + dd = DifferentialOperator(sol, parent) + return HolonomicFunction(dd, self.x, self.x0, y0) + if n < 0: + raise NotHolonomicError("Negative Power on a Holonomic Function") + if n == 0: + Dx = self.annihilator.parent.derivative_operator + return HolonomicFunction(Dx, self.x, S.Zero, [S.One]) + if n == 1: + return self + else: + if n % 2 == 1: + powreduce = self**(n - 1) + return powreduce * self + elif n % 2 == 0: + powreduce = self**(n / 2) + return powreduce * powreduce + + def degree(self): + """ + Returns the highest power of `x` in the annihilator. + """ + sol = [i.degree() for i in self.annihilator.listofpoly] + return max(sol) + + def composition(self, expr, *args, **kwargs): + """ + Returns function after composition of a holonomic + function with an algebraic function. The method cannot compute + initial conditions for the result by itself, so they can be also be + provided. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2) + HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1]) + >>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0]) + HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0]) + + See Also + ======== + + from_hyper + """ + + R = self.annihilator.parent + a = self.annihilator.order + diff = expr.diff(self.x) + listofpoly = self.annihilator.listofpoly + + for i, j in enumerate(listofpoly): + if isinstance(j, self.annihilator.parent.base.dtype): + listofpoly[i] = self.annihilator.parent.base.to_sympy(j) + + r = listofpoly[a].subs({self.x:expr}) + subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)] + coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a)) + coeffs[0] = S.One + system = [coeffs] + homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose() + while True: + coeffs_next = [p.diff(self.x) for p in coeffs] + for i in range(a - 1): + coeffs_next[i + 1] += (coeffs[i] * diff) + for i in range(a): + coeffs_next[i] += (coeffs[-1] * subs[i] * diff) + coeffs = coeffs_next + # check for linear relations + system.append(coeffs) + sol, taus = (Matrix(system).transpose() + ).gauss_jordan_solve(homogeneous) + if sol.is_zero_matrix is not True: + break + + tau = list(taus)[0] + sol = sol.subs(tau, 1) + sol = _normalize(sol[0:], R, negative=False) + + # if initial conditions are given for the resulting function + if args: + return HolonomicFunction(sol, self.x, args[0], args[1]) + return HolonomicFunction(sol, self.x) + + def to_sequence(self, lb=True): + r""" + Finds recurrence relation for the coefficients in the series expansion + of the function about :math:`x_0`, where :math:`x_0` is the point at + which the initial condition is stored. + + Explanation + =========== + + If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]` + is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the + smallest ``n`` for which the recurrence holds true. + + If the point :math:`x_0` is regular singular, a list of solutions in + the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`. + Each tuple in this vector represents a recurrence relation :math:`R` + associated with a root of the indicial equation ``p``. Conditions of + a different format can also be provided in this case, see the + docstring of HolonomicFunction class. + + If it's not possible to numerically compute a initial condition, + it is returned as a symbol :math:`C_j`, denoting the coefficient of + :math:`(x - x_0)^j` in the power series about :math:`x_0`. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols, S + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence() + [(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)] + >>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence() + [(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)] + >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence() + [(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)] + + See Also + ======== + + HolonomicFunction.series + + References + ========== + + .. [1] https://hal.inria.fr/inria-00070025/document + .. [2] https://www3.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf + + """ + + if self.x0 != 0: + return self.shift_x(self.x0).to_sequence() + + # check whether a power series exists if the point is singular + if self.annihilator.is_singular(self.x0): + return self._frobenius(lb=lb) + + dict1 = {} + n = Symbol('n', integer=True) + dom = self.annihilator.parent.base.dom + R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') + + # substituting each term of the form `x^k Dx^j` in the + # annihilator, according to the formula below: + # x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo)) + # for explanation see [2]. + for i, j in enumerate(self.annihilator.listofpoly): + + listofdmp = j.all_coeffs() + degree = len(listofdmp) - 1 + + for k in range(degree + 1): + coeff = listofdmp[degree - k] + + if coeff == 0: + continue + + if (i - k, k) in dict1: + dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i)) + else: + dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i)) + + + sol = [] + keylist = [i[0] for i in dict1] + lower = min(keylist) + upper = max(keylist) + degree = self.degree() + + # the recurrence relation holds for all values of + # n greater than smallest_n, i.e. n >= smallest_n + smallest_n = lower + degree + dummys = {} + eqs = [] + unknowns = [] + + # an appropriate shift of the recurrence + for j in range(lower, upper + 1): + if j in keylist: + temp = S.Zero + for k in dict1.keys(): + if k[0] == j: + temp += dict1[k].subs(n, n - lower) + sol.append(temp) + else: + sol.append(S.Zero) + + # the recurrence relation + sol = RecurrenceOperator(sol, R) + + # computing the initial conditions for recurrence + order = sol.order + all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') + all_roots = all_roots.keys() + + if all_roots: + max_root = max(all_roots) + 1 + smallest_n = max(max_root, smallest_n) + order += smallest_n + + y0 = _extend_y0(self, order) + u0 = [] + + # u(n) = y^n(0)/factorial(n) + for i, j in enumerate(y0): + u0.append(j / factorial(i)) + + # if sufficient conditions can't be computed then + # try to use the series method i.e. + # equate the coefficients of x^k in the equation formed by + # substituting the series in differential equation, to zero. + if len(u0) < order: + + for i in range(degree): + eq = S.Zero + + for j in dict1: + + if i + j[0] < 0: + dummys[i + j[0]] = S.Zero + + elif i + j[0] < len(u0): + dummys[i + j[0]] = u0[i + j[0]] + + elif not i + j[0] in dummys: + dummys[i + j[0]] = Symbol('C_%s' %(i + j[0])) + unknowns.append(dummys[i + j[0]]) + + if j[1] <= i: + eq += dict1[j].subs(n, i) * dummys[i + j[0]] + + eqs.append(eq) + + # solve the system of equations formed + soleqs = solve(eqs, *unknowns) + + if isinstance(soleqs, dict): + + for i in range(len(u0), order): + + if i not in dummys: + dummys[i] = Symbol('C_%s' %i) + + if dummys[i] in soleqs: + u0.append(soleqs[dummys[i]]) + + else: + u0.append(dummys[i]) + + if lb: + return [(HolonomicSequence(sol, u0), smallest_n)] + return [HolonomicSequence(sol, u0)] + + for i in range(len(u0), order): + + if i not in dummys: + dummys[i] = Symbol('C_%s' %i) + + s = False + for j in soleqs: + if dummys[i] in j: + u0.append(j[dummys[i]]) + s = True + if not s: + u0.append(dummys[i]) + + if lb: + return [(HolonomicSequence(sol, u0), smallest_n)] + + return [HolonomicSequence(sol, u0)] + + def _frobenius(self, lb=True): + # compute the roots of indicial equation + indicialroots = self._indicial() + + reals = [] + compl = [] + for i in ordered(indicialroots.keys()): + if i.is_real: + reals.extend([i] * indicialroots[i]) + else: + a, b = i.as_real_imag() + compl.extend([(i, a, b)] * indicialroots[i]) + + # sort the roots for a fixed ordering of solution + compl.sort(key=lambda x : x[1]) + compl.sort(key=lambda x : x[2]) + reals.sort() + + # grouping the roots, roots differ by an integer are put in the same group. + grp = [] + + for i in reals: + intdiff = False + if len(grp) == 0: + grp.append([i]) + continue + for j in grp: + if int(j[0] - i) == j[0] - i: + j.append(i) + intdiff = True + break + if not intdiff: + grp.append([i]) + + # True if none of the roots differ by an integer i.e. + # each element in group have only one member + independent = True if all(len(i) == 1 for i in grp) else False + + allpos = all(i >= 0 for i in reals) + allint = all(int(i) == i for i in reals) + + # if initial conditions are provided + # then use them. + if self.is_singularics() == True: + rootstoconsider = [] + for i in ordered(self.y0.keys()): + for j in ordered(indicialroots.keys()): + if equal_valued(j, i): + rootstoconsider.append(i) + + elif allpos and allint: + rootstoconsider = [min(reals)] + + elif independent: + rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl] + + elif not allint: + rootstoconsider = [] + for i in reals: + if not int(i) == i: + rootstoconsider.append(i) + + elif not allpos: + + if not self._have_init_cond() or S(self.y0[0]).is_finite == False: + rootstoconsider = [min(reals)] + + else: + posroots = [] + for i in reals: + if i >= 0: + posroots.append(i) + rootstoconsider = [min(posroots)] + + n = Symbol('n', integer=True) + dom = self.annihilator.parent.base.dom + R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') + + finalsol = [] + char = ord('C') + + for p in rootstoconsider: + dict1 = {} + + for i, j in enumerate(self.annihilator.listofpoly): + + listofdmp = j.all_coeffs() + degree = len(listofdmp) - 1 + + for k in range(degree + 1): + coeff = listofdmp[degree - k] + + if coeff == 0: + continue + + if (i - k, k - i) in dict1: + dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) + else: + dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) + + sol = [] + keylist = [i[0] for i in dict1] + lower = min(keylist) + upper = max(keylist) + degree = max([i[1] for i in dict1]) + degree2 = min([i[1] for i in dict1]) + + smallest_n = lower + degree + dummys = {} + eqs = [] + unknowns = [] + + for j in range(lower, upper + 1): + if j in keylist: + temp = S.Zero + for k in dict1.keys(): + if k[0] == j: + temp += dict1[k].subs(n, n - lower) + sol.append(temp) + else: + sol.append(S.Zero) + + # the recurrence relation + sol = RecurrenceOperator(sol, R) + + # computing the initial conditions for recurrence + order = sol.order + all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') + all_roots = all_roots.keys() + + if all_roots: + max_root = max(all_roots) + 1 + smallest_n = max(max_root, smallest_n) + order += smallest_n + + u0 = [] + + if self.is_singularics() == True: + u0 = self.y0[p] + + elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1: + y0 = _extend_y0(self, order + int(p)) + # u(n) = y^n(0)/factorial(n) + if len(y0) > int(p): + for i in range(int(p), len(y0)): + u0.append(y0[i] / factorial(i)) + + if len(u0) < order: + + for i in range(degree2, degree): + eq = S.Zero + + for j in dict1: + if i + j[0] < 0: + dummys[i + j[0]] = S.Zero + + elif i + j[0] < len(u0): + dummys[i + j[0]] = u0[i + j[0]] + + elif not i + j[0] in dummys: + letter = chr(char) + '_%s' %(i + j[0]) + dummys[i + j[0]] = Symbol(letter) + unknowns.append(dummys[i + j[0]]) + + if j[1] <= i: + eq += dict1[j].subs(n, i) * dummys[i + j[0]] + + eqs.append(eq) + + # solve the system of equations formed + soleqs = solve(eqs, *unknowns) + + if isinstance(soleqs, dict): + + for i in range(len(u0), order): + + if i not in dummys: + letter = chr(char) + '_%s' %i + dummys[i] = Symbol(letter) + + if dummys[i] in soleqs: + u0.append(soleqs[dummys[i]]) + + else: + u0.append(dummys[i]) + + if lb: + finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) + continue + else: + finalsol.append((HolonomicSequence(sol, u0), p)) + continue + + for i in range(len(u0), order): + + if i not in dummys: + letter = chr(char) + '_%s' %i + dummys[i] = Symbol(letter) + + s = False + for j in soleqs: + if dummys[i] in j: + u0.append(j[dummys[i]]) + s = True + if not s: + u0.append(dummys[i]) + if lb: + finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) + + else: + finalsol.append((HolonomicSequence(sol, u0), p)) + char += 1 + return finalsol + + def series(self, n=6, coefficient=False, order=True, _recur=None): + r""" + Finds the power series expansion of given holonomic function about :math:`x_0`. + + Explanation + =========== + + A list of series might be returned if :math:`x_0` is a regular point with + multiple roots of the indicial equation. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x + 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x) + x - x**3/6 + x**5/120 - x**7/5040 + O(x**8) + + See Also + ======== + + HolonomicFunction.to_sequence + """ + + if _recur is None: + recurrence = self.to_sequence() + else: + recurrence = _recur + + if isinstance(recurrence, tuple) and len(recurrence) == 2: + recurrence = recurrence[0] + constantpower = 0 + elif isinstance(recurrence, tuple) and len(recurrence) == 3: + constantpower = recurrence[1] + recurrence = recurrence[0] + + elif len(recurrence) == 1 and len(recurrence[0]) == 2: + recurrence = recurrence[0][0] + constantpower = 0 + elif len(recurrence) == 1 and len(recurrence[0]) == 3: + constantpower = recurrence[0][1] + recurrence = recurrence[0][0] + else: + sol = [] + for i in recurrence: + sol.append(self.series(_recur=i)) + return sol + + n = n - int(constantpower) + l = len(recurrence.u0) - 1 + k = recurrence.recurrence.order + x = self.x + x0 = self.x0 + seq_dmp = recurrence.recurrence.listofpoly + R = recurrence.recurrence.parent.base + K = R.get_field() + seq = [] + + for i, j in enumerate(seq_dmp): + seq.append(K.new(j.rep)) + + sub = [-seq[i] / seq[k] for i in range(k)] + sol = list(recurrence.u0) + + if l + 1 >= n: + pass + else: + # use the initial conditions to find the next term + for i in range(l + 1 - k, n - k): + coeff = S.Zero + for j in range(k): + if i + j >= 0: + coeff += DMFsubs(sub[j], i) * sol[i + j] + sol.append(coeff) + + if coefficient: + return sol + + ser = S.Zero + for i, j in enumerate(sol): + ser += x**(i + constantpower) * j + if order: + ser += Order(x**(n + int(constantpower)), x) + if x0 != 0: + return ser.subs(x, x - x0) + return ser + + def _indicial(self): + """ + Computes roots of the Indicial equation. + """ + + if self.x0 != 0: + return self.shift_x(self.x0)._indicial() + + list_coeff = self.annihilator.listofpoly + R = self.annihilator.parent.base + x = self.x + s = R.zero + y = R.one + + def _pole_degree(poly): + root_all = roots(R.to_sympy(poly), x, filter='Z') + if 0 in root_all.keys(): + return root_all[0] + else: + return 0 + + degree = [j.degree() for j in list_coeff] + degree = max(degree) + inf = 10 * (max(1, degree) + max(1, self.annihilator.order)) + + deg = lambda q: inf if q.is_zero else _pole_degree(q) + b = deg(list_coeff[0]) + + for j in range(1, len(list_coeff)): + b = min(b, deg(list_coeff[j]) - j) + + for i, j in enumerate(list_coeff): + listofdmp = j.all_coeffs() + degree = len(listofdmp) - 1 + if - i - b <= 0 and degree - i - b >= 0: + s = s + listofdmp[degree - i - b] * y + y *= x - i + + return roots(R.to_sympy(s), x) + + def evalf(self, points, method='RK4', h=0.05, derivatives=False): + r""" + Finds numerical value of a holonomic function using numerical methods. + (RK4 by default). A set of points (real or complex) must be provided + which will be the path for the numerical integration. + + Explanation + =========== + + The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical + values will be computed at each point in this order + :math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`. + + Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + + A straight line on the real axis from (0 to 1) + + >>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] + + Runge-Kutta 4th order on e^x from 0.1 to 1. + Exact solution at 1 is 2.71828182845905 + + >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r) + [1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069, + 1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232, + 2.45960141378007, 2.71827974413517] + + Euler's method for the same + + >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler') + [1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881, + 2.357947691, 2.5937424601] + + One can also observe that the value obtained using Runge-Kutta 4th order + is much more accurate than Euler's method. + """ + + from sympy.holonomic.numerical import _evalf + lp = False + + # if a point `b` is given instead of a mesh + if not hasattr(points, "__iter__"): + lp = True + b = S(points) + if self.x0 == b: + return _evalf(self, [b], method=method, derivatives=derivatives)[-1] + + if not b.is_Number: + raise NotImplementedError + + a = self.x0 + if a > b: + h = -h + n = int((b - a) / h) + points = [a + h] + for i in range(n - 1): + points.append(points[-1] + h) + + for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x): + if i == self.x0 or i in points: + raise SingularityError(self, i) + + if lp: + return _evalf(self, points, method=method, derivatives=derivatives)[-1] + return _evalf(self, points, method=method, derivatives=derivatives) + + def change_x(self, z): + """ + Changes only the variable of Holonomic Function, for internal + purposes. For composition use HolonomicFunction.composition() + """ + + dom = self.annihilator.parent.base.dom + R = dom.old_poly_ring(z) + parent, _ = DifferentialOperators(R, 'Dx') + sol = [] + for j in self.annihilator.listofpoly: + sol.append(R(j.rep)) + sol = DifferentialOperator(sol, parent) + return HolonomicFunction(sol, z, self.x0, self.y0) + + def shift_x(self, a): + """ + Substitute `x + a` for `x`. + """ + + x = self.x + listaftershift = self.annihilator.listofpoly + base = self.annihilator.parent.base + + sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift] + sol = DifferentialOperator(sol, self.annihilator.parent) + x0 = self.x0 - a + if not self._have_init_cond(): + return HolonomicFunction(sol, x) + return HolonomicFunction(sol, x, x0, self.y0) + + def to_hyper(self, as_list=False, _recur=None): + r""" + Returns a hypergeometric function (or linear combination of them) + representing the given holonomic function. + + Explanation + =========== + + Returns an answer of the form: + `a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots` + + This is very useful as one can now use ``hyperexpand`` to find the + symbolic expressions/functions. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + >>> # sin(x) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper() + x*hyper((), (3/2,), -x**2/4) + >>> # exp(x) + >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper() + hyper((), (), x) + + See Also + ======== + + from_hyper, from_meijerg + """ + + if _recur is None: + recurrence = self.to_sequence() + else: + recurrence = _recur + + if isinstance(recurrence, tuple) and len(recurrence) == 2: + smallest_n = recurrence[1] + recurrence = recurrence[0] + constantpower = 0 + elif isinstance(recurrence, tuple) and len(recurrence) == 3: + smallest_n = recurrence[2] + constantpower = recurrence[1] + recurrence = recurrence[0] + elif len(recurrence) == 1 and len(recurrence[0]) == 2: + smallest_n = recurrence[0][1] + recurrence = recurrence[0][0] + constantpower = 0 + elif len(recurrence) == 1 and len(recurrence[0]) == 3: + smallest_n = recurrence[0][2] + constantpower = recurrence[0][1] + recurrence = recurrence[0][0] + else: + sol = self.to_hyper(as_list=as_list, _recur=recurrence[0]) + for i in recurrence[1:]: + sol += self.to_hyper(as_list=as_list, _recur=i) + return sol + + u0 = recurrence.u0 + r = recurrence.recurrence + x = self.x + x0 = self.x0 + + # order of the recurrence relation + m = r.order + + # when no recurrence exists, and the power series have finite terms + if m == 0: + nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R') + + sol = S.Zero + for j, i in enumerate(nonzeroterms): + + if i < 0 or int(i) != i: + continue + + i = int(i) + if i < len(u0): + if isinstance(u0[i], (PolyElement, FracElement)): + u0[i] = u0[i].as_expr() + sol += u0[i] * x**i + + else: + sol += Symbol('C_%s' %j) * x**i + + if isinstance(sol, (PolyElement, FracElement)): + sol = sol.as_expr() * x**constantpower + else: + sol = sol * x**constantpower + if as_list: + if x0 != 0: + return [(sol.subs(x, x - x0), )] + return [(sol, )] + if x0 != 0: + return sol.subs(x, x - x0) + return sol + + if smallest_n + m > len(u0): + raise NotImplementedError("Can't compute sufficient Initial Conditions") + + # check if the recurrence represents a hypergeometric series + is_hyper = True + + for i in range(1, len(r.listofpoly)-1): + if r.listofpoly[i] != r.parent.base.zero: + is_hyper = False + break + + if not is_hyper: + raise NotHyperSeriesError(self, self.x0) + + a = r.listofpoly[0] + b = r.listofpoly[-1] + + # the constant multiple of argument of hypergeometric function + if isinstance(a.rep[0], (PolyElement, FracElement)): + c = - (S(a.rep[0].as_expr()) * m**(a.degree())) / (S(b.rep[0].as_expr()) * m**(b.degree())) + else: + c = - (S(a.rep[0]) * m**(a.degree())) / (S(b.rep[0]) * m**(b.degree())) + + sol = 0 + + arg1 = roots(r.parent.base.to_sympy(a), recurrence.n) + arg2 = roots(r.parent.base.to_sympy(b), recurrence.n) + + # iterate through the initial conditions to find + # the hypergeometric representation of the given + # function. + # The answer will be a linear combination + # of different hypergeometric series which satisfies + # the recurrence. + if as_list: + listofsol = [] + for i in range(smallest_n + m): + + # if the recurrence relation doesn't hold for `n = i`, + # then a Hypergeometric representation doesn't exist. + # add the algebraic term a * x**i to the solution, + # where a is u0[i] + if i < smallest_n: + if as_list: + listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), )) + else: + sol += S(u0[i]) * x**i + continue + + # if the coefficient u0[i] is zero, then the + # independent hypergeomtric series starting with + # x**i is not a part of the answer. + if S(u0[i]) == 0: + continue + + ap = [] + bq = [] + + # substitute m * n + i for n + for k in ordered(arg1.keys()): + ap.extend([nsimplify((i - k) / m)] * arg1[k]) + + for k in ordered(arg2.keys()): + bq.extend([nsimplify((i - k) / m)] * arg2[k]) + + # convention of (k + 1) in the denominator + if 1 in bq: + bq.remove(1) + else: + ap.append(1) + if as_list: + listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0))) + else: + sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i + if as_list: + return listofsol + sol = sol * x**constantpower + if x0 != 0: + return sol.subs(x, x - x0) + + return sol + + def to_expr(self): + """ + Converts a Holonomic Function back to elementary functions. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols, S + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr() + besselj(1, x) + >>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr() + x*log(x + 1) + log(x + 1) + 1 + + """ + + return hyperexpand(self.to_hyper()).simplify() + + def change_ics(self, b, lenics=None): + """ + Changes the point `x0` to ``b`` for initial conditions. + + Examples + ======== + + >>> from sympy.holonomic import expr_to_holonomic + >>> from sympy import symbols, sin, exp + >>> x = symbols('x') + + >>> expr_to_holonomic(sin(x)).change_ics(1) + HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)]) + + >>> expr_to_holonomic(exp(x)).change_ics(2) + HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)]) + """ + + symbolic = True + + if lenics is None and len(self.y0) > self.annihilator.order: + lenics = len(self.y0) + dom = self.annihilator.parent.base.domain + + try: + sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom) + except (NotPowerSeriesError, NotHyperSeriesError): + symbolic = False + + if symbolic and sol.x0 == b: + return sol + + y0 = self.evalf(b, derivatives=True) + return HolonomicFunction(self.annihilator, self.x, b, y0) + + def to_meijerg(self): + """ + Returns a linear combination of Meijer G-functions. + + Examples + ======== + + >>> from sympy.holonomic import expr_to_holonomic + >>> from sympy import sin, cos, hyperexpand, log, symbols + >>> x = symbols('x') + >>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg()) + sin(x) + cos(x) + >>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() + log(x) + + See Also + ======== + + to_hyper + """ + + # convert to hypergeometric first + rep = self.to_hyper(as_list=True) + sol = S.Zero + + for i in rep: + if len(i) == 1: + sol += i[0] + + elif len(i) == 2: + sol += i[0] * _hyper_to_meijerg(i[1]) + + return sol + + +def from_hyper(func, x0=0, evalf=False): + r""" + Converts a hypergeometric function to holonomic. + ``func`` is the Hypergeometric Function and ``x0`` is the point at + which initial conditions are required. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import from_hyper + >>> from sympy import symbols, hyper, S + >>> x = symbols('x') + >>> from_hyper(hyper([], [S(3)/2], x**2/4)) + HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)]) + """ + + a = func.ap + b = func.bq + z = func.args[2] + x = z.atoms(Symbol).pop() + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + + # generalized hypergeometric differential equation + xDx = x*Dx + r1 = 1 + for ai in a: # XXX gives sympify error if Mul is used with list of all factors + r1 *= xDx + ai + xDx_1 = xDx - 1 + # r2 = Mul(*([Dx] + [xDx_1 + bi for bi in b])) # XXX gives sympify error + r2 = Dx + for bi in b: + r2 *= xDx_1 + bi + sol = r1 - r2 + + simp = hyperexpand(func) + + if simp in (Infinity, NegativeInfinity): + return HolonomicFunction(sol, x).composition(z) + + def _find_conditions(simp, x, x0, order, evalf=False): + y0 = [] + for i in range(order): + if evalf: + val = simp.subs(x, x0).evalf() + else: + val = simp.subs(x, x0) + # return None if it is Infinite or NaN + if val.is_finite is False or isinstance(val, NaN): + return None + y0.append(val) + simp = simp.diff(x) + return y0 + + # if the function is known symbolically + if not isinstance(simp, hyper): + y0 = _find_conditions(simp, x, x0, sol.order) + while not y0: + # if values don't exist at 0, then try to find initial + # conditions at 1. If it doesn't exist at 1 too then + # try 2 and so on. + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order) + + return HolonomicFunction(sol, x).composition(z, x0, y0) + + if isinstance(simp, hyper): + x0 = 1 + # use evalf if the function can't be simplified + y0 = _find_conditions(simp, x, x0, sol.order, evalf) + while not y0: + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order, evalf) + return HolonomicFunction(sol, x).composition(z, x0, y0) + + return HolonomicFunction(sol, x).composition(z) + + +def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ): + """ + Converts a Meijer G-function to Holonomic. + ``func`` is the G-Function and ``x0`` is the point at + which initial conditions are required. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import from_meijerg + >>> from sympy import symbols, meijerg, S + >>> x = symbols('x') + >>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4)) + HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)]) + """ + + a = func.ap + b = func.bq + n = len(func.an) + m = len(func.bm) + p = len(a) + z = func.args[2] + x = z.atoms(Symbol).pop() + R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx') + + # compute the differential equation satisfied by the + # Meijer G-function. + xDx = x*Dx + xDx1 = xDx + 1 + r1 = x*(-1)**(m + n - p) + for ai in a: # XXX gives sympify error if args given in list + r1 *= xDx1 - ai + # r2 = Mul(*[xDx - bi for bi in b]) # gives sympify error + r2 = 1 + for bi in b: + r2 *= xDx - bi + sol = r1 - r2 + + if not initcond: + return HolonomicFunction(sol, x).composition(z) + + simp = hyperexpand(func) + + if simp in (Infinity, NegativeInfinity): + return HolonomicFunction(sol, x).composition(z) + + def _find_conditions(simp, x, x0, order, evalf=False): + y0 = [] + for i in range(order): + if evalf: + val = simp.subs(x, x0).evalf() + else: + val = simp.subs(x, x0) + if val.is_finite is False or isinstance(val, NaN): + return None + y0.append(val) + simp = simp.diff(x) + return y0 + + # computing initial conditions + if not isinstance(simp, meijerg): + y0 = _find_conditions(simp, x, x0, sol.order) + while not y0: + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order) + + return HolonomicFunction(sol, x).composition(z, x0, y0) + + if isinstance(simp, meijerg): + x0 = 1 + y0 = _find_conditions(simp, x, x0, sol.order, evalf) + while not y0: + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order, evalf) + + return HolonomicFunction(sol, x).composition(z, x0, y0) + + return HolonomicFunction(sol, x).composition(z) + + +x_1 = Dummy('x_1') +_lookup_table = None +domain_for_table = None +from sympy.integrals.meijerint import _mytype + + +def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True): + """ + Converts a function or an expression to a holonomic function. + + Parameters + ========== + + func: + The expression to be converted. + x: + variable for the function. + x0: + point at which initial condition must be computed. + y0: + One can optionally provide initial condition if the method + is not able to do it automatically. + lenics: + Number of terms in the initial condition. By default it is + equal to the order of the annihilator. + domain: + Ground domain for the polynomials in ``x`` appearing as coefficients + in the annihilator. + initcond: + Set it false if you do not want the initial conditions to be computed. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import expr_to_holonomic + >>> from sympy import sin, exp, symbols + >>> x = symbols('x') + >>> expr_to_holonomic(sin(x)) + HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1]) + >>> expr_to_holonomic(exp(x)) + HolonomicFunction((-1) + (1)*Dx, x, 0, [1]) + + See Also + ======== + + sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table + """ + func = sympify(func) + syms = func.free_symbols + + if not x: + if len(syms) == 1: + x= syms.pop() + else: + raise ValueError("Specify the variable for the function") + elif x in syms: + syms.remove(x) + + extra_syms = list(syms) + + if domain is None: + if func.has(Float): + domain = RR + else: + domain = QQ + if len(extra_syms) != 0: + domain = domain[extra_syms].get_field() + + # try to convert if the function is polynomial or rational + solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond) + if solpoly: + return solpoly + + # create the lookup table + global _lookup_table, domain_for_table + if not _lookup_table: + domain_for_table = domain + _lookup_table = {} + _create_table(_lookup_table, domain=domain) + elif domain != domain_for_table: + domain_for_table = domain + _lookup_table = {} + _create_table(_lookup_table, domain=domain) + + # use the table directly to convert to Holonomic + if func.is_Function: + f = func.subs(x, x_1) + t = _mytype(f, x_1) + if t in _lookup_table: + l = _lookup_table[t] + sol = l[0][1].change_x(x) + else: + sol = _convert_meijerint(func, x, initcond=False, domain=domain) + if not sol: + raise NotImplementedError + if y0: + sol.y0 = y0 + if y0 or not initcond: + sol.x0 = x0 + return sol + if not lenics: + lenics = sol.annihilator.order + _y0 = _find_conditions(func, x, x0, lenics) + while not _y0: + x0 += 1 + _y0 = _find_conditions(func, x, x0, lenics) + return HolonomicFunction(sol.annihilator, x, x0, _y0) + + if y0 or not initcond: + sol = sol.composition(func.args[0]) + if y0: + sol.y0 = y0 + sol.x0 = x0 + return sol + if not lenics: + lenics = sol.annihilator.order + + _y0 = _find_conditions(func, x, x0, lenics) + while not _y0: + x0 += 1 + _y0 = _find_conditions(func, x, x0, lenics) + return sol.composition(func.args[0], x0, _y0) + + # iterate through the expression recursively + args = func.args + f = func.func + sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain) + + if f is Add: + for i in range(1, len(args)): + sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) + + elif f is Mul: + for i in range(1, len(args)): + sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) + + elif f is Pow: + sol = sol**args[1] + sol.x0 = x0 + if not sol: + raise NotImplementedError + if y0: + sol.y0 = y0 + if y0 or not initcond: + return sol + if sol.y0: + return sol + if not lenics: + lenics = sol.annihilator.order + if sol.annihilator.is_singular(x0): + r = sol._indicial() + l = list(r) + if len(r) == 1 and r[l[0]] == S.One: + r = l[0] + g = func / (x - x0)**r + singular_ics = _find_conditions(g, x, x0, lenics) + singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] + y0 = {r:singular_ics} + return HolonomicFunction(sol.annihilator, x, x0, y0) + + _y0 = _find_conditions(func, x, x0, lenics) + while not _y0: + x0 += 1 + _y0 = _find_conditions(func, x, x0, lenics) + + return HolonomicFunction(sol.annihilator, x, x0, _y0) + + +## Some helper functions ## + +def _normalize(list_of, parent, negative=True): + """ + Normalize a given annihilator + """ + + num = [] + denom = [] + base = parent.base + K = base.get_field() + lcm_denom = base.from_sympy(S.One) + list_of_coeff = [] + + # convert polynomials to the elements of associated + # fraction field + for i, j in enumerate(list_of): + if isinstance(j, base.dtype): + list_of_coeff.append(K.new(j.rep)) + elif not isinstance(j, K.dtype): + list_of_coeff.append(K.from_sympy(sympify(j))) + else: + list_of_coeff.append(j) + + # corresponding numerators of the sequence of polynomials + num.append(list_of_coeff[i].numer()) + + # corresponding denominators + denom.append(list_of_coeff[i].denom()) + + # lcm of denominators in the coefficients + for i in denom: + lcm_denom = i.lcm(lcm_denom) + + if negative: + lcm_denom = -lcm_denom + + lcm_denom = K.new(lcm_denom.rep) + + # multiply the coefficients with lcm + for i, j in enumerate(list_of_coeff): + list_of_coeff[i] = j * lcm_denom + + gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep) + + # gcd of numerators in the coefficients + for i in num: + gcd_numer = i.gcd(gcd_numer) + + gcd_numer = K.new(gcd_numer.rep) + + # divide all the coefficients by the gcd + for i, j in enumerate(list_of_coeff): + frac_ans = j / gcd_numer + list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep) + + return DifferentialOperator(list_of_coeff, parent) + + +def _derivate_diff_eq(listofpoly): + """ + Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0 + where a0, a1,... are polynomials or rational functions. The function + returns b0, b1, b2... such that the differential equation + b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the + former equation. + """ + + sol = [] + a = len(listofpoly) - 1 + sol.append(DMFdiff(listofpoly[0])) + + for i, j in enumerate(listofpoly[1:]): + sol.append(DMFdiff(j) + listofpoly[i]) + + sol.append(listofpoly[a]) + return sol + + +def _hyper_to_meijerg(func): + """ + Converts a `hyper` to meijerg. + """ + ap = func.ap + bq = func.bq + + ispoly = any(i <= 0 and int(i) == i for i in ap) + if ispoly: + return hyperexpand(func) + + z = func.args[2] + + # parameters of the `meijerg` function. + an = (1 - i for i in ap) + anp = () + bm = (S.Zero, ) + bmq = (1 - i for i in bq) + + k = S.One + + for i in bq: + k = k * gamma(i) + + for i in ap: + k = k / gamma(i) + + return k * meijerg(an, anp, bm, bmq, -z) + + +def _add_lists(list1, list2): + """Takes polynomial sequences of two annihilators a and b and returns + the list of polynomials of sum of a and b. + """ + if len(list1) <= len(list2): + sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):] + else: + sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):] + return sol + + +def _extend_y0(Holonomic, n): + """ + Tries to find more initial conditions by substituting the initial + value point in the differential equation. + """ + + if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True: + return Holonomic.y0 + + annihilator = Holonomic.annihilator + a = annihilator.order + + listofpoly = [] + + y0 = Holonomic.y0 + R = annihilator.parent.base + K = R.get_field() + + for i, j in enumerate(annihilator.listofpoly): + if isinstance(j, annihilator.parent.base.dtype): + listofpoly.append(K.new(j.rep)) + + if len(y0) < a or n <= len(y0): + return y0 + else: + list_red = [-listofpoly[i] / listofpoly[a] + for i in range(a)] + if len(y0) > a: + y1 = [y0[i] for i in range(a)] + else: + y1 = list(y0) + for i in range(n - a): + sol = 0 + for a, b in zip(y1, list_red): + r = DMFsubs(b, Holonomic.x0) + if not getattr(r, 'is_finite', True): + return y0 + if isinstance(r, (PolyElement, FracElement)): + r = r.as_expr() + sol += a * r + y1.append(sol) + list_red = _derivate_diff_eq(list_red) + + return y0 + y1[len(y0):] + + +def DMFdiff(frac): + # differentiate a DMF object represented as p/q + if not isinstance(frac, DMF): + return frac.diff() + + K = frac.ring + p = K.numer(frac) + q = K.denom(frac) + sol_num = - p * q.diff() + q * p.diff() + sol_denom = q**2 + return K((sol_num.rep, sol_denom.rep)) + + +def DMFsubs(frac, x0, mpm=False): + # substitute the point x0 in DMF object of the form p/q + if not isinstance(frac, DMF): + return frac + + p = frac.num + q = frac.den + sol_p = S.Zero + sol_q = S.Zero + + if mpm: + from mpmath import mp + + for i, j in enumerate(reversed(p)): + if mpm: + j = sympify(j)._to_mpmath(mp.prec) + sol_p += j * x0**i + + for i, j in enumerate(reversed(q)): + if mpm: + j = sympify(j)._to_mpmath(mp.prec) + sol_q += j * x0**i + + if isinstance(sol_p, (PolyElement, FracElement)): + sol_p = sol_p.as_expr() + if isinstance(sol_q, (PolyElement, FracElement)): + sol_q = sol_q.as_expr() + + return sol_p / sol_q + + +def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True): + """ + Converts polynomials, rationals and algebraic functions to holonomic. + """ + + ispoly = func.is_polynomial() + if not ispoly: + israt = func.is_rational_function() + else: + israt = True + + if not (ispoly or israt): + basepoly, ratexp = func.as_base_exp() + if basepoly.is_polynomial() and ratexp.is_Number: + if isinstance(ratexp, Float): + ratexp = nsimplify(ratexp) + m, n = ratexp.p, ratexp.q + is_alg = True + else: + is_alg = False + else: + is_alg = True + + if not (ispoly or israt or is_alg): + return None + + R = domain.old_poly_ring(x) + _, Dx = DifferentialOperators(R, 'Dx') + + # if the function is constant + if not func.has(x): + return HolonomicFunction(Dx, x, 0, [func]) + + if ispoly: + # differential equation satisfied by polynomial + sol = func * Dx - func.diff(x) + sol = _normalize(sol.listofpoly, sol.parent, negative=False) + is_singular = sol.is_singular(x0) + + # try to compute the conditions for singular points + if y0 is None and x0 == 0 and is_singular: + rep = R.from_sympy(func).rep + for i, j in enumerate(reversed(rep)): + if j == 0: + continue + else: + coeff = list(reversed(rep))[i:] + indicial = i + break + for i, j in enumerate(coeff): + if isinstance(j, (PolyElement, FracElement)): + coeff[i] = j.as_expr() + y0 = {indicial: S(coeff)} + + elif israt: + p, q = func.as_numer_denom() + # differential equation satisfied by rational + sol = p * q * Dx + p * q.diff(x) - q * p.diff(x) + sol = _normalize(sol.listofpoly, sol.parent, negative=False) + + elif is_alg: + sol = n * (x / m) * Dx - 1 + sol = HolonomicFunction(sol, x).composition(basepoly).annihilator + is_singular = sol.is_singular(x0) + + # try to compute the conditions for singular points + if y0 is None and x0 == 0 and is_singular and \ + (lenics is None or lenics <= 1): + rep = R.from_sympy(basepoly).rep + for i, j in enumerate(reversed(rep)): + if j == 0: + continue + if isinstance(j, (PolyElement, FracElement)): + j = j.as_expr() + + coeff = S(j)**ratexp + indicial = S(i) * ratexp + break + if isinstance(coeff, (PolyElement, FracElement)): + coeff = coeff.as_expr() + y0 = {indicial: S([coeff])} + + if y0 or not initcond: + return HolonomicFunction(sol, x, x0, y0) + + if not lenics: + lenics = sol.order + + if sol.is_singular(x0): + r = HolonomicFunction(sol, x, x0)._indicial() + l = list(r) + if len(r) == 1 and r[l[0]] == S.One: + r = l[0] + g = func / (x - x0)**r + singular_ics = _find_conditions(g, x, x0, lenics) + singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] + y0 = {r:singular_ics} + return HolonomicFunction(sol, x, x0, y0) + + y0 = _find_conditions(func, x, x0, lenics) + while not y0: + x0 += 1 + y0 = _find_conditions(func, x, x0, lenics) + + return HolonomicFunction(sol, x, x0, y0) + + +def _convert_meijerint(func, x, initcond=True, domain=QQ): + args = meijerint._rewrite1(func, x) + + if args: + fac, po, g, _ = args + else: + return None + + # lists for sum of meijerg functions + fac_list = [fac * i[0] for i in g] + t = po.as_base_exp() + s = t[1] if t[0] == x else S.Zero + po_list = [s + i[1] for i in g] + G_list = [i[2] for i in g] + + # finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z) + def _shift(func, s): + z = func.args[-1] + if z.has(I): + z = z.subs(exp_polar, exp) + + d = z.collect(x, evaluate=False) + b = list(d)[0] + a = d[b] + + t = b.as_base_exp() + b = t[1] if t[0] == x else S.Zero + r = s / b + an = (i + r for i in func.args[0][0]) + ap = (i + r for i in func.args[0][1]) + bm = (i + r for i in func.args[1][0]) + bq = (i + r for i in func.args[1][1]) + + return a**-r, meijerg((an, ap), (bm, bq), z) + + coeff, m = _shift(G_list[0], po_list[0]) + sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain) + + # add all the meijerg functions after converting to holonomic + for i in range(1, len(G_list)): + coeff, m = _shift(G_list[i], po_list[i]) + sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain) + + return sol + + +def _create_table(table, domain=QQ): + """ + Creates the look-up table. For a similar implementation + see meijerint._create_lookup_table. + """ + + def add(formula, annihilator, arg, x0=0, y0=()): + """ + Adds a formula in the dictionary + """ + table.setdefault(_mytype(formula, x_1), []).append((formula, + HolonomicFunction(annihilator, arg, x0, y0))) + + R = domain.old_poly_ring(x_1) + _, Dx = DifferentialOperators(R, 'Dx') + + # add some basic functions + add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1]) + add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0]) + add(exp(x_1), Dx - 1, x_1, 0, 1) + add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1]) + + add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) + add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)]) + add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) + + add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1]) + add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0]) + + add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1) + + add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) + add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) + + add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) + + +def _find_conditions(func, x, x0, order): + y0 = [] + for i in range(order): + val = func.subs(x, x0) + if isinstance(val, NaN): + val = limit(func, x, x0) + if val.is_finite is False or isinstance(val, NaN): + return None + y0.append(val) + func = func.diff(x) + return y0 diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py b/venv/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py new file mode 100644 index 0000000000000000000000000000000000000000..459a94eb25b186e30b9577d972ebc62a36801f6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py @@ -0,0 +1,49 @@ +""" Common Exceptions for `holonomic` module. """ + +class BaseHolonomicError(Exception): + + def new(self, *args): + raise NotImplementedError("abstract base class") + +class NotPowerSeriesError(BaseHolonomicError): + + def __init__(self, holonomic, x0): + self.holonomic = holonomic + self.x0 = x0 + + def __str__(self): + s = 'A Power Series does not exists for ' + s += str(self.holonomic) + s += ' about %s.' %self.x0 + return s + +class NotHolonomicError(BaseHolonomicError): + + def __init__(self, m): + self.m = m + + def __str__(self): + return self.m + +class SingularityError(BaseHolonomicError): + + def __init__(self, holonomic, x0): + self.holonomic = holonomic + self.x0 = x0 + + def __str__(self): + s = str(self.holonomic) + s += ' has a singularity at %s.' %self.x0 + return s + +class NotHyperSeriesError(BaseHolonomicError): + + def __init__(self, holonomic, x0): + self.holonomic = holonomic + self.x0 = x0 + + def __str__(self): + s = 'Power series expansion of ' + s += str(self.holonomic) + s += ' about %s is not hypergeometric' %self.x0 + return s diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/numerical.py b/venv/lib/python3.10/site-packages/sympy/holonomic/numerical.py new file mode 100644 index 0000000000000000000000000000000000000000..ed78f6ee78676cd429cb9ad11a28e9046745e5d3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/numerical.py @@ -0,0 +1,109 @@ +"""Numerical Methods for Holonomic Functions""" + +from sympy.core.sympify import sympify +from sympy.holonomic.holonomic import DMFsubs + +from mpmath import mp + + +def _evalf(func, points, derivatives=False, method='RK4'): + """ + Numerical methods for numerical integration along a given set of + points in the complex plane. + """ + + ann = func.annihilator + a = ann.order + R = ann.parent.base + K = R.get_field() + + if method == 'Euler': + meth = _euler + else: + meth = _rk4 + + dmf = [] + for j in ann.listofpoly: + dmf.append(K.new(j.rep)) + + red = [-dmf[i] / dmf[a] for i in range(a)] + + y0 = func.y0 + if len(y0) < a: + raise TypeError("Not Enough Initial Conditions") + x0 = func.x0 + sol = [meth(red, x0, points[0], y0, a)] + + for i, j in enumerate(points[1:]): + sol.append(meth(red, points[i], j, sol[-1], a)) + + if not derivatives: + return [sympify(i[0]) for i in sol] + else: + return sympify(sol) + + +def _euler(red, x0, x1, y0, a): + """ + Euler's method for numerical integration. + From x0 to x1 with initial values given at x0 as vector y0. + """ + + A = sympify(x0)._to_mpmath(mp.prec) + B = sympify(x1)._to_mpmath(mp.prec) + y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0] + h = B - A + f_0 = y_0[1:] + f_0_n = 0 + + for i in range(a): + f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i] + f_0.append(f_0_n) + + sol = [] + for i in range(a): + sol.append(y_0[i] + h * f_0[i]) + + return sol + + +def _rk4(red, x0, x1, y0, a): + """ + Runge-Kutta 4th order numerical method. + """ + + A = sympify(x0)._to_mpmath(mp.prec) + B = sympify(x1)._to_mpmath(mp.prec) + y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0] + h = B - A + + f_0_n = 0 + f_1_n = 0 + f_2_n = 0 + f_3_n = 0 + + f_0 = y_0[1:] + for i in range(a): + f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i] + f_0.append(f_0_n) + + f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)] + for i in range(a): + f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2) + f_1.append(f_1_n) + + f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)] + for i in range(a): + f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2) + f_2.append(f_2_n) + + f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)] + for i in range(a): + f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h) + f_3.append(f_3_n) + + sol = [] + for i in range(a): + sol.append(y_0[i] + h * (f_0[i]+2*f_1[i]+2*f_2[i]+f_3[i])/6) + + return sol diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/recurrence.py b/venv/lib/python3.10/site-packages/sympy/holonomic/recurrence.py new file mode 100644 index 0000000000000000000000000000000000000000..4c77ae64453ed6b8b336949515b6f2f6197ca251 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/recurrence.py @@ -0,0 +1,365 @@ +"""Recurrence Operators""" + +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.printing import sstr +from sympy.core.sympify import sympify + + +def RecurrenceOperators(base, generator): + """ + Returns an Algebra of Recurrence Operators and the operator for + shifting i.e. the `Sn` operator. + The first argument needs to be the base polynomial ring for the algebra + and the second argument must be a generator which can be either a + noncommutative Symbol or a string. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy import symbols + >>> from sympy.holonomic.recurrence import RecurrenceOperators + >>> n = symbols('n', integer=True) + >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn') + """ + + ring = RecurrenceOperatorAlgebra(base, generator) + return (ring, ring.shift_operator) + + +class RecurrenceOperatorAlgebra: + """ + A Recurrence Operator Algebra is a set of noncommutative polynomials + in intermediate `Sn` and coefficients in a base ring A. It follows the + commutation rule: + Sn * a(n) = a(n + 1) * Sn + + This class represents a Recurrence Operator Algebra and serves as the parent ring + for Recurrence Operators. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy import symbols + >>> from sympy.holonomic.recurrence import RecurrenceOperators + >>> n = symbols('n', integer=True) + >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn') + >>> R + Univariate Recurrence Operator Algebra in intermediate Sn over the base ring + ZZ[n] + + See Also + ======== + + RecurrenceOperator + """ + + def __init__(self, base, generator): + # the base ring for the algebra + self.base = base + # the operator representing shift i.e. `Sn` + self.shift_operator = RecurrenceOperator( + [base.zero, base.one], self) + + if generator is None: + self.gen_symbol = symbols('Sn', commutative=False) + else: + if isinstance(generator, str): + self.gen_symbol = symbols(generator, commutative=False) + elif isinstance(generator, Symbol): + self.gen_symbol = generator + + def __str__(self): + string = 'Univariate Recurrence Operator Algebra in intermediate '\ + + sstr(self.gen_symbol) + ' over the base ring ' + \ + (self.base).__str__() + + return string + + __repr__ = __str__ + + def __eq__(self, other): + if self.base == other.base and self.gen_symbol == other.gen_symbol: + return True + else: + return False + + +def _add_lists(list1, list2): + if len(list1) <= len(list2): + sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):] + else: + sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):] + return sol + + +class RecurrenceOperator: + """ + The Recurrence Operators are defined by a list of polynomials + in the base ring and the parent ring of the Operator. + + Explanation + =========== + + Takes a list of polynomials for each power of Sn and the + parent ring which must be an instance of RecurrenceOperatorAlgebra. + + A Recurrence Operator can be created easily using + the operator `Sn`. See examples below. + + Examples + ======== + + >>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> n = symbols('n', integer=True) + >>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn') + + >>> RecurrenceOperator([0, 1, n**2], R) + (1)Sn + (n**2)Sn**2 + + >>> Sn*n + (n + 1)Sn + + >>> n*Sn*n + 1 - Sn**2*n + (1) + (n**2 + n)Sn + (-n - 2)Sn**2 + + See Also + ======== + + DifferentialOperatorAlgebra + """ + + _op_priority = 20 + + def __init__(self, list_of_poly, parent): + # the parent ring for this operator + # must be an RecurrenceOperatorAlgebra object + self.parent = parent + # sequence of polynomials in n for each power of Sn + # represents the operator + # convert the expressions into ring elements using from_sympy + if isinstance(list_of_poly, list): + for i, j in enumerate(list_of_poly): + if isinstance(j, int): + list_of_poly[i] = self.parent.base.from_sympy(S(j)) + elif not isinstance(j, self.parent.base.dtype): + list_of_poly[i] = self.parent.base.from_sympy(j) + + self.listofpoly = list_of_poly + self.order = len(self.listofpoly) - 1 + + def __mul__(self, other): + """ + Multiplies two Operators and returns another + RecurrenceOperator instance using the commutation rule + Sn * a(n) = a(n + 1) * Sn + """ + + listofself = self.listofpoly + base = self.parent.base + + if not isinstance(other, RecurrenceOperator): + if not isinstance(other, self.parent.base.dtype): + listofother = [self.parent.base.from_sympy(sympify(other))] + + else: + listofother = [other] + else: + listofother = other.listofpoly + # multiply a polynomial `b` with a list of polynomials + + def _mul_dmp_diffop(b, listofother): + if isinstance(listofother, list): + sol = [] + for i in listofother: + sol.append(i * b) + return sol + else: + return [b * listofother] + + sol = _mul_dmp_diffop(listofself[0], listofother) + + # compute Sn^i * b + def _mul_Sni_b(b): + sol = [base.zero] + + if isinstance(b, list): + for i in b: + j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One) + sol.append(base.from_sympy(j)) + + else: + j = b.subs(base.gens[0], base.gens[0] + S.One) + sol.append(base.from_sympy(j)) + + return sol + + for i in range(1, len(listofself)): + # find Sn^i * b in ith iteration + listofother = _mul_Sni_b(listofother) + # solution = solution + listofself[i] * (Sn^i * b) + sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) + + return RecurrenceOperator(sol, self.parent) + + def __rmul__(self, other): + if not isinstance(other, RecurrenceOperator): + + if isinstance(other, int): + other = S(other) + + if not isinstance(other, self.parent.base.dtype): + other = (self.parent.base).from_sympy(other) + + sol = [] + for j in self.listofpoly: + sol.append(other * j) + + return RecurrenceOperator(sol, self.parent) + + def __add__(self, other): + if isinstance(other, RecurrenceOperator): + + sol = _add_lists(self.listofpoly, other.listofpoly) + return RecurrenceOperator(sol, self.parent) + + else: + + if isinstance(other, int): + other = S(other) + list_self = self.listofpoly + if not isinstance(other, self.parent.base.dtype): + list_other = [((self.parent).base).from_sympy(other)] + else: + list_other = [other] + sol = [] + sol.append(list_self[0] + list_other[0]) + sol += list_self[1:] + + return RecurrenceOperator(sol, self.parent) + + __radd__ = __add__ + + def __sub__(self, other): + return self + (-1) * other + + def __rsub__(self, other): + return (-1) * self + other + + def __pow__(self, n): + if n == 1: + return self + if n == 0: + return RecurrenceOperator([self.parent.base.one], self.parent) + # if self is `Sn` + if self.listofpoly == self.parent.shift_operator.listofpoly: + sol = [] + for i in range(0, n): + sol.append(self.parent.base.zero) + sol.append(self.parent.base.one) + + return RecurrenceOperator(sol, self.parent) + + else: + if n % 2 == 1: + powreduce = self**(n - 1) + return powreduce * self + elif n % 2 == 0: + powreduce = self**(n / 2) + return powreduce * powreduce + + def __str__(self): + listofpoly = self.listofpoly + print_str = '' + + for i, j in enumerate(listofpoly): + if j == self.parent.base.zero: + continue + + if i == 0: + print_str += '(' + sstr(j) + ')' + continue + + if print_str: + print_str += ' + ' + + if i == 1: + print_str += '(' + sstr(j) + ')Sn' + continue + + print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i) + + return print_str + + __repr__ = __str__ + + def __eq__(self, other): + if isinstance(other, RecurrenceOperator): + if self.listofpoly == other.listofpoly and self.parent == other.parent: + return True + else: + return False + else: + if self.listofpoly[0] == other: + for i in self.listofpoly[1:]: + if i is not self.parent.base.zero: + return False + return True + else: + return False + + +class HolonomicSequence: + """ + A Holonomic Sequence is a type of sequence satisfying a linear homogeneous + recurrence relation with Polynomial coefficients. Alternatively, A sequence + is Holonomic if and only if its generating function is a Holonomic Function. + """ + + def __init__(self, recurrence, u0=[]): + self.recurrence = recurrence + if not isinstance(u0, list): + self.u0 = [u0] + else: + self.u0 = u0 + + if len(self.u0) == 0: + self._have_init_cond = False + else: + self._have_init_cond = True + self.n = recurrence.parent.base.gens[0] + + def __repr__(self): + str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n)) + if not self._have_init_cond: + return str_sol + else: + cond_str = '' + seq_str = 0 + for i in self.u0: + cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i)) + seq_str += 1 + + sol = str_sol + cond_str + return sol + + __str__ = __repr__ + + def __eq__(self, other): + if self.recurrence == other.recurrence: + if self.n == other.n: + if self._have_init_cond and other._have_init_cond: + if self.u0 == other.u0: + return True + else: + return False + else: + return True + else: + return False + else: + return False diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d25868a3831692be51b645fa8bd5a803f4697b51 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..629fae2638afa65db234adf318126629be5f00e4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff415050748b46ac33ce28883d31e9c55e249047 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py new file mode 100644 index 0000000000000000000000000000000000000000..e5069c89a84ab89c46c95a026c8998089b73fac5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py @@ -0,0 +1,830 @@ +from sympy.holonomic import (DifferentialOperator, HolonomicFunction, + DifferentialOperators, from_hyper, + from_meijerg, expr_to_holonomic) +from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence +from sympy.core import EulerGamma +from sympy.core.numbers import (I, Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.hyperbolic import (asinh, cosh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.bessel import besselj +from sympy.functions.special.beta_functions import beta +from sympy.functions.special.error_functions import (Ci, Si, erf, erfc) +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import (hyper, meijerg) +from sympy.printing.str import sstr +from sympy.series.order import O +from sympy.simplify.hyperexpand import hyperexpand +from sympy.polys.domains.integerring import ZZ +from sympy.polys.domains.rationalfield import QQ +from sympy.polys.domains.realfield import RR + + +def test_DifferentialOperator(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + assert Dx == R.derivative_operator + assert Dx == DifferentialOperator([R.base.zero, R.base.one], R) + assert x * Dx + x**2 * Dx**2 == DifferentialOperator([0, x, x**2], R) + assert (x**2 + 1) + Dx + x * \ + Dx**5 == DifferentialOperator([x**2 + 1, 1, 0, 0, 0, x], R) + assert (x * Dx + x**2 + 1 - Dx * (x**3 + x))**3 == (-48 * x**6) + \ + (-57 * x**7) * Dx + (-15 * x**8) * Dx**2 + (-x**9) * Dx**3 + p = (x * Dx**2 + (x**2 + 3) * Dx**5) * (Dx + x**2) + q = (2 * x) + (4 * x**2) * Dx + (x**3) * Dx**2 + \ + (20 * x**2 + x + 60) * Dx**3 + (10 * x**3 + 30 * x) * Dx**4 + \ + (x**4 + 3 * x**2) * Dx**5 + (x**2 + 3) * Dx**6 + assert p == q + + +def test_HolonomicFunction_addition(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx**2 * x, x) + q = HolonomicFunction((2) * Dx + (x) * Dx**2, x) + assert p == q + p = HolonomicFunction(x * Dx + 1, x) + q = HolonomicFunction(Dx + 1, x) + r = HolonomicFunction((x - 2) + (x**2 - 2) * Dx + (x**2 - x) * Dx**2, x) + assert p + q == r + p = HolonomicFunction(x * Dx + Dx**2 * (x**2 + 2), x) + q = HolonomicFunction(Dx - 3, x) + r = HolonomicFunction((-54 * x**2 - 126 * x - 150) + (-135 * x**3 - 252 * x**2 - 270 * x + 140) * Dx +\ + (-27 * x**4 - 24 * x**2 + 14 * x - 150) * Dx**2 + \ + (9 * x**4 + 15 * x**3 + 38 * x**2 + 30 * x +40) * Dx**3, x) + assert p + q == r + p = HolonomicFunction(Dx**5 - 1, x) + q = HolonomicFunction(x**3 + Dx, x) + r = HolonomicFunction((-x**18 + 45*x**14 - 525*x**10 + 1575*x**6 - x**3 - 630*x**2) + \ + (-x**15 + 30*x**11 - 195*x**7 + 210*x**3 - 1)*Dx + (x**18 - 45*x**14 + 525*x**10 - \ + 1575*x**6 + x**3 + 630*x**2)*Dx**5 + (x**15 - 30*x**11 + 195*x**7 - 210*x**3 + \ + 1)*Dx**6, x) + assert p+q == r + + p = x**2 + 3*x + 8 + q = x**3 - 7*x + 5 + p = p*Dx - p.diff() + q = q*Dx - q.diff() + r = HolonomicFunction(p, x) + HolonomicFunction(q, x) + s = HolonomicFunction((6*x**2 + 18*x + 14) + (-4*x**3 - 18*x**2 - 62*x + 10)*Dx +\ + (x**4 + 6*x**3 + 31*x**2 - 10*x - 71)*Dx**2, x) + assert r == s + + +def test_HolonomicFunction_multiplication(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx+x+x*Dx**2, x) + q = HolonomicFunction(x*Dx+Dx*x+Dx**2, x) + r = HolonomicFunction((8*x**6 + 4*x**4 + 6*x**2 + 3) + (24*x**5 - 4*x**3 + 24*x)*Dx + \ + (8*x**6 + 20*x**4 + 12*x**2 + 2)*Dx**2 + (8*x**5 + 4*x**3 + 4*x)*Dx**3 + \ + (2*x**4 + x**2)*Dx**4, x) + assert p*q == r + p = HolonomicFunction(Dx**2+1, x) + q = HolonomicFunction(Dx-1, x) + r = HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x) + assert p*q == r + p = HolonomicFunction(Dx**2+1+x+Dx, x) + q = HolonomicFunction((Dx*x-1)**2, x) + r = HolonomicFunction((4*x**7 + 11*x**6 + 16*x**5 + 4*x**4 - 6*x**3 - 7*x**2 - 8*x - 2) + \ + (8*x**6 + 26*x**5 + 24*x**4 - 3*x**3 - 11*x**2 - 6*x - 2)*Dx + \ + (8*x**6 + 18*x**5 + 15*x**4 - 3*x**3 - 6*x**2 - 6*x - 2)*Dx**2 + (8*x**5 + \ + 10*x**4 + 6*x**3 - 2*x**2 - 4*x)*Dx**3 + (4*x**5 + 3*x**4 - x**2)*Dx**4, x) + assert p*q == r + p = HolonomicFunction(x*Dx**2-1, x) + q = HolonomicFunction(Dx*x-x, x) + r = HolonomicFunction((x - 3) + (-2*x + 2)*Dx + (x)*Dx**2, x) + assert p*q == r + + +def test_addition_initial_condition(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx-1, x, 0, [3]) + q = HolonomicFunction(Dx**2+1, x, 0, [1, 0]) + r = HolonomicFunction(-1 + Dx - Dx**2 + Dx**3, x, 0, [4, 3, 2]) + assert p + q == r + p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2]) + q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0]) + r = HolonomicFunction((-x**4 - x**3/4 - x**2 + Rational(1, 4)) + (x**3 + x**2/4 + x*Rational(3, 4) + 1)*Dx + \ + (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]) + assert p + q == r + p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4]) + q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1]) + r = HolonomicFunction((x**6 + 2*x**4 - 5*x**2 - 6) + (4*x**5 + 36*x**3 - 32*x)*Dx + \ + (x**6 + 3*x**4 + 5*x**2 - 9)*Dx**2 + (4*x**5 + 36*x**3 - 32*x)*Dx**3 + (x**4 + \ + 10*x**2 - 3)*Dx**4, x, 0, [4, 5, -1, -17]) + assert p + q == r + q = HolonomicFunction(Dx**3 + x, x, 2, [3, 0, 1]) + p = HolonomicFunction(Dx - 1, x, 2, [1]) + r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \ + (x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ]) + assert p + q == r + p = expr_to_holonomic(sin(x)) + q = expr_to_holonomic(1/x, x0=1) + r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \ + x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2]) + assert p + q == r + C_1 = symbols('C_1') + p = expr_to_holonomic(sqrt(x)) + q = expr_to_holonomic(sqrt(x**2-x)) + r = (p + q).to_expr().subs(C_1, -I/2).expand() + assert r == I*sqrt(x)*sqrt(-x + 1) + sqrt(x) + + +def test_multiplication_initial_condition(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx**2 + x*Dx - 1, x, 0, [3, 1]) + q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1]) + r = HolonomicFunction((x**4 + 14*x**2 + 60) + 4*x*Dx + (x**4 + 9*x**2 + 20)*Dx**2 + \ + (2*x**3 + 18*x)*Dx**3 + (x**2 + 10)*Dx**4, x, 0, [3, 4, 2, 3]) + assert p * q == r + p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0]) + q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3]) + r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \ + 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 + \ + 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 + \ + 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 + \ + (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 + \ + 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]) + assert p * q == r + p = HolonomicFunction(Dx - 1, x, 0, [2]) + q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) + r = HolonomicFunction(2 -2*Dx + Dx**2, x, 0, [0, 2]) + assert p * q == r + q = HolonomicFunction(x*Dx**2 + 1 + 2*Dx, x, 0,[0, 1]) + r = HolonomicFunction((x - 1) + (-2*x + 2)*Dx + x*Dx**2, x, 0, [0, 2]) + assert p * q == r + p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 3]) + q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1]) + r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2]) + assert p * q == r + p = expr_to_holonomic(sin(x)) + q = expr_to_holonomic(1/x, x0=1) + r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)]) + assert p * q == r + p = expr_to_holonomic(sqrt(x)) + q = expr_to_holonomic(sqrt(x**2-x)) + r = (p * q).to_expr() + assert r == I*x*sqrt(-x + 1) + + +def test_HolonomicFunction_composition(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx-1, x).composition(x**2+x) + r = HolonomicFunction((-2*x - 1) + Dx, x) + assert p == r + p = HolonomicFunction(Dx**2+1, x).composition(x**5+x**2+1) + r = HolonomicFunction((125*x**12 + 150*x**9 + 60*x**6 + 8*x**3) + (-20*x**3 - 2)*Dx + \ + (5*x**4 + 2*x)*Dx**2, x) + assert p == r + p = HolonomicFunction(Dx**2*x+x, x).composition(2*x**3+x**2+1) + r = HolonomicFunction((216*x**9 + 324*x**8 + 180*x**7 + 152*x**6 + 112*x**5 + \ + 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 + \ + x**3 + 3*x**2 + x)*Dx**2, x) + assert p == r + p = HolonomicFunction(Dx**2+1, x).composition(1-x**2) + r = HolonomicFunction((4*x**3) - Dx + x*Dx**2, x) + assert p == r + p = HolonomicFunction(Dx**2+1, x).composition(x - 2/(x**2 + 1)) + r = HolonomicFunction((x**12 + 6*x**10 + 12*x**9 + 15*x**8 + 48*x**7 + 68*x**6 + \ + 72*x**5 + 111*x**4 + 112*x**3 + 54*x**2 + 12*x + 1) + (12*x**8 + 32*x**6 + \ + 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+ \ + 15*x**4 + 16*x**3 + 6*x**2 + 4*x + 1)*Dx**2, x) + assert p == r + + +def test_from_hyper(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + p = hyper([1, 1], [Rational(3, 2)], x**2/4) + 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)]) + r = from_hyper(p) + assert r == q + p = from_hyper(hyper([1], [Rational(3, 2)], x**2/4)) + q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x) + # x0 = 1 + y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]' + assert sstr(p.y0) == y0 + assert q.annihilator == p.annihilator + + +def test_from_meijerg(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + p = from_meijerg(meijerg(([], [Rational(3, 2)]), ([S.Half], [S.Half, 1]), x)) + q = HolonomicFunction(x/2 - Rational(1, 4) + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \ + [1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))]) + assert p == q + p = from_meijerg(meijerg(([], []), ([0], []), x)) + q = HolonomicFunction(1 + Dx, x, 0, [1]) + assert p == q + p = from_meijerg(meijerg(([1], []), ([S.Half], [0]), x)) + q = HolonomicFunction((x + S.Half)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)]) + assert p == q + p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2)) + q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(Rational(-1, 2)) + 1, -exp(Rational(-1, 2))]) + assert p == q + + +def test_to_Sequence(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + n = symbols('n', integer=True) + _, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn') + p = HolonomicFunction(x**2*Dx**4 + x + Dx, x).to_sequence() + q = [(HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 0, 1)] + assert p == q + p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence() + q = [(HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0, 0)] + assert p == q + p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence() + q = [(HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 0, 0)] + assert p == q + p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence() + 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)] + assert p == q + + +def test_to_Sequence_Initial_Coniditons(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + n = symbols('n', integer=True) + _, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn') + p = HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence() + q = [(HolonomicSequence(-1 + (n + 1)*Sn, 1), 0)] + assert p == q + p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_sequence() + q = [(HolonomicSequence(1 + (n**2 + 3*n + 2)*Sn**2, [0, 1]), 0)] + assert p == q + p = HolonomicFunction(Dx**2 + 1 + x**3*Dx, x, 0, [2, 3]).to_sequence() + q = [(HolonomicSequence(n + Sn**2 + (n**2 + 7*n + 12)*Sn**4, [2, 3, -1, Rational(-1, 2), Rational(1, 12)]), 1)] + assert p == q + p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence() + q = [(HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 0, 3)] + assert p == q + C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3') + p = expr_to_holonomic(log(1+x**2)) + q = [(HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2]), 0, 1)] + assert p.to_sequence() == q + p = p.diff() + q = [(HolonomicSequence((n + 2) + (n + 2)*Sn**2, [C_0, 0]), 1, 0)] + assert p.to_sequence() == q + p = expr_to_holonomic(erf(x) + x).to_sequence() + 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)] + assert p == q + +def test_series(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx**2 + 2*x*Dx, x, 0, [0, 1]).series(n=10) + q = x - x**3/3 + x**5/10 - x**7/42 + x**9/216 + O(x**10) + assert p == q + p = HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2) + q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # cos(x) + r = (p * q).series(n=10) # expansion of cos(x) * exp(x**2) + s = 1 + x**2/2 + x**4/24 - 31*x**6/720 - 179*x**8/8064 + O(x**10) + assert r == s + t = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # log(1 + x) + r = (p * t + q).series(n=10) + s = 1 + x - x**2 + 4*x**3/3 - 17*x**4/24 + 31*x**5/30 - 481*x**6/720 +\ + 71*x**7/105 - 20159*x**8/40320 + 379*x**9/840 + O(x**10) + assert r == s + p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \ + (4-6*x**3+2*x**4)*Dx**2, x, 0, [0, 1]).series(n=7) + q = x + x**3/6 - 3*x**4/16 + x**5/20 - 23*x**6/960 + O(x**7) + assert p == q + p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \ + (4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7) + q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7) + assert p == q + p = expr_to_holonomic(erf(x) + x).series(n=10) + C_3 = symbols('C_3') + q = (erf(x) + x).series(n=10) + assert p.subs(C_3, -2/(3*sqrt(pi))) == q + assert expr_to_holonomic(sqrt(x**3 + x)).series(n=10) == sqrt(x**3 + x).series(n=10) + assert expr_to_holonomic((2*x - 3*x**2)**Rational(1, 3)).series() == ((2*x - 3*x**2)**Rational(1, 3)).series() + assert expr_to_holonomic(sqrt(x**2-x)).series() == (sqrt(x**2-x)).series() + 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) + 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() + assert expr_to_holonomic(cos(x-1)**2/(x-1)**2, x0=1, y0={-2: [1, 0, -1]}).series(n=10) \ + == (cos(x-1)**2/(x-1)**2).series(x0=1, n=10) + +def test_evalf_euler(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + + # log(1+x) + p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) + + # path taken is a straight line from 0 to 1, on the real axis + r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] + s = '0.699525841805253' # approx. equal to log(2) i.e. 0.693147180559945 + assert sstr(p.evalf(r, method='Euler')[-1]) == s + + # path taken is a triangle 0-->1+i-->2 + r = [0.1 + 0.1*I] + for i in range(9): + r.append(r[-1]+0.1+0.1*I) + for i in range(10): + r.append(r[-1]+0.1-0.1*I) + + # close to the exact solution 1.09861228866811 + # imaginary part also close to zero + s = '1.07530466271334 - 0.0251200594793912*I' + assert sstr(p.evalf(r, method='Euler')[-1]) == s + + # sin(x) + p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) + s = '0.905546532085401 - 6.93889390390723e-18*I' + assert sstr(p.evalf(r, method='Euler')[-1]) == s + + # computing sin(pi/2) using this method + # using a linear path from 0 to pi/2 + r = [0.1] + for i in range(14): + r.append(r[-1] + 0.1) + r.append(pi/2) + s = '1.08016557252834' # close to 1.0 (exact solution) + assert sstr(p.evalf(r, method='Euler')[-1]) == s + + # trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2) + # computing the same value sin(pi/2) using different path + r = [0.1*I] + for i in range(9): + r.append(r[-1]+0.1*I) + for i in range(15): + r.append(r[-1]+0.1) + r.append(pi/2+I) + for i in range(10): + r.append(r[-1]-0.1*I) + + # close to 1.0 + s = '0.976882381836257 - 1.65557671738537e-16*I' + assert sstr(p.evalf(r, method='Euler')[-1]) == s + + # cos(x) + p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) + # compute cos(pi) along 0-->pi + r = [0.05] + for i in range(61): + r.append(r[-1]+0.05) + r.append(pi) + # close to -1 (exact answer) + s = '-1.08140824719196' + assert sstr(p.evalf(r, method='Euler')[-1]) == s + + # a rectangular path (0 -> i -> 2+i -> 2) + r = [0.1*I] + for i in range(9): + r.append(r[-1]+0.1*I) + for i in range(20): + r.append(r[-1]+0.1) + for i in range(10): + r.append(r[-1]-0.1*I) + + p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r, method='Euler') + s = '0.501421652861245 - 3.88578058618805e-16*I' + assert sstr(p[-1]) == s + +def test_evalf_rk4(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + + # log(1+x) + p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) + + # path taken is a straight line from 0 to 1, on the real axis + r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] + s = '0.693146363174626' # approx. equal to log(2) i.e. 0.693147180559945 + assert sstr(p.evalf(r)[-1]) == s + + # path taken is a triangle 0-->1+i-->2 + r = [0.1 + 0.1*I] + for i in range(9): + r.append(r[-1]+0.1+0.1*I) + for i in range(10): + r.append(r[-1]+0.1-0.1*I) + + # close to the exact solution 1.09861228866811 + # imaginary part also close to zero + s = '1.098616 + 1.36083e-7*I' + assert sstr(p.evalf(r)[-1].n(7)) == s + + # sin(x) + p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) + s = '0.90929463522785 + 1.52655665885959e-16*I' + assert sstr(p.evalf(r)[-1]) == s + + # computing sin(pi/2) using this method + # using a linear path from 0 to pi/2 + r = [0.1] + for i in range(14): + r.append(r[-1] + 0.1) + r.append(pi/2) + s = '0.999999895088917' # close to 1.0 (exact solution) + assert sstr(p.evalf(r)[-1]) == s + + # trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2) + # computing the same value sin(pi/2) using different path + r = [0.1*I] + for i in range(9): + r.append(r[-1]+0.1*I) + for i in range(15): + r.append(r[-1]+0.1) + r.append(pi/2+I) + for i in range(10): + r.append(r[-1]-0.1*I) + + # close to 1.0 + s = '1.00000003415141 + 6.11940487991086e-16*I' + assert sstr(p.evalf(r)[-1]) == s + + # cos(x) + p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) + # compute cos(pi) along 0-->pi + r = [0.05] + for i in range(61): + r.append(r[-1]+0.05) + r.append(pi) + # close to -1 (exact answer) + s = '-0.999999993238714' + assert sstr(p.evalf(r)[-1]) == s + + # a rectangular path (0 -> i -> 2+i -> 2) + r = [0.1*I] + for i in range(9): + r.append(r[-1]+0.1*I) + for i in range(20): + r.append(r[-1]+0.1) + for i in range(10): + r.append(r[-1]-0.1*I) + + p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r) + s = '0.493152791638442 - 1.41553435639707e-15*I' + assert sstr(p[-1]) == s + + +def test_expr_to_holonomic(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + p = expr_to_holonomic((sin(x)/x)**2) + q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \ + [1, 0, Rational(-2, 3)]) + assert p == q + p = expr_to_holonomic(1/(1+x**2)**2) + q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, [1]) + assert p == q + p = expr_to_holonomic(exp(x)*sin(x)+x*log(1+x)) + q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \ + - 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \ + (-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \ + 7*x**2/2 + x + Rational(5, 2))*Dx**4, x, 0, [0, 1, 4, -1]) + assert p == q + p = expr_to_holonomic(x*exp(x)+cos(x)+1) + q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \ + 0, [2, 1, 1, 3]) + assert p == q + assert (x*exp(x)+cos(x)+1).series(n=10) == p.series(n=10) + p = expr_to_holonomic(log(1 + x)**2 + 1) + q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2]) + assert p == q + p = expr_to_holonomic(erf(x)**2 + x) + q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \ + (x**2+ Rational(1, 4))*Dx**4, x, 0, [0, 1, 8/pi, 0]) + assert p == q + p = expr_to_holonomic(cosh(x)*x) + q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1]) + assert p == q + p = expr_to_holonomic(besselj(2, x)) + q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0]) + assert p == q + p = expr_to_holonomic(besselj(0, x) + exp(x)) + q = HolonomicFunction((-x**2 - x/2 + S.Half) + (x**2 - x/2 - Rational(3, 2))*Dx + (-x**2 + x/2 + 1)*Dx**2 +\ + (x**2 + x/2)*Dx**3, x, 0, [2, 1, S.Half]) + assert p == q + p = expr_to_holonomic(sin(x)**2/x) + q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0]) + assert p == q + p = expr_to_holonomic(sin(x)**2/x, x0=2) + q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2, + sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)]) + assert p == q + p = expr_to_holonomic(log(x)/2 - Ci(2*x)/2 + Ci(2)/2) + q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \ + [-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0]) + assert p == q + p = p.to_expr() + q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2 + assert p == q + p = expr_to_holonomic(x**S.Half, x0=1) + q = HolonomicFunction(x*Dx - S.Half, x, 1, [1]) + assert p == q + p = expr_to_holonomic(sqrt(1 + x**2)) + q = HolonomicFunction((-x) + (x**2 + 1)*Dx, x, 0, [1]) + assert p == q + assert (expr_to_holonomic(sqrt(x) + sqrt(2*x)).to_expr()-\ + (sqrt(x) + sqrt(2*x))).simplify() == 0 + assert expr_to_holonomic(3*x+2*sqrt(x)).to_expr() == 3*x+2*sqrt(x) + p = expr_to_holonomic((x**4+x**3+5*x**2+3*x+2)/x**2, lenics=3) + q = HolonomicFunction((-2*x**4 - x**3 + 3*x + 4) + (x**5 + x**4 + 5*x**3 + 3*x**2 + \ + 2*x)*Dx, x, 0, {-2: [2, 3, 5]}) + assert p == q + p = expr_to_holonomic(1/(x-1)**2, lenics=3, x0=1) + q = HolonomicFunction((2) + (x - 1)*Dx, x, 1, {-2: [1, 0, 0]}) + assert p == q + a = symbols("a") + p = expr_to_holonomic(sqrt(a*x), x=x) + assert p.to_expr() == sqrt(a)*sqrt(x) + +def test_to_hyper(): + x = symbols('x') + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx - 2, x, 0, [3]).to_hyper() + q = 3 * hyper([], [], 2*x) + assert p == q + p = hyperexpand(HolonomicFunction((1 + x) * Dx - 3, x, 0, [2]).to_hyper()).expand() + q = 2*x**3 + 6*x**2 + 6*x + 2 + assert p == q + p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_hyper() + q = -x**2*hyper((2, 2, 1), (3, 2), -x)/2 + x + assert p == q + p = HolonomicFunction(2*x*Dx + Dx**2, x, 0, [0, 2/sqrt(pi)]).to_hyper() + q = 2*x*hyper((S.Half,), (Rational(3, 2),), -x**2)/sqrt(pi) + assert p == q + p = hyperexpand(HolonomicFunction(2*x*Dx + Dx**2, x, 0, [1, -2/sqrt(pi)]).to_hyper()) + q = erfc(x) + assert p.rewrite(erfc) == q + p = hyperexpand(HolonomicFunction((x**2 - 1) + x*Dx + x**2*Dx**2, + x, 0, [0, S.Half]).to_hyper()) + q = besselj(1, x) + assert p == q + p = hyperexpand(HolonomicFunction(x*Dx**2 + Dx + x, x, 0, [1, 0]).to_hyper()) + q = besselj(0, x) + assert p == q + +def test_to_expr(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(Dx - 1, x, 0, [1]).to_expr() + q = exp(x) + assert p == q + p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).to_expr() + q = cos(x) + assert p == q + p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]).to_expr() + q = cosh(x) + assert p == q + p = HolonomicFunction(2 + (4*x - 1)*Dx + \ + (x**2 - x)*Dx**2, x, 0, [1, 2]).to_expr().expand() + q = 1/(x**2 - 2*x + 1) + assert p == q + p = expr_to_holonomic(sin(x)**2/x).integrate((x, 0, x)).to_expr() + q = (sin(x)**2/x).integrate((x, 0, x)) + assert p == q + C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3') + p = expr_to_holonomic(log(1+x**2)).to_expr() + q = C_2*log(x**2 + 1) + assert p == q + p = expr_to_holonomic(log(1+x**2)).diff().to_expr() + q = C_0*x/(x**2 + 1) + assert p == q + p = expr_to_holonomic(erf(x) + x).to_expr() + q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi) + assert p == q + p = expr_to_holonomic(sqrt(x), x0=1).to_expr() + assert p == sqrt(x) + assert expr_to_holonomic(sqrt(x)).to_expr() == sqrt(x) + p = expr_to_holonomic(sqrt(1 + x**2)).to_expr() + assert p == sqrt(1+x**2) + p = expr_to_holonomic((2*x**2 + 1)**Rational(2, 3)).to_expr() + assert p == (2*x**2 + 1)**Rational(2, 3) + p = expr_to_holonomic(sqrt(-x**2+2*x)).to_expr() + assert p == sqrt(x)*sqrt(-x + 2) + p = expr_to_holonomic((-2*x**3+7*x)**Rational(2, 3)).to_expr() + q = x**Rational(2, 3)*(-2*x**2 + 7)**Rational(2, 3) + assert p == q + p = from_hyper(hyper((-2, -3), (S.Half, ), x)) + s = hyperexpand(hyper((-2, -3), (S.Half, ), x)) + D_0 = Symbol('D_0') + C_0 = Symbol('C_0') + assert (p.to_expr().subs({C_0:1, D_0:0}) - s).simplify() == 0 + p.y0 = {0: [1], S.Half: [0]} + assert p.to_expr() == s + assert expr_to_holonomic(x**5).to_expr() == x**5 + assert expr_to_holonomic(2*x**3-3*x**2).to_expr().expand() == \ + 2*x**3-3*x**2 + a = symbols("a") + p = (expr_to_holonomic(1.4*x)*expr_to_holonomic(a*x, x)).to_expr() + q = 1.4*a*x**2 + assert p == q + p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(a*x, x)).to_expr() + q = x*(a + 1.4) + assert p == q + p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(x)).to_expr() + assert p == 2.4*x + + +def test_integrate(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 2, 3)) + q = '0.166270406994788' + assert sstr(p) == q + p = expr_to_holonomic(sin(x)).integrate((x, 0, x)).to_expr() + q = 1 - cos(x) + assert p == q + p = expr_to_holonomic(sin(x)).integrate((x, 0, 3)) + q = 1 - cos(3) + assert p == q + p = expr_to_holonomic(sin(x)/x, x0=1).integrate((x, 1, 2)) + q = '0.659329913368450' + assert sstr(p) == q + p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 1, 0)) + q = '-0.423690480850035' + assert sstr(p) == q + p = expr_to_holonomic(sin(x)/x) + assert p.integrate(x).to_expr() == Si(x) + assert p.integrate((x, 0, 2)) == Si(2) + p = expr_to_holonomic(sin(x)**2/x) + q = p.to_expr() + assert p.integrate(x).to_expr() == q.integrate((x, 0, x)) + assert p.integrate((x, 0, 1)) == q.integrate((x, 0, 1)) + assert expr_to_holonomic(1/x, x0=1).integrate(x).to_expr() == log(x) + p = expr_to_holonomic((x + 1)**3*exp(-x), x0=-1).integrate(x).to_expr() + q = (-x**3 - 6*x**2 - 15*x + 6*exp(x + 1) - 16)*exp(-x) + assert p == q + p = expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).integrate(x).to_expr() + q = -Si(2*x) - cos(x)**2/x + assert p == q + p = expr_to_holonomic(sqrt(x**2+x)).integrate(x).to_expr() + q = (x**Rational(3, 2)*(2*x**2 + 3*x + 1) - x*sqrt(x + 1)*asinh(sqrt(x)))/(4*x*sqrt(x + 1)) + assert p == q + p = expr_to_holonomic(sqrt(x**2+1)).integrate(x).to_expr() + q = (sqrt(x**2+1)).integrate(x) + assert (p-q).simplify() == 0 + p = expr_to_holonomic(1/x**2, y0={-2:[1, 0, 0]}) + r = expr_to_holonomic(1/x**2, lenics=3) + assert p == r + q = expr_to_holonomic(cos(x)**2) + assert (r*q).integrate(x).to_expr() == -Si(2*x) - cos(x)**2/x + + +def test_diff(): + x, y = symbols('x, y') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1]) + assert p.diff().to_expr() == p.to_expr().diff().simplify() + p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]) + assert p.diff(x, 2).to_expr() == p.to_expr() + p = expr_to_holonomic(Si(x)) + assert p.diff().to_expr() == sin(x)/x + assert p.diff(y) == 0 + C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3') + q = Si(x) + assert p.diff(x).to_expr() == q.diff() + assert p.diff(x, 2).to_expr().subs(C_0, Rational(-1, 3)).cancel() == q.diff(x, 2).cancel() + assert p.diff(x, 3).series().subs({C_3: Rational(-1, 3), C_0: 0}) == q.diff(x, 3).series() + + +def test_extended_domain_in_expr_to_holonomic(): + x = symbols('x') + p = expr_to_holonomic(1.2*cos(3.1*x)) + assert p.to_expr() == 1.2*cos(3.1*x) + assert sstr(p.integrate(x).to_expr()) == '0.387096774193548*sin(3.1*x)' + _, Dx = DifferentialOperators(RR.old_poly_ring(x), 'Dx') + p = expr_to_holonomic(1.1329138213*x) + q = HolonomicFunction((-1.1329138213) + (1.1329138213*x)*Dx, x, 0, {1: [1.1329138213]}) + assert p == q + assert p.to_expr() == 1.1329138213*x + assert sstr(p.integrate((x, 1, 2))) == sstr((1.1329138213*x).integrate((x, 1, 2))) + y, z = symbols('y, z') + p = expr_to_holonomic(sin(x*y*z), x=x) + assert p.to_expr() == sin(x*y*z) + assert p.integrate(x).to_expr() == (-cos(x*y*z) + 1)/(y*z) + p = expr_to_holonomic(sin(x*y + z), x=x).integrate(x).to_expr() + q = (cos(z) - cos(x*y + z))/y + assert p == q + a = symbols('a') + p = expr_to_holonomic(a*x, x) + assert p.to_expr() == a*x + assert p.integrate(x).to_expr() == a*x**2/2 + D_2, C_1 = symbols("D_2, C_1") + p = expr_to_holonomic(x) + expr_to_holonomic(1.2*cos(x)) + p = p.to_expr().subs(D_2, 0) + assert p - x - 1.2*cos(1.0*x) == 0 + p = expr_to_holonomic(x) * expr_to_holonomic(1.2*cos(x)) + p = p.to_expr().subs(C_1, 0) + assert p - 1.2*x*cos(1.0*x) == 0 + + +def test_to_meijerg(): + x = symbols('x') + assert hyperexpand(expr_to_holonomic(sin(x)).to_meijerg()) == sin(x) + assert hyperexpand(expr_to_holonomic(cos(x)).to_meijerg()) == cos(x) + assert hyperexpand(expr_to_holonomic(exp(x)).to_meijerg()) == exp(x) + assert hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() == log(x) + assert expr_to_holonomic(4*x**2/3 + 7).to_meijerg() == 4*x**2/3 + 7 + assert hyperexpand(expr_to_holonomic(besselj(2, x), lenics=3).to_meijerg()) == besselj(2, x) + p = hyper((Rational(-1, 2), -3), (), x) + assert from_hyper(p).to_meijerg() == hyperexpand(p) + p = hyper((S.One, S(3)), (S(2), ), x) + assert (hyperexpand(from_hyper(p).to_meijerg()) - hyperexpand(p)).expand() == 0 + p = from_hyper(hyper((-2, -3), (S.Half, ), x)) + s = hyperexpand(hyper((-2, -3), (S.Half, ), x)) + C_0 = Symbol('C_0') + C_1 = Symbol('C_1') + D_0 = Symbol('D_0') + assert (hyperexpand(p.to_meijerg()).subs({C_0:1, D_0:0}) - s).simplify() == 0 + p.y0 = {0: [1], S.Half: [0]} + assert (hyperexpand(p.to_meijerg()) - s).simplify() == 0 + p = expr_to_holonomic(besselj(S.Half, x), initcond=False) + assert (p.to_expr() - (D_0*sin(x) + C_0*cos(x) + C_1*sin(x))/sqrt(x)).simplify() == 0 + p = expr_to_holonomic(besselj(S.Half, x), y0={Rational(-1, 2): [sqrt(2)/sqrt(pi), sqrt(2)/sqrt(pi)]}) + assert (p.to_expr() - besselj(S.Half, x) - besselj(Rational(-1, 2), x)).simplify() == 0 + + +def test_gaussian(): + mu, x = symbols("mu x") + sd = symbols("sd", positive=True) + Q = QQ[mu, sd].get_field() + e = sqrt(2)*exp(-(-mu + x)**2/(2*sd**2))/(2*sqrt(pi)*sd) + h1 = expr_to_holonomic(e, x, domain=Q) + + _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') + h2 = HolonomicFunction((-mu/sd**2 + x/sd**2) + (1)*Dx, x) + + assert h1 == h2 + + +def test_beta(): + a, b, x = symbols("a b x", positive=True) + e = x**(a - 1)*(-x + 1)**(b - 1)/beta(a, b) + Q = QQ[a, b].get_field() + h1 = expr_to_holonomic(e, x, domain=Q) + + _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') + h2 = HolonomicFunction((a + x*(-a - b + 2) - 1) + (x**2 - x)*Dx, x) + + assert h1 == h2 + + +def test_gamma(): + a, b, x = symbols("a b x", positive=True) + e = b**(-a)*x**(a - 1)*exp(-x/b)/gamma(a) + Q = QQ[a, b].get_field() + h1 = expr_to_holonomic(e, x, domain=Q) + + _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') + h2 = HolonomicFunction((-a + 1 + x/b) + (x)*Dx, x) + + assert h1 == h2 + + +def test_symbolic_power(): + x, n = symbols("x n") + Q = QQ[n].get_field() + _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') + h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -n + h2 = HolonomicFunction((n) + (x)*Dx, x) + + assert h1 == h2 + + +def test_negative_power(): + x = symbols("x") + _, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -2 + h2 = HolonomicFunction((2) + (x)*Dx, x) + + assert h1 == h2 + + +def test_expr_in_power(): + x, n = symbols("x n") + Q = QQ[n].get_field() + _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') + h1 = HolonomicFunction((-1) + (x)*Dx, x) ** (n - 3) + h2 = HolonomicFunction((-n + 3) + (x)*Dx, x) + + assert h1 == h2 + +def test_DifferentialOperatorEqPoly(): + x = symbols('x', integer=True) + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + do = DifferentialOperator([x**2, R.base.zero, R.base.zero], R) + do2 = DifferentialOperator([x**2, 1, x], R) + assert not do == do2 + + # polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799 + # should work once that is solved + # p = do.listofpoly[0] + # assert do == p + + p2 = do2.listofpoly[0] + assert not do2 == p2 diff --git a/venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py new file mode 100644 index 0000000000000000000000000000000000000000..695ca43d9cd81187dc52495db2329e7a347720bc --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py @@ -0,0 +1,29 @@ +from sympy.holonomic.recurrence import RecurrenceOperators, RecurrenceOperator +from sympy.core.symbol import symbols +from sympy.polys.domains.rationalfield import QQ + +def test_RecurrenceOperator(): + n = symbols('n', integer=True) + R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn') + assert Sn*n == (n + 1)*Sn + assert Sn*n**2 == (n**2+1+2*n)*Sn + assert Sn**2*n**2 == (n**2 + 4*n + 4)*Sn**2 + p = (Sn**3*n**2 + Sn*n)**2 + q = (n**2 + 3*n + 2)*Sn**2 + (2*n**3 + 19*n**2 + 57*n + 52)*Sn**4 + (n**4 + 18*n**3 + \ + 117*n**2 + 324*n + 324)*Sn**6 + assert p == q + +def test_RecurrenceOperatorEqPoly(): + n = symbols('n', integer=True) + R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn') + rr = RecurrenceOperator([n**2, 0, 0], R) + rr2 = RecurrenceOperator([n**2, 1, n], R) + assert not rr == rr2 + + # polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799 + # should work once that is solved + # d = rr.listofpoly[0] + # assert rr == d + + d2 = rr2.listofpoly[0] + assert not rr2 == d2 diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bb0efd74cb4646ac24a1ab449c8e33686e1a5f9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c230ea5db089224664174b00ec437068c01242ad Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b0f7ebc06896241e20904981734d5fb6578aaf1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e230652aa615930a6eff58d15c1c9aa9ede8b812 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee9f2ed8c82fe4eefde6b21dff99c1ba6da1256d Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28c26d94cea13779cb7feec1834106f635a33d72 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/setexpr.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/setexpr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14ba5cf20c2b9986882ee982c43fd57d731daccb Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/setexpr.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7972d22d47969b8f88c9e53a1d1fe2da5425b40 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdf1bff84b1e0e16350dc4b9457b307f3a832e44 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..551dfbcb35e47d1397c7595f35aa0e06a2b00ee7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a006a2d4f5980f580ba64ea035da7c1efb0c68b Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f7b05ba3dde88901cd798ee52ed262808085bdb Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..533109e7a5e70209c2a6a45f4554241d4635ef4f Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/issubset.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/issubset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1edfb1bf08ddbe21d02927da39ea709c31039415 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/issubset.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d354e9d3eba7db888aa4f7678c4be2d593aaf5ae Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/power.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/power.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff27546e728e0dc91119a3120159780fc82bcf4e Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/power.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3455a25885b5d55633bd9ac4fd193e10a665cc9e Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/add.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/add.py new file mode 100644 index 0000000000000000000000000000000000000000..8c07b25ed19d21febffd6b23a92b34b787179f44 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/add.py @@ -0,0 +1,79 @@ +from sympy.core.numbers import oo, Infinity, NegativeInfinity +from sympy.core.singleton import S +from sympy.core import Basic, Expr +from sympy.multipledispatch import Dispatcher +from sympy.sets import Interval, FiniteSet + + + +# XXX: The functions in this module are clearly not tested and are broken in a +# number of ways. + +_set_add = Dispatcher('_set_add') +_set_sub = Dispatcher('_set_sub') + + +@_set_add.register(Basic, Basic) +def _(x, y): + return None + + +@_set_add.register(Expr, Expr) +def _(x, y): + return x+y + + +@_set_add.register(Interval, Interval) +def _(x, y): + """ + Additions in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + return Interval(x.start + y.start, x.end + y.end, + x.left_open or y.left_open, x.right_open or y.right_open) + + +@_set_add.register(Interval, Infinity) +def _(x, y): + if x.start is S.NegativeInfinity: + return Interval(-oo, oo) + return FiniteSet({S.Infinity}) + +@_set_add.register(Interval, NegativeInfinity) +def _(x, y): + if x.end is S.Infinity: + return Interval(-oo, oo) + return FiniteSet({S.NegativeInfinity}) + + +@_set_sub.register(Basic, Basic) +def _(x, y): + return None + + +@_set_sub.register(Expr, Expr) +def _(x, y): + return x-y + + +@_set_sub.register(Interval, Interval) +def _(x, y): + """ + Subtractions in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + return Interval(x.start - y.end, x.end - y.start, + x.left_open or y.right_open, x.right_open or y.left_open) + + +@_set_sub.register(Interval, Infinity) +def _(x, y): + if x.start is S.NegativeInfinity: + return Interval(-oo, oo) + return FiniteSet(-oo) + +@_set_sub.register(Interval, NegativeInfinity) +def _(x, y): + if x.start is S.NegativeInfinity: + return Interval(-oo, oo) + return FiniteSet(-oo) diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..b64d1a2a22e15d09f6f10fb4fef730163d468d45 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py @@ -0,0 +1,53 @@ +from sympy.core.relational import Eq, is_eq +from sympy.core.basic import Basic +from sympy.core.logic import fuzzy_and, fuzzy_bool +from sympy.logic.boolalg import And +from sympy.multipledispatch import dispatch +from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet, Set + + +@dispatch(Interval, FiniteSet) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return False + + +@dispatch(FiniteSet, Interval) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return False + + +@dispatch(Interval, Interval) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return And(Eq(lhs.left, rhs.left), + Eq(lhs.right, rhs.right), + lhs.left_open == rhs.left_open, + lhs.right_open == rhs.right_open) + +@dispatch(FiniteSet, FiniteSet) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + def all_in_both(): + s_set = set(lhs.args) + o_set = set(rhs.args) + yield fuzzy_and(lhs._contains(e) for e in o_set - s_set) + yield fuzzy_and(rhs._contains(e) for e in s_set - o_set) + + return tfn[fuzzy_and(all_in_both())] + + +@dispatch(ProductSet, ProductSet) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + if len(lhs.sets) != len(rhs.sets): + return False + + eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets)) + return tfn[fuzzy_and(map(fuzzy_bool, eqs))] + + +@dispatch(Set, Basic) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return False + + +@dispatch(Set, Set) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return tfn[fuzzy_and(a.is_subset(b) for a, b in [(lhs, rhs), (rhs, lhs)])] diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/functions.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..2529dbfd458451d7d09e91c717b170df77b1d9fe --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/functions.py @@ -0,0 +1,262 @@ +from sympy.core.singleton import S +from sympy.sets.sets import Set +from sympy.calculus.singularities import singularities +from sympy.core import Expr, Add +from sympy.core.function import Lambda, FunctionClass, diff, expand_mul +from sympy.core.numbers import Float, oo +from sympy.core.symbol import Dummy, symbols, Wild +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.logic.boolalg import true +from sympy.multipledispatch import Dispatcher +from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet, + Intersection, Range, Complement) +from sympy.sets.sets import EmptySet, is_function_invertible_in_set +from sympy.sets.fancysets import Integers, Naturals, Reals +from sympy.functions.elementary.exponential import match_real_imag + + +_x, _y = symbols("x y") + +FunctionUnion = (FunctionClass, Lambda) + +_set_function = Dispatcher('_set_function') + + +@_set_function.register(FunctionClass, Set) +def _(f, x): + return None + +@_set_function.register(FunctionUnion, FiniteSet) +def _(f, x): + return FiniteSet(*map(f, x)) + +@_set_function.register(Lambda, Interval) +def _(f, x): + from sympy.solvers.solveset import solveset + from sympy.series import limit + # TODO: handle functions with infinitely many solutions (eg, sin, tan) + # TODO: handle multivariate functions + + expr = f.expr + if len(expr.free_symbols) > 1 or len(f.variables) != 1: + return + var = f.variables[0] + if not var.is_real: + if expr.subs(var, Dummy(real=True)).is_real is False: + return + + if expr.is_Piecewise: + result = S.EmptySet + domain_set = x + for (p_expr, p_cond) in expr.args: + if p_cond is true: + intrvl = domain_set + else: + intrvl = p_cond.as_set() + intrvl = Intersection(domain_set, intrvl) + + if p_expr.is_Number: + image = FiniteSet(p_expr) + else: + image = imageset(Lambda(var, p_expr), intrvl) + result = Union(result, image) + + # remove the part which has been `imaged` + domain_set = Complement(domain_set, intrvl) + if domain_set is S.EmptySet: + break + return result + + if not x.start.is_comparable or not x.end.is_comparable: + return + + try: + from sympy.polys.polyutils import _nsort + sing = list(singularities(expr, var, x)) + if len(sing) > 1: + sing = _nsort(sing) + except NotImplementedError: + return + + if x.left_open: + _start = limit(expr, var, x.start, dir="+") + elif x.start not in sing: + _start = f(x.start) + if x.right_open: + _end = limit(expr, var, x.end, dir="-") + elif x.end not in sing: + _end = f(x.end) + + if len(sing) == 0: + soln_expr = solveset(diff(expr, var), var) + if not (isinstance(soln_expr, FiniteSet) + or soln_expr is S.EmptySet): + return + solns = list(soln_expr) + + extr = [_start, _end] + [f(i) for i in solns + if i.is_real and i in x] + start, end = Min(*extr), Max(*extr) + + left_open, right_open = False, False + if _start <= _end: + # the minimum or maximum value can occur simultaneously + # on both the edge of the interval and in some interior + # point + if start == _start and start not in solns: + left_open = x.left_open + if end == _end and end not in solns: + right_open = x.right_open + else: + if start == _end and start not in solns: + left_open = x.right_open + if end == _start and end not in solns: + right_open = x.left_open + + return Interval(start, end, left_open, right_open) + else: + return imageset(f, Interval(x.start, sing[0], + x.left_open, True)) + \ + Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True)) + for i in range(0, len(sing) - 1)]) + \ + imageset(f, Interval(sing[-1], x.end, True, x.right_open)) + +@_set_function.register(FunctionClass, Interval) +def _(f, x): + if f == exp: + return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open) + elif f == log: + return Interval(log(x.start), log(x.end), x.left_open, x.right_open) + return ImageSet(Lambda(_x, f(_x)), x) + +@_set_function.register(FunctionUnion, Union) +def _(f, x): + return Union(*(imageset(f, arg) for arg in x.args)) + +@_set_function.register(FunctionUnion, Intersection) +def _(f, x): + # If the function is invertible, intersect the maps of the sets. + if is_function_invertible_in_set(f, x): + return Intersection(*(imageset(f, arg) for arg in x.args)) + else: + return ImageSet(Lambda(_x, f(_x)), x) + +@_set_function.register(FunctionUnion, EmptySet) +def _(f, x): + return x + +@_set_function.register(FunctionUnion, Set) +def _(f, x): + return ImageSet(Lambda(_x, f(_x)), x) + +@_set_function.register(FunctionUnion, Range) +def _(f, self): + if not self: + return S.EmptySet + if not isinstance(f.expr, Expr): + return + if self.size == 1: + return FiniteSet(f(self[0])) + if f is S.IdentityFunction: + return self + + x = f.variables[0] + expr = f.expr + # handle f that is linear in f's variable + if x not in expr.free_symbols or x in expr.diff(x).free_symbols: + return + if self.start.is_finite: + F = f(self.step*x + self.start) # for i in range(len(self)) + else: + F = f(-self.step*x + self[-1]) + F = expand_mul(F) + if F != expr: + return imageset(x, F, Range(self.size)) + +@_set_function.register(FunctionUnion, Integers) +def _(f, self): + expr = f.expr + if not isinstance(expr, Expr): + return + + n = f.variables[0] + if expr == abs(n): + return S.Naturals0 + + # f(x) + c and f(-x) + c cover the same integers + # so choose the form that has the fewest negatives + c = f(0) + fx = f(n) - c + f_x = f(-n) - c + neg_count = lambda e: sum(_.could_extract_minus_sign() + for _ in Add.make_args(e)) + if neg_count(f_x) < neg_count(fx): + expr = f_x + c + + a = Wild('a', exclude=[n]) + b = Wild('b', exclude=[n]) + match = expr.match(a*n + b) + if match and match[a] and ( + not match[a].atoms(Float) and + not match[b].atoms(Float)): + # canonical shift + a, b = match[a], match[b] + if a in [1, -1]: + # drop integer addends in b + nonint = [] + for bi in Add.make_args(b): + if not bi.is_integer: + nonint.append(bi) + b = Add(*nonint) + if b.is_number and a.is_real: + # avoid Mod for complex numbers, #11391 + br, bi = match_real_imag(b) + if br and br.is_comparable and a.is_comparable: + br %= a + b = br + S.ImaginaryUnit*bi + elif b.is_number and a.is_imaginary: + br, bi = match_real_imag(b) + ai = a/S.ImaginaryUnit + if bi and bi.is_comparable and ai.is_comparable: + bi %= ai + b = br + S.ImaginaryUnit*bi + expr = a*n + b + + if expr != f.expr: + return ImageSet(Lambda(n, expr), S.Integers) + + +@_set_function.register(FunctionUnion, Naturals) +def _(f, self): + expr = f.expr + if not isinstance(expr, Expr): + return + + x = f.variables[0] + if not expr.free_symbols - {x}: + if expr == abs(x): + if self is S.Naturals: + return self + return S.Naturals0 + step = expr.coeff(x) + c = expr.subs(x, 0) + if c.is_Integer and step.is_Integer and expr == step*x + c: + if self is S.Naturals: + c += step + if step > 0: + if step == 1: + if c == 0: + return S.Naturals0 + elif c == 1: + return S.Naturals + return Range(c, oo, step) + return Range(c, -oo, step) + + +@_set_function.register(FunctionUnion, Reals) +def _(f, self): + expr = f.expr + if not isinstance(expr, Expr): + return + return _set_function(f, Interval(-oo, oo)) diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py new file mode 100644 index 0000000000000000000000000000000000000000..b2db3f6f0e26c9228f35e045993de09f7ffaaef2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py @@ -0,0 +1,514 @@ +from sympy.core.function import Lambda, expand_complex +from sympy.core.mul import Mul +from sympy.core.numbers import ilcm +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, symbols) +from sympy.core.sorting import ordered +from sympy.functions.elementary.complexes import sign +from sympy.functions.elementary.integers import floor, ceiling +from sympy.sets.fancysets import ComplexRegion +from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union) +from sympy.multipledispatch import Dispatcher +from sympy.sets.conditionset import ConditionSet +from sympy.sets.fancysets import (Integers, Naturals, Reals, Range, + ImageSet, Rationals) +from sympy.sets.sets import EmptySet, UniversalSet, imageset, ProductSet +from sympy.simplify.radsimp import numer + + +intersection_sets = Dispatcher('intersection_sets') + + +@intersection_sets.register(ConditionSet, ConditionSet) +def _(a, b): + return None + +@intersection_sets.register(ConditionSet, Set) +def _(a, b): + return ConditionSet(a.sym, a.condition, Intersection(a.base_set, b)) + +@intersection_sets.register(Naturals, Integers) +def _(a, b): + return a + +@intersection_sets.register(Naturals, Naturals) +def _(a, b): + return a if a is S.Naturals else b + +@intersection_sets.register(Interval, Naturals) +def _(a, b): + return intersection_sets(b, a) + +@intersection_sets.register(ComplexRegion, Set) +def _(self, other): + if other.is_ComplexRegion: + # self in rectangular form + if (not self.polar) and (not other.polar): + return ComplexRegion(Intersection(self.sets, other.sets)) + + # self in polar form + elif self.polar and other.polar: + r1, theta1 = self.a_interval, self.b_interval + r2, theta2 = other.a_interval, other.b_interval + new_r_interval = Intersection(r1, r2) + new_theta_interval = Intersection(theta1, theta2) + + # 0 and 2*Pi means the same + if ((2*S.Pi in theta1 and S.Zero in theta2) or + (2*S.Pi in theta2 and S.Zero in theta1)): + new_theta_interval = Union(new_theta_interval, + FiniteSet(0)) + return ComplexRegion(new_r_interval*new_theta_interval, + polar=True) + + + if other.is_subset(S.Reals): + new_interval = [] + x = symbols("x", cls=Dummy, real=True) + + # self in rectangular form + if not self.polar: + for element in self.psets: + if S.Zero in element.args[1]: + new_interval.append(element.args[0]) + new_interval = Union(*new_interval) + return Intersection(new_interval, other) + + # self in polar form + elif self.polar: + for element in self.psets: + if S.Zero in element.args[1]: + new_interval.append(element.args[0]) + if S.Pi in element.args[1]: + new_interval.append(ImageSet(Lambda(x, -x), element.args[0])) + if S.Zero in element.args[0]: + new_interval.append(FiniteSet(0)) + new_interval = Union(*new_interval) + return Intersection(new_interval, other) + +@intersection_sets.register(Integers, Reals) +def _(a, b): + return a + +@intersection_sets.register(Range, Interval) +def _(a, b): + # Check that there are no symbolic arguments + if not all(i.is_number for i in a.args + b.args[:2]): + return + + # In case of null Range, return an EmptySet. + if a.size == 0: + return S.EmptySet + + # trim down to self's size, and represent + # as a Range with step 1. + start = ceiling(max(b.inf, a.inf)) + if start not in b: + start += 1 + end = floor(min(b.sup, a.sup)) + if end not in b: + end -= 1 + return intersection_sets(a, Range(start, end + 1)) + +@intersection_sets.register(Range, Naturals) +def _(a, b): + return intersection_sets(a, Interval(b.inf, S.Infinity)) + +@intersection_sets.register(Range, Range) +def _(a, b): + # Check that there are no symbolic range arguments + if not all(all(v.is_number for v in r.args) for r in [a, b]): + return None + + # non-overlap quick exits + if not b: + return S.EmptySet + if not a: + return S.EmptySet + if b.sup < a.inf: + return S.EmptySet + if b.inf > a.sup: + return S.EmptySet + + # work with finite end at the start + r1 = a + if r1.start.is_infinite: + r1 = r1.reversed + r2 = b + if r2.start.is_infinite: + r2 = r2.reversed + + # If both ends are infinite then it means that one Range is just the set + # of all integers (the step must be 1). + if r1.start.is_infinite: + return b + if r2.start.is_infinite: + return a + + from sympy.solvers.diophantine.diophantine import diop_linear + + # this equation represents the values of the Range; + # it's a linear equation + eq = lambda r, i: r.start + i*r.step + + # we want to know when the two equations might + # have integer solutions so we use the diophantine + # solver + va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b'))) + + # check for no solution + no_solution = va is None and vb is None + if no_solution: + return S.EmptySet + + # there is a solution + # ------------------- + + # find the coincident point, c + a0 = va.as_coeff_Add()[0] + c = eq(r1, a0) + + # find the first point, if possible, in each range + # since c may not be that point + def _first_finite_point(r1, c): + if c == r1.start: + return c + # st is the signed step we need to take to + # get from c to r1.start + st = sign(r1.start - c)*step + # use Range to calculate the first point: + # we want to get as close as possible to + # r1.start; the Range will not be null since + # it will at least contain c + s1 = Range(c, r1.start + st, st)[-1] + if s1 == r1.start: + pass + else: + # if we didn't hit r1.start then, if the + # sign of st didn't match the sign of r1.step + # we are off by one and s1 is not in r1 + if sign(r1.step) != sign(st): + s1 -= st + if s1 not in r1: + return + return s1 + + # calculate the step size of the new Range + step = abs(ilcm(r1.step, r2.step)) + s1 = _first_finite_point(r1, c) + if s1 is None: + return S.EmptySet + s2 = _first_finite_point(r2, c) + if s2 is None: + return S.EmptySet + + # replace the corresponding start or stop in + # the original Ranges with these points; the + # result must have at least one point since + # we know that s1 and s2 are in the Ranges + def _updated_range(r, first): + st = sign(r.step)*step + if r.start.is_finite: + rv = Range(first, r.stop, st) + else: + rv = Range(r.start, first + st, st) + return rv + r1 = _updated_range(a, s1) + r2 = _updated_range(b, s2) + + # work with them both in the increasing direction + if sign(r1.step) < 0: + r1 = r1.reversed + if sign(r2.step) < 0: + r2 = r2.reversed + + # return clipped Range with positive step; it + # can't be empty at this point + start = max(r1.start, r2.start) + stop = min(r1.stop, r2.stop) + return Range(start, stop, step) + + +@intersection_sets.register(Range, Integers) +def _(a, b): + return a + + +@intersection_sets.register(Range, Rationals) +def _(a, b): + return a + + +@intersection_sets.register(ImageSet, Set) +def _(self, other): + from sympy.solvers.diophantine import diophantine + + # Only handle the straight-forward univariate case + if (len(self.lamda.variables) > 1 + or self.lamda.signature != self.lamda.variables): + return None + base_set = self.base_sets[0] + + # Intersection between ImageSets with Integers as base set + # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the + # diophantine equations f(n)=g(m). + # If the solutions for n are {h(t) : t in Integers} then we return + # {f(h(t)) : t in integers}. + # If the solutions for n are {n_1, n_2, ..., n_k} then we return + # {f(n_i) : 1 <= i <= k}. + if base_set is S.Integers: + gm = None + if isinstance(other, ImageSet) and other.base_sets == (S.Integers,): + gm = other.lamda.expr + var = other.lamda.variables[0] + # Symbol of second ImageSet lambda must be distinct from first + m = Dummy('m') + gm = gm.subs(var, m) + elif other is S.Integers: + m = gm = Dummy('m') + if gm is not None: + fn = self.lamda.expr + n = self.lamda.variables[0] + try: + solns = list(diophantine(fn - gm, syms=(n, m), permute=True)) + except (TypeError, NotImplementedError): + # TypeError if equation not polynomial with rational coeff. + # NotImplementedError if correct format but no solver. + return + # 3 cases are possible for solns: + # - empty set, + # - one or more parametric (infinite) solutions, + # - a finite number of (non-parametric) solution couples. + # Among those, there is one type of solution set that is + # not helpful here: multiple parametric solutions. + if len(solns) == 0: + return S.EmptySet + elif any(s.free_symbols for tupl in solns for s in tupl): + if len(solns) == 1: + soln, solm = solns[0] + (t,) = soln.free_symbols + expr = fn.subs(n, soln.subs(t, n)).expand() + return imageset(Lambda(n, expr), S.Integers) + else: + return + else: + return FiniteSet(*(fn.subs(n, s[0]) for s in solns)) + + if other == S.Reals: + from sympy.solvers.solvers import denoms, solve_linear + + def _solution_union(exprs, sym): + # return a union of linear solutions to i in expr; + # if i cannot be solved, use a ConditionSet for solution + sols = [] + for i in exprs: + x, xis = solve_linear(i, 0, [sym]) + if x == sym: + sols.append(FiniteSet(xis)) + else: + sols.append(ConditionSet(sym, Eq(i, 0))) + return Union(*sols) + + f = self.lamda.expr + n = self.lamda.variables[0] + + n_ = Dummy(n.name, real=True) + f_ = f.subs(n, n_) + + re, im = f_.as_real_imag() + im = expand_complex(im) + + re = re.subs(n_, n) + im = im.subs(n_, n) + ifree = im.free_symbols + lam = Lambda(n, re) + if im.is_zero: + # allow re-evaluation + # of self in this case to make + # the result canonical + pass + elif im.is_zero is False: + return S.EmptySet + elif ifree != {n}: + return None + else: + # univarite imaginary part in same variable; + # use numer instead of as_numer_denom to keep + # this as fast as possible while still handling + # simple cases + base_set &= _solution_union( + Mul.make_args(numer(im)), n) + # exclude values that make denominators 0 + base_set -= _solution_union(denoms(f), n) + return imageset(lam, base_set) + + elif isinstance(other, Interval): + from sympy.solvers.solveset import (invert_real, invert_complex, + solveset) + + f = self.lamda.expr + n = self.lamda.variables[0] + new_inf, new_sup = None, None + new_lopen, new_ropen = other.left_open, other.right_open + + if f.is_real: + inverter = invert_real + else: + inverter = invert_complex + + g1, h1 = inverter(f, other.inf, n) + g2, h2 = inverter(f, other.sup, n) + + if all(isinstance(i, FiniteSet) for i in (h1, h2)): + if g1 == n: + if len(h1) == 1: + new_inf = h1.args[0] + if g2 == n: + if len(h2) == 1: + new_sup = h2.args[0] + # TODO: Design a technique to handle multiple-inverse + # functions + + # Any of the new boundary values cannot be determined + if any(i is None for i in (new_sup, new_inf)): + return + + + range_set = S.EmptySet + + if all(i.is_real for i in (new_sup, new_inf)): + # this assumes continuity of underlying function + # however fixes the case when it is decreasing + if new_inf > new_sup: + new_inf, new_sup = new_sup, new_inf + new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen) + range_set = base_set.intersect(new_interval) + else: + if other.is_subset(S.Reals): + solutions = solveset(f, n, S.Reals) + if not isinstance(range_set, (ImageSet, ConditionSet)): + range_set = solutions.intersect(other) + else: + return + + if range_set is S.EmptySet: + return S.EmptySet + elif isinstance(range_set, Range) and range_set.size is not S.Infinity: + range_set = FiniteSet(*list(range_set)) + + if range_set is not None: + return imageset(Lambda(n, f), range_set) + return + else: + return + + +@intersection_sets.register(ProductSet, ProductSet) +def _(a, b): + if len(b.args) != len(a.args): + return S.EmptySet + return ProductSet(*(i.intersect(j) for i, j in zip(a.sets, b.sets))) + + +@intersection_sets.register(Interval, Interval) +def _(a, b): + # handle (-oo, oo) + infty = S.NegativeInfinity, S.Infinity + if a == Interval(*infty): + l, r = a.left, a.right + if l.is_real or l in infty or r.is_real or r in infty: + return b + + # We can't intersect [0,3] with [x,6] -- we don't know if x>0 or x<0 + if not a._is_comparable(b): + return None + + empty = False + + if a.start <= b.end and b.start <= a.end: + # Get topology right. + if a.start < b.start: + start = b.start + left_open = b.left_open + elif a.start > b.start: + start = a.start + left_open = a.left_open + else: + #this is to ensure that if Eq(a.start,b.start) but + #type(a.start) != type(b.start) the order of a and b + #does not matter for the result + start = list(ordered([a,b]))[0].start + left_open = a.left_open or b.left_open + + if a.end < b.end: + end = a.end + right_open = a.right_open + elif a.end > b.end: + end = b.end + right_open = b.right_open + else: + end = list(ordered([a,b]))[0].end + right_open = a.right_open or b.right_open + + if end - start == 0 and (left_open or right_open): + empty = True + else: + empty = True + + if empty: + return S.EmptySet + + return Interval(start, end, left_open, right_open) + +@intersection_sets.register(EmptySet, Set) +def _(a, b): + return S.EmptySet + +@intersection_sets.register(UniversalSet, Set) +def _(a, b): + return b + +@intersection_sets.register(FiniteSet, FiniteSet) +def _(a, b): + return FiniteSet(*(a._elements & b._elements)) + +@intersection_sets.register(FiniteSet, Set) +def _(a, b): + try: + return FiniteSet(*[el for el in a if el in b]) + except TypeError: + return None # could not evaluate `el in b` due to symbolic ranges. + +@intersection_sets.register(Set, Set) +def _(a, b): + return None + +@intersection_sets.register(Integers, Rationals) +def _(a, b): + return a + +@intersection_sets.register(Naturals, Rationals) +def _(a, b): + return a + +@intersection_sets.register(Rationals, Reals) +def _(a, b): + return a + +def _intlike_interval(a, b): + try: + if b._inf is S.NegativeInfinity and b._sup is S.Infinity: + return a + s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1) + return intersection_sets(s, b) # take out endpoints if open interval + except ValueError: + return None + +@intersection_sets.register(Integers, Interval) +def _(a, b): + return _intlike_interval(a, b) + +@intersection_sets.register(Naturals, Interval) +def _(a, b): + return _intlike_interval(a, b) diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py new file mode 100644 index 0000000000000000000000000000000000000000..cc23e8bf56f1743cd7f08452dd09a0acf981f5da --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py @@ -0,0 +1,144 @@ +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or +from sympy.core.relational import Eq +from sympy.sets.sets import FiniteSet, Interval, Set, Union, ProductSet +from sympy.sets.fancysets import Complexes, Reals, Range, Rationals +from sympy.multipledispatch import Dispatcher + + +_inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes] + + +is_subset_sets = Dispatcher('is_subset_sets') + + +@is_subset_sets.register(Set, Set) +def _(a, b): + return None + +@is_subset_sets.register(Interval, Interval) +def _(a, b): + # This is correct but can be made more comprehensive... + if fuzzy_bool(a.start < b.start): + return False + if fuzzy_bool(a.end > b.end): + return False + if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))): + return False + if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))): + return False + +@is_subset_sets.register(Interval, FiniteSet) +def _(a_interval, b_fs): + # An Interval can only be a subset of a finite set if it is finite + # which can only happen if it has zero measure. + if fuzzy_not(a_interval.measure.is_zero): + return False + +@is_subset_sets.register(Interval, Union) +def _(a_interval, b_u): + if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args): + intervals = [s for s in b_u.args if isinstance(s, Interval)] + if all(fuzzy_bool(a_interval.start < s.start) for s in intervals): + return False + if all(fuzzy_bool(a_interval.end > s.end) for s in intervals): + return False + if a_interval.measure.is_nonzero: + no_overlap = lambda s1, s2: fuzzy_or([ + fuzzy_bool(s1.end <= s2.start), + fuzzy_bool(s1.start >= s2.end), + ]) + if all(no_overlap(s, a_interval) for s in intervals): + return False + +@is_subset_sets.register(Range, Range) +def _(a, b): + if a.step == b.step == 1: + return fuzzy_and([fuzzy_bool(a.start >= b.start), + fuzzy_bool(a.stop <= b.stop)]) + +@is_subset_sets.register(Range, Interval) +def _(a_range, b_interval): + if a_range.step.is_positive: + if b_interval.left_open and a_range.inf.is_finite: + cond_left = a_range.inf > b_interval.left + else: + cond_left = a_range.inf >= b_interval.left + if b_interval.right_open and a_range.sup.is_finite: + cond_right = a_range.sup < b_interval.right + else: + cond_right = a_range.sup <= b_interval.right + return fuzzy_and([cond_left, cond_right]) + +@is_subset_sets.register(Range, FiniteSet) +def _(a_range, b_finiteset): + try: + a_size = a_range.size + except ValueError: + # symbolic Range of unknown size + return None + if a_size > len(b_finiteset): + return False + elif any(arg.has(Symbol) for arg in a_range.args): + return fuzzy_and(b_finiteset.contains(x) for x in a_range) + else: + # Checking A \ B == EmptySet is more efficient than repeated naive + # membership checks on an arbitrary FiniteSet. + a_set = set(a_range) + b_remaining = len(b_finiteset) + # Symbolic expressions and numbers of unknown type (integer or not) are + # all counted as "candidates", i.e. *potentially* matching some a in + # a_range. + cnt_candidate = 0 + for b in b_finiteset: + if b.is_Integer: + a_set.discard(b) + elif fuzzy_not(b.is_integer): + pass + else: + cnt_candidate += 1 + b_remaining -= 1 + if len(a_set) > b_remaining + cnt_candidate: + return False + if len(a_set) == 0: + return True + return None + +@is_subset_sets.register(Interval, Range) +def _(a_interval, b_range): + if a_interval.measure.is_extended_nonzero: + return False + +@is_subset_sets.register(Interval, Rationals) +def _(a_interval, b_rationals): + if a_interval.measure.is_extended_nonzero: + return False + +@is_subset_sets.register(Range, Complexes) +def _(a, b): + return True + +@is_subset_sets.register(Complexes, Interval) +def _(a, b): + return False + +@is_subset_sets.register(Complexes, Range) +def _(a, b): + return False + +@is_subset_sets.register(Complexes, Rationals) +def _(a, b): + return False + +@is_subset_sets.register(Rationals, Reals) +def _(a, b): + return True + +@is_subset_sets.register(Rationals, Range) +def _(a, b): + return False + +@is_subset_sets.register(ProductSet, FiniteSet) +def _(a_ps, b_fs): + return fuzzy_and(b_fs.contains(x) for x in a_ps) diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/mul.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/mul.py new file mode 100644 index 0000000000000000000000000000000000000000..0dedc8068b7973fd4cb6fbf2854e5fa671d188de --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/mul.py @@ -0,0 +1,79 @@ +from sympy.core import Basic, Expr +from sympy.core.numbers import oo +from sympy.core.symbol import symbols +from sympy.multipledispatch import Dispatcher +from sympy.sets.setexpr import set_mul +from sympy.sets.sets import Interval, Set + + +_x, _y = symbols("x y") + + +_set_mul = Dispatcher('_set_mul') +_set_div = Dispatcher('_set_div') + + +@_set_mul.register(Basic, Basic) +def _(x, y): + return None + +@_set_mul.register(Set, Set) +def _(x, y): + return None + +@_set_mul.register(Expr, Expr) +def _(x, y): + return x*y + +@_set_mul.register(Interval, Interval) +def _(x, y): + """ + Multiplications in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + # TODO: some intervals containing 0 and oo will fail as 0*oo returns nan. + comvals = ( + (x.start * y.start, bool(x.left_open or y.left_open)), + (x.start * y.end, bool(x.left_open or y.right_open)), + (x.end * y.start, bool(x.right_open or y.left_open)), + (x.end * y.end, bool(x.right_open or y.right_open)), + ) + # TODO: handle symbolic intervals + minval, minopen = min(comvals) + maxval, maxopen = max(comvals) + return Interval( + minval, + maxval, + minopen, + maxopen + ) + +@_set_div.register(Basic, Basic) +def _(x, y): + return None + +@_set_div.register(Expr, Expr) +def _(x, y): + return x/y + +@_set_div.register(Set, Set) +def _(x, y): + return None + +@_set_div.register(Interval, Interval) +def _(x, y): + """ + Divisions in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + if (y.start*y.end).is_negative: + return Interval(-oo, oo) + if y.start == 0: + s2 = oo + else: + s2 = 1/y.start + if y.end == 0: + s1 = -oo + else: + s1 = 1/y.end + return set_mul(x, Interval(s1, s2, y.right_open, y.left_open)) diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/power.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/power.py new file mode 100644 index 0000000000000000000000000000000000000000..3cad4ee49ab27770143bc121d1fbcd024bf01548 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/power.py @@ -0,0 +1,107 @@ +from sympy.core import Basic, Expr +from sympy.core.function import Lambda +from sympy.core.numbers import oo, Infinity, NegativeInfinity, Zero, Integer +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import (Max, Min) +from sympy.sets.fancysets import ImageSet +from sympy.sets.setexpr import set_div +from sympy.sets.sets import Set, Interval, FiniteSet, Union +from sympy.multipledispatch import Dispatcher + + +_x, _y = symbols("x y") + + +_set_pow = Dispatcher('_set_pow') + + +@_set_pow.register(Basic, Basic) +def _(x, y): + return None + +@_set_pow.register(Set, Set) +def _(x, y): + return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y) + +@_set_pow.register(Expr, Expr) +def _(x, y): + return x**y + +@_set_pow.register(Interval, Zero) +def _(x, z): + return FiniteSet(S.One) + +@_set_pow.register(Interval, Integer) +def _(x, exponent): + """ + Powers in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + s1 = x.start**exponent + s2 = x.end**exponent + if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True: + left_open = x.left_open + right_open = x.right_open + # TODO: handle unevaluated condition. + sleft = s2 + else: + # TODO: `s2 > s1` could be unevaluated. + left_open = x.right_open + right_open = x.left_open + sleft = s1 + + if x.start.is_positive: + return Interval( + Min(s1, s2), + Max(s1, s2), left_open, right_open) + elif x.end.is_negative: + return Interval( + Min(s1, s2), + Max(s1, s2), left_open, right_open) + + # Case where x.start < 0 and x.end > 0: + if exponent.is_odd: + if exponent.is_negative: + if x.start.is_zero: + return Interval(s2, oo, x.right_open) + if x.end.is_zero: + return Interval(-oo, s1, True, x.left_open) + return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open)) + else: + return Interval(s1, s2, x.left_open, x.right_open) + elif exponent.is_even: + if exponent.is_negative: + if x.start.is_zero: + return Interval(s2, oo, x.right_open) + if x.end.is_zero: + return Interval(s1, oo, x.left_open) + return Interval(0, oo) + else: + return Interval(S.Zero, sleft, S.Zero not in x, left_open) + +@_set_pow.register(Interval, Infinity) +def _(b, e): + # TODO: add logic for open intervals? + if b.start.is_nonnegative: + if b.end < 1: + return FiniteSet(S.Zero) + if b.start > 1: + return FiniteSet(S.Infinity) + return Interval(0, oo) + elif b.end.is_negative: + if b.start > -1: + return FiniteSet(S.Zero) + if b.end < -1: + return FiniteSet(-oo, oo) + return Interval(-oo, oo) + else: + if b.start > -1: + if b.end < 1: + return FiniteSet(S.Zero) + return Interval(0, oo) + return Interval(-oo, oo) + +@_set_pow.register(Interval, NegativeInfinity) +def _(b, e): + return _set_pow(set_div(S.One, b), oo) diff --git a/venv/lib/python3.10/site-packages/sympy/sets/handlers/union.py b/venv/lib/python3.10/site-packages/sympy/sets/handlers/union.py new file mode 100644 index 0000000000000000000000000000000000000000..75d867b49969ae2aeea76155dbaae7e05c1a6847 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/sets/handlers/union.py @@ -0,0 +1,147 @@ +from sympy.core.singleton import S +from sympy.core.sympify import sympify +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.sets.sets import (EmptySet, FiniteSet, Intersection, + Interval, ProductSet, Set, Union, UniversalSet) +from sympy.sets.fancysets import (ComplexRegion, Naturals, Naturals0, + Integers, Rationals, Reals) +from sympy.multipledispatch import Dispatcher + + +union_sets = Dispatcher('union_sets') + + +@union_sets.register(Naturals0, Naturals) +def _(a, b): + return a + +@union_sets.register(Rationals, Naturals) +def _(a, b): + return a + +@union_sets.register(Rationals, Naturals0) +def _(a, b): + return a + +@union_sets.register(Reals, Naturals) +def _(a, b): + return a + +@union_sets.register(Reals, Naturals0) +def _(a, b): + return a + +@union_sets.register(Reals, Rationals) +def _(a, b): + return a + +@union_sets.register(Integers, Set) +def _(a, b): + intersect = Intersection(a, b) + if intersect == a: + return b + elif intersect == b: + return a + +@union_sets.register(ComplexRegion, Set) +def _(a, b): + if b.is_subset(S.Reals): + # treat a subset of reals as a complex region + b = ComplexRegion.from_real(b) + + if b.is_ComplexRegion: + # a in rectangular form + if (not a.polar) and (not b.polar): + return ComplexRegion(Union(a.sets, b.sets)) + # a in polar form + elif a.polar and b.polar: + return ComplexRegion(Union(a.sets, b.sets), polar=True) + return None + +@union_sets.register(EmptySet, Set) +def _(a, b): + return b + + +@union_sets.register(UniversalSet, Set) +def _(a, b): + return a + +@union_sets.register(ProductSet, ProductSet) +def _(a, b): + if b.is_subset(a): + return a + if len(b.sets) != len(a.sets): + return None + if len(a.sets) == 2: + a1, a2 = a.sets + b1, b2 = b.sets + if a1 == b1: + return a1 * Union(a2, b2) + if a2 == b2: + return Union(a1, b1) * a2 + return None + +@union_sets.register(ProductSet, Set) +def _(a, b): + if b.is_subset(a): + return a + return None + +@union_sets.register(Interval, Interval) +def _(a, b): + if a._is_comparable(b): + # Non-overlapping intervals + end = Min(a.end, b.end) + start = Max(a.start, b.start) + if (end < start or + (end == start and (end not in a and end not in b))): + return None + else: + start = Min(a.start, b.start) + end = Max(a.end, b.end) + + left_open = ((a.start != start or a.left_open) and + (b.start != start or b.left_open)) + right_open = ((a.end != end or a.right_open) and + (b.end != end or b.right_open)) + return Interval(start, end, left_open, right_open) + +@union_sets.register(Interval, UniversalSet) +def _(a, b): + return S.UniversalSet + +@union_sets.register(Interval, Set) +def _(a, b): + # If I have open end points and these endpoints are contained in b + # But only in case, when endpoints are finite. Because + # interval does not contain oo or -oo. + open_left_in_b_and_finite = (a.left_open and + sympify(b.contains(a.start)) is S.true and + a.start.is_finite) + open_right_in_b_and_finite = (a.right_open and + sympify(b.contains(a.end)) is S.true and + a.end.is_finite) + if open_left_in_b_and_finite or open_right_in_b_and_finite: + # Fill in my end points and return + open_left = a.left_open and a.start not in b + open_right = a.right_open and a.end not in b + new_a = Interval(a.start, a.end, open_left, open_right) + return {new_a, b} + return None + +@union_sets.register(FiniteSet, FiniteSet) +def _(a, b): + return FiniteSet(*(a._elements | b._elements)) + +@union_sets.register(FiniteSet, Set) +def _(a, b): + # If `b` set contains one of my elements, remove it from `a` + if any(b.contains(x) == True for x in a): + return { + FiniteSet(*[x for x in a if b.contains(x) != True]), b} + return None + +@union_sets.register(Set, Set) +def _(a, b): + return None diff --git a/venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..195947e88f9b49fb69e64c4617d905aa283e4aef Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68e7dadd5b6cb6ab77d2c66d24a7da28fa56b6af Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/__init__.py b/venv/lib/python3.10/site-packages/sympy/strategies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4c5aa8afe6fd818e136ec0797b7429e2da76cf --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/__init__.py @@ -0,0 +1,50 @@ +""" Rewrite Rules + +DISCLAIMER: This module is experimental. The interface is subject to change. + +A rule is a function that transforms one expression into another + + Rule :: Expr -> Expr + +A strategy is a function that says how a rule should be applied to a syntax +tree. In general strategies take rules and produce a new rule + + Strategy :: [Rules], Other-stuff -> Rule + +This allows developers to separate a mathematical transformation from the +algorithmic details of applying that transformation. The goal is to separate +the work of mathematical programming from algorithmic programming. + +Submodules + +strategies.rl - some fundamental rules +strategies.core - generic non-SymPy specific strategies +strategies.traverse - strategies that traverse a SymPy tree +strategies.tools - some conglomerate strategies that do depend on SymPy +""" + +from . import rl +from . import traverse +from .rl import rm_id, unpack, flatten, sort, glom, distribute, rebuild +from .util import new +from .core import ( + condition, debug, chain, null_safe, do_one, exhaust, minimize, tryit) +from .tools import canon, typed +from . import branch + +__all__ = [ + 'rl', + + 'traverse', + + 'rm_id', 'unpack', 'flatten', 'sort', 'glom', 'distribute', 'rebuild', + + 'new', + + 'condition', 'debug', 'chain', 'null_safe', 'do_one', 'exhaust', + 'minimize', 'tryit', + + 'canon', 'typed', + + 'branch', +] diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/core.py b/venv/lib/python3.10/site-packages/sympy/strategies/core.py new file mode 100644 index 0000000000000000000000000000000000000000..75b75cb5f2e0693eea98a7b1c9b3e7f036ec26f6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/core.py @@ -0,0 +1,151 @@ +""" Generic SymPy-Independent Strategies """ +from __future__ import annotations +from collections.abc import Callable, Mapping +from typing import TypeVar +from sys import stdout + + +_S = TypeVar('_S') +_T = TypeVar('_T') + + +def identity(x: _T) -> _T: + return x + + +def exhaust(rule: Callable[[_T], _T]) -> Callable[[_T], _T]: + """ Apply a rule repeatedly until it has no effect """ + def exhaustive_rl(expr: _T) -> _T: + new, old = rule(expr), expr + while new != old: + new, old = rule(new), new + return new + return exhaustive_rl + + +def memoize(rule: Callable[[_S], _T]) -> Callable[[_S], _T]: + """Memoized version of a rule + + Notes + ===== + + This cache can grow infinitely, so it is not recommended to use this + than ``functools.lru_cache`` unless you need very heavy computation. + """ + cache: dict[_S, _T] = {} + + def memoized_rl(expr: _S) -> _T: + if expr in cache: + return cache[expr] + else: + result = rule(expr) + cache[expr] = result + return result + return memoized_rl + + +def condition( + cond: Callable[[_T], bool], rule: Callable[[_T], _T] +) -> Callable[[_T], _T]: + """ Only apply rule if condition is true """ + def conditioned_rl(expr: _T) -> _T: + if cond(expr): + return rule(expr) + return expr + return conditioned_rl + + +def chain(*rules: Callable[[_T], _T]) -> Callable[[_T], _T]: + """ + Compose a sequence of rules so that they apply to the expr sequentially + """ + def chain_rl(expr: _T) -> _T: + for rule in rules: + expr = rule(expr) + return expr + return chain_rl + + +def debug(rule, file=None): + """ Print out before and after expressions each time rule is used """ + if file is None: + file = stdout + + def debug_rl(*args, **kwargs): + expr = args[0] + result = rule(*args, **kwargs) + if result != expr: + file.write("Rule: %s\n" % rule.__name__) + file.write("In: %s\nOut: %s\n\n" % (expr, result)) + return result + return debug_rl + + +def null_safe(rule: Callable[[_T], _T | None]) -> Callable[[_T], _T]: + """ Return original expr if rule returns None """ + def null_safe_rl(expr: _T) -> _T: + result = rule(expr) + if result is None: + return expr + return result + return null_safe_rl + + +def tryit(rule: Callable[[_T], _T], exception) -> Callable[[_T], _T]: + """ Return original expr if rule raises exception """ + def try_rl(expr: _T) -> _T: + try: + return rule(expr) + except exception: + return expr + return try_rl + + +def do_one(*rules: Callable[[_T], _T]) -> Callable[[_T], _T]: + """ Try each of the rules until one works. Then stop. """ + def do_one_rl(expr: _T) -> _T: + for rl in rules: + result = rl(expr) + if result != expr: + return result + return expr + return do_one_rl + + +def switch( + key: Callable[[_S], _T], + ruledict: Mapping[_T, Callable[[_S], _S]] +) -> Callable[[_S], _S]: + """ Select a rule based on the result of key called on the function """ + def switch_rl(expr: _S) -> _S: + rl = ruledict.get(key(expr), identity) + return rl(expr) + return switch_rl + + +# XXX Untyped default argument for minimize function +# where python requires SupportsRichComparison type +def _identity(x): + return x + + +def minimize( + *rules: Callable[[_S], _T], + objective=_identity +) -> Callable[[_S], _T]: + """ Select result of rules that minimizes objective + + >>> from sympy.strategies import minimize + >>> inc = lambda x: x + 1 + >>> dec = lambda x: x - 1 + >>> rl = minimize(inc, dec) + >>> rl(4) + 3 + + >>> rl = minimize(inc, dec, objective=lambda x: -x) # maximize + >>> rl(4) + 5 + """ + def minrule(expr: _S) -> _T: + return min([rule(expr) for rule in rules], key=objective) + return minrule diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/rl.py b/venv/lib/python3.10/site-packages/sympy/strategies/rl.py new file mode 100644 index 0000000000000000000000000000000000000000..c002f8b9aeb73015c1246b44ab0c11710c4d5a72 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/rl.py @@ -0,0 +1,176 @@ +""" Generic Rules for SymPy + +This file assumes knowledge of Basic and little else. +""" +from sympy.utilities.iterables import sift +from .util import new + + +# Functions that create rules +def rm_id(isid, new=new): + """ Create a rule to remove identities. + + isid - fn :: x -> Bool --- whether or not this element is an identity. + + Examples + ======== + + >>> from sympy.strategies import rm_id + >>> from sympy import Basic, S + >>> remove_zeros = rm_id(lambda x: x==0) + >>> remove_zeros(Basic(S(1), S(0), S(2))) + Basic(1, 2) + >>> remove_zeros(Basic(S(0), S(0))) # If only identites then we keep one + Basic(0) + + See Also: + unpack + """ + def ident_remove(expr): + """ Remove identities """ + ids = list(map(isid, expr.args)) + if sum(ids) == 0: # No identities. Common case + return expr + elif sum(ids) != len(ids): # there is at least one non-identity + return new(expr.__class__, + *[arg for arg, x in zip(expr.args, ids) if not x]) + else: + return new(expr.__class__, expr.args[0]) + + return ident_remove + + +def glom(key, count, combine): + """ Create a rule to conglomerate identical args. + + Examples + ======== + + >>> from sympy.strategies import glom + >>> from sympy import Add + >>> from sympy.abc import x + + >>> key = lambda x: x.as_coeff_Mul()[1] + >>> count = lambda x: x.as_coeff_Mul()[0] + >>> combine = lambda cnt, arg: cnt * arg + >>> rl = glom(key, count, combine) + + >>> rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) + 3*x + 5 + + Wait, how are key, count and combine supposed to work? + + >>> key(2*x) + x + >>> count(2*x) + 2 + >>> combine(2, x) + 2*x + """ + def conglomerate(expr): + """ Conglomerate together identical args x + x -> 2x """ + groups = sift(expr.args, key) + counts = {k: sum(map(count, args)) for k, args in groups.items()} + newargs = [combine(cnt, mat) for mat, cnt in counts.items()] + if set(newargs) != set(expr.args): + return new(type(expr), *newargs) + else: + return expr + + return conglomerate + + +def sort(key, new=new): + """ Create a rule to sort by a key function. + + Examples + ======== + + >>> from sympy.strategies import sort + >>> from sympy import Basic, S + >>> sort_rl = sort(str) + >>> sort_rl(Basic(S(3), S(1), S(2))) + Basic(1, 2, 3) + """ + + def sort_rl(expr): + return new(expr.__class__, *sorted(expr.args, key=key)) + return sort_rl + + +def distribute(A, B): + """ Turns an A containing Bs into a B of As + + where A, B are container types + + >>> from sympy.strategies import distribute + >>> from sympy import Add, Mul, symbols + >>> x, y = symbols('x,y') + >>> dist = distribute(Mul, Add) + >>> expr = Mul(2, x+y, evaluate=False) + >>> expr + 2*(x + y) + >>> dist(expr) + 2*x + 2*y + """ + + def distribute_rl(expr): + for i, arg in enumerate(expr.args): + if isinstance(arg, B): + first, b, tail = expr.args[:i], expr.args[i], expr.args[i + 1:] + return B(*[A(*(first + (arg,) + tail)) for arg in b.args]) + return expr + return distribute_rl + + +def subs(a, b): + """ Replace expressions exactly """ + def subs_rl(expr): + if expr == a: + return b + else: + return expr + return subs_rl + + +# Functions that are rules +def unpack(expr): + """ Rule to unpack singleton args + + >>> from sympy.strategies import unpack + >>> from sympy import Basic, S + >>> unpack(Basic(S(2))) + 2 + """ + if len(expr.args) == 1: + return expr.args[0] + else: + return expr + + +def flatten(expr, new=new): + """ Flatten T(a, b, T(c, d), T2(e)) to T(a, b, c, d, T2(e)) """ + cls = expr.__class__ + args = [] + for arg in expr.args: + if arg.__class__ == cls: + args.extend(arg.args) + else: + args.append(arg) + return new(expr.__class__, *args) + + +def rebuild(expr): + """ Rebuild a SymPy tree. + + Explanation + =========== + + This function recursively calls constructors in the expression tree. + This forces canonicalization and removes ugliness introduced by the use of + Basic.__new__ + """ + if expr.is_Atom: + return expr + else: + return expr.func(*list(map(rebuild, expr.args))) diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/tests/test_tools.py b/venv/lib/python3.10/site-packages/sympy/strategies/tests/test_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..89774aeb92ead5781966e4f48ad32dc63e1bf7e2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/tests/test_tools.py @@ -0,0 +1,32 @@ +from sympy.strategies.tools import subs, typed +from sympy.strategies.rl import rm_id +from sympy.core.basic import Basic +from sympy.core.singleton import S + + +def test_subs(): + from sympy.core.symbol import symbols + a, b, c, d, e, f = symbols('a,b,c,d,e,f') + mapping = {a: d, d: a, Basic(e): Basic(f)} + expr = Basic(a, Basic(b, c), Basic(d, Basic(e))) + result = Basic(d, Basic(b, c), Basic(a, Basic(f))) + assert subs(mapping)(expr) == result + + +def test_subs_empty(): + assert subs({})(Basic(S(1), S(2))) == Basic(S(1), S(2)) + + +def test_typed(): + class A(Basic): + pass + + class B(Basic): + pass + + rmzeros = rm_id(lambda x: x == S(0)) + rmones = rm_id(lambda x: x == S(1)) + remove_something = typed({A: rmzeros, B: rmones}) + + assert remove_something(A(S(0), S(1))) == A(S(1)) + assert remove_something(B(S(0), S(1))) == B(S(0)) diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/tests/test_tree.py b/venv/lib/python3.10/site-packages/sympy/strategies/tests/test_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..d5cdde747fe3ab90c8fd181701194403bc526067 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/tests/test_tree.py @@ -0,0 +1,92 @@ +from sympy.strategies.tree import treeapply, greedy, allresults, brute +from functools import partial, reduce + + +def inc(x): + return x + 1 + + +def dec(x): + return x - 1 + + +def double(x): + return 2 * x + + +def square(x): + return x**2 + + +def add(*args): + return sum(args) + + +def mul(*args): + return reduce(lambda a, b: a * b, args, 1) + + +def test_treeapply(): + tree = ([3, 3], [4, 1], 2) + assert treeapply(tree, {list: min, tuple: max}) == 3 + assert treeapply(tree, {list: add, tuple: mul}) == 60 + + +def test_treeapply_leaf(): + assert treeapply(3, {}, leaf=lambda x: x**2) == 9 + tree = ([3, 3], [4, 1], 2) + treep1 = ([4, 4], [5, 2], 3) + assert treeapply(tree, {list: min, tuple: max}, leaf=lambda x: x + 1) == \ + treeapply(treep1, {list: min, tuple: max}) + + +def test_treeapply_strategies(): + from sympy.strategies import chain, minimize + join = {list: chain, tuple: minimize} + + assert treeapply(inc, join) == inc + assert treeapply((inc, dec), join)(5) == minimize(inc, dec)(5) + assert treeapply([inc, dec], join)(5) == chain(inc, dec)(5) + tree = (inc, [dec, double]) # either inc or dec-then-double + assert treeapply(tree, join)(5) == 6 + assert treeapply(tree, join)(1) == 0 + + maximize = partial(minimize, objective=lambda x: -x) + join = {list: chain, tuple: maximize} + fn = treeapply(tree, join) + assert fn(4) == 6 # highest value comes from the dec then double + assert fn(1) == 2 # highest value comes from the inc + + +def test_greedy(): + tree = [inc, (dec, double)] # either inc or dec-then-double + + fn = greedy(tree, objective=lambda x: -x) + assert fn(4) == 6 # highest value comes from the dec then double + assert fn(1) == 2 # highest value comes from the inc + + tree = [inc, dec, [inc, dec, [(inc, inc), (dec, dec)]]] + lowest = greedy(tree) + assert lowest(10) == 8 + + highest = greedy(tree, objective=lambda x: -x) + assert highest(10) == 12 + + +def test_allresults(): + # square = lambda x: x**2 + + assert set(allresults(inc)(3)) == {inc(3)} + assert set(allresults([inc, dec])(3)) == {2, 4} + assert set(allresults((inc, dec))(3)) == {3} + assert set(allresults([inc, (dec, double)])(4)) == {5, 6} + + +def test_brute(): + tree = ([inc, dec], square) + fn = brute(tree, lambda x: -x) + + assert fn(2) == (2 + 1)**2 + assert fn(-2) == (-2 - 1)**2 + + assert brute(inc)(1) == 2 diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/tools.py b/venv/lib/python3.10/site-packages/sympy/strategies/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a94c16db57206d7c83c8a5e13930c4cffdde47 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/tools.py @@ -0,0 +1,53 @@ +from . import rl +from .core import do_one, exhaust, switch +from .traverse import top_down + + +def subs(d, **kwargs): + """ Full simultaneous exact substitution. + + Examples + ======== + + >>> from sympy.strategies.tools import subs + >>> from sympy import Basic, S + >>> mapping = {S(1): S(4), S(4): S(1), Basic(S(5)): Basic(S(6), S(7))} + >>> expr = Basic(S(1), Basic(S(2), S(3)), Basic(S(4), Basic(S(5)))) + >>> subs(mapping)(expr) + Basic(4, Basic(2, 3), Basic(1, Basic(6, 7))) + """ + if d: + return top_down(do_one(*map(rl.subs, *zip(*d.items()))), **kwargs) + else: + return lambda x: x + + +def canon(*rules, **kwargs): + """ Strategy for canonicalization. + + Explanation + =========== + + Apply each rule in a bottom_up fashion through the tree. + Do each one in turn. + Keep doing this until there is no change. + """ + return exhaust(top_down(exhaust(do_one(*rules)), **kwargs)) + + +def typed(ruletypes): + """ Apply rules based on the expression type + + inputs: + ruletypes -- a dict mapping {Type: rule} + + Examples + ======== + + >>> from sympy.strategies import rm_id, typed + >>> from sympy import Add, Mul + >>> rm_zeros = rm_id(lambda x: x==0) + >>> rm_ones = rm_id(lambda x: x==1) + >>> remove_idents = typed({Add: rm_zeros, Mul: rm_ones}) + """ + return switch(type, ruletypes) diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/traverse.py b/venv/lib/python3.10/site-packages/sympy/strategies/traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..869361f443742b5b7346c9c970f103b955e8473e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/traverse.py @@ -0,0 +1,37 @@ +"""Strategies to Traverse a Tree.""" +from sympy.strategies.util import basic_fns +from sympy.strategies.core import chain, do_one + + +def top_down(rule, fns=basic_fns): + """Apply a rule down a tree running it on the top nodes first.""" + return chain(rule, lambda expr: sall(top_down(rule, fns), fns)(expr)) + + +def bottom_up(rule, fns=basic_fns): + """Apply a rule down a tree running it on the bottom nodes first.""" + return chain(lambda expr: sall(bottom_up(rule, fns), fns)(expr), rule) + + +def top_down_once(rule, fns=basic_fns): + """Apply a rule down a tree - stop on success.""" + return do_one(rule, lambda expr: sall(top_down(rule, fns), fns)(expr)) + + +def bottom_up_once(rule, fns=basic_fns): + """Apply a rule up a tree - stop on success.""" + return do_one(lambda expr: sall(bottom_up(rule, fns), fns)(expr), rule) + + +def sall(rule, fns=basic_fns): + """Strategic all - apply rule to args.""" + op, new, children, leaf = map(fns.get, ('op', 'new', 'children', 'leaf')) + + def all_rl(expr): + if leaf(expr): + return expr + else: + args = map(rule, children(expr)) + return new(op(expr), *args) + + return all_rl diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/tree.py b/venv/lib/python3.10/site-packages/sympy/strategies/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..c2006fde4fc5d09f3d38baae4d7335b4cbd971b7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/tree.py @@ -0,0 +1,139 @@ +from functools import partial +from sympy.strategies import chain, minimize +from sympy.strategies.core import identity +import sympy.strategies.branch as branch +from sympy.strategies.branch import yieldify + + +def treeapply(tree, join, leaf=identity): + """ Apply functions onto recursive containers (tree). + + Explanation + =========== + + join - a dictionary mapping container types to functions + e.g. ``{list: minimize, tuple: chain}`` + + Keys are containers/iterables. Values are functions [a] -> a. + + Examples + ======== + + >>> from sympy.strategies.tree import treeapply + >>> tree = [(3, 2), (4, 1)] + >>> treeapply(tree, {list: max, tuple: min}) + 2 + + >>> add = lambda *args: sum(args) + >>> def mul(*args): + ... total = 1 + ... for arg in args: + ... total *= arg + ... return total + >>> treeapply(tree, {list: mul, tuple: add}) + 25 + """ + for typ in join: + if isinstance(tree, typ): + return join[typ](*map(partial(treeapply, join=join, leaf=leaf), + tree)) + return leaf(tree) + + +def greedy(tree, objective=identity, **kwargs): + """ Execute a strategic tree. Select alternatives greedily + + Trees + ----- + + Nodes in a tree can be either + + function - a leaf + list - a selection among operations + tuple - a sequence of chained operations + + Textual examples + ---------------- + + Text: Run f, then run g, e.g. ``lambda x: g(f(x))`` + Code: ``(f, g)`` + + Text: Run either f or g, whichever minimizes the objective + Code: ``[f, g]`` + + Textx: Run either f or g, whichever is better, then run h + Code: ``([f, g], h)`` + + Text: Either expand then simplify or try factor then foosimp. Finally print + Code: ``([(expand, simplify), (factor, foosimp)], print)`` + + Objective + --------- + + "Better" is determined by the objective keyword. This function makes + choices to minimize the objective. It defaults to the identity. + + Examples + ======== + + >>> from sympy.strategies.tree import greedy + >>> inc = lambda x: x + 1 + >>> dec = lambda x: x - 1 + >>> double = lambda x: 2*x + + >>> tree = [inc, (dec, double)] # either inc or dec-then-double + >>> fn = greedy(tree) + >>> fn(4) # lowest value comes from the inc + 5 + >>> fn(1) # lowest value comes from dec then double + 0 + + This function selects between options in a tuple. The result is chosen + that minimizes the objective function. + + >>> fn = greedy(tree, objective=lambda x: -x) # maximize + >>> fn(4) # highest value comes from the dec then double + 6 + >>> fn(1) # highest value comes from the inc + 2 + + Greediness + ---------- + + This is a greedy algorithm. In the example: + + ([a, b], c) # do either a or b, then do c + + the choice between running ``a`` or ``b`` is made without foresight to c + """ + optimize = partial(minimize, objective=objective) + return treeapply(tree, {list: optimize, tuple: chain}, **kwargs) + + +def allresults(tree, leaf=yieldify): + """ Execute a strategic tree. Return all possibilities. + + Returns a lazy iterator of all possible results + + Exhaustiveness + -------------- + + This is an exhaustive algorithm. In the example + + ([a, b], [c, d]) + + All of the results from + + (a, c), (b, c), (a, d), (b, d) + + are returned. This can lead to combinatorial blowup. + + See sympy.strategies.greedy for details on input + """ + return treeapply(tree, {list: branch.multiplex, tuple: branch.chain}, + leaf=leaf) + + +def brute(tree, objective=identity, **kwargs): + return lambda expr: min(tuple(allresults(tree, **kwargs)(expr)), + key=objective) diff --git a/venv/lib/python3.10/site-packages/sympy/strategies/util.py b/venv/lib/python3.10/site-packages/sympy/strategies/util.py new file mode 100644 index 0000000000000000000000000000000000000000..13aab5f6a49650c5ded9cd913c23c6682f18d40a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/strategies/util.py @@ -0,0 +1,17 @@ +from sympy.core.basic import Basic + +new = Basic.__new__ + + +def assoc(d, k, v): + d = d.copy() + d[k] = v + return d + + +basic_fns = {'op': type, + 'new': Basic.__new__, + 'leaf': lambda x: not isinstance(x, Basic) or x.is_Atom, + 'children': lambda x: x.args} + +expr_fns = assoc(basic_fns, 'new', lambda op, *args: op(*args)) diff --git a/venv/lib/python3.10/site-packages/sympy/unify/__init__.py b/venv/lib/python3.10/site-packages/sympy/unify/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c166f9163785f4aa5744324eb817bef79b33525 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/unify/__init__.py @@ -0,0 +1,15 @@ +""" Unification in SymPy + +See sympy.unify.core docstring for algorithmic details + +See http://matthewrocklin.com/blog/work/2012/11/01/Unification/ for discussion +""" + +from .usympy import unify, rebuild +from .rewrite import rewriterule + +__all__ = [ + 'unify', 'rebuild', + + 'rewriterule', +] diff --git a/venv/lib/python3.10/site-packages/sympy/unify/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/sympy/unify/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d40b33e3fddd5f8c4fa83dfede30cfd626a60cd Binary files /dev/null and b/venv/lib/python3.10/site-packages/sympy/unify/__pycache__/core.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sympy/unify/core.py b/venv/lib/python3.10/site-packages/sympy/unify/core.py new file mode 100644 index 0000000000000000000000000000000000000000..5359d0bbd376e9fa9efacff1d90c0bf51414cebf --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/unify/core.py @@ -0,0 +1,234 @@ +""" Generic Unification algorithm for expression trees with lists of children + +This implementation is a direct translation of + +Artificial Intelligence: A Modern Approach by Stuart Russel and Peter Norvig +Second edition, section 9.2, page 276 + +It is modified in the following ways: + +1. We allow associative and commutative Compound expressions. This results in + combinatorial blowup. +2. We explore the tree lazily. +3. We provide generic interfaces to symbolic algebra libraries in Python. + +A more traditional version can be found here +http://aima.cs.berkeley.edu/python/logic.html +""" + +from sympy.utilities.iterables import kbins + +class Compound: + """ A little class to represent an interior node in the tree + + This is analogous to SymPy.Basic for non-Atoms + """ + def __init__(self, op, args): + self.op = op + self.args = args + + def __eq__(self, other): + return (type(self) is type(other) and self.op == other.op and + self.args == other.args) + + def __hash__(self): + return hash((type(self), self.op, self.args)) + + def __str__(self): + return "%s[%s]" % (str(self.op), ', '.join(map(str, self.args))) + +class Variable: + """ A Wild token """ + def __init__(self, arg): + self.arg = arg + + def __eq__(self, other): + return type(self) is type(other) and self.arg == other.arg + + def __hash__(self): + return hash((type(self), self.arg)) + + def __str__(self): + return "Variable(%s)" % str(self.arg) + +class CondVariable: + """ A wild token that matches conditionally. + + arg - a wild token. + valid - an additional constraining function on a match. + """ + def __init__(self, arg, valid): + self.arg = arg + self.valid = valid + + def __eq__(self, other): + return (type(self) is type(other) and + self.arg == other.arg and + self.valid == other.valid) + + def __hash__(self): + return hash((type(self), self.arg, self.valid)) + + def __str__(self): + return "CondVariable(%s)" % str(self.arg) + +def unify(x, y, s=None, **fns): + """ Unify two expressions. + + Parameters + ========== + + x, y - expression trees containing leaves, Compounds and Variables. + s - a mapping of variables to subtrees. + + Returns + ======= + + lazy sequence of mappings {Variable: subtree} + + Examples + ======== + + >>> from sympy.unify.core import unify, Compound, Variable + >>> expr = Compound("Add", ("x", "y")) + >>> pattern = Compound("Add", ("x", Variable("a"))) + >>> next(unify(expr, pattern, {})) + {Variable(a): 'y'} + """ + s = s or {} + + if x == y: + yield s + elif isinstance(x, (Variable, CondVariable)): + yield from unify_var(x, y, s, **fns) + elif isinstance(y, (Variable, CondVariable)): + yield from unify_var(y, x, s, **fns) + elif isinstance(x, Compound) and isinstance(y, Compound): + is_commutative = fns.get('is_commutative', lambda x: False) + is_associative = fns.get('is_associative', lambda x: False) + for sop in unify(x.op, y.op, s, **fns): + if is_associative(x) and is_associative(y): + a, b = (x, y) if len(x.args) < len(y.args) else (y, x) + if is_commutative(x) and is_commutative(y): + combs = allcombinations(a.args, b.args, 'commutative') + else: + combs = allcombinations(a.args, b.args, 'associative') + for aaargs, bbargs in combs: + aa = [unpack(Compound(a.op, arg)) for arg in aaargs] + bb = [unpack(Compound(b.op, arg)) for arg in bbargs] + yield from unify(aa, bb, sop, **fns) + elif len(x.args) == len(y.args): + yield from unify(x.args, y.args, sop, **fns) + + elif is_args(x) and is_args(y) and len(x) == len(y): + if len(x) == 0: + yield s + else: + for shead in unify(x[0], y[0], s, **fns): + yield from unify(x[1:], y[1:], shead, **fns) + +def unify_var(var, x, s, **fns): + if var in s: + yield from unify(s[var], x, s, **fns) + elif occur_check(var, x): + pass + elif isinstance(var, CondVariable) and var.valid(x): + yield assoc(s, var, x) + elif isinstance(var, Variable): + yield assoc(s, var, x) + +def occur_check(var, x): + """ var occurs in subtree owned by x? """ + if var == x: + return True + elif isinstance(x, Compound): + return occur_check(var, x.args) + elif is_args(x): + if any(occur_check(var, xi) for xi in x): return True + return False + +def assoc(d, key, val): + """ Return copy of d with key associated to val """ + d = d.copy() + d[key] = val + return d + +def is_args(x): + """ Is x a traditional iterable? """ + return type(x) in (tuple, list, set) + +def unpack(x): + if isinstance(x, Compound) and len(x.args) == 1: + return x.args[0] + else: + return x + +def allcombinations(A, B, ordered): + """ + Restructure A and B to have the same number of elements. + + Parameters + ========== + + ordered must be either 'commutative' or 'associative'. + + A and B can be rearranged so that the larger of the two lists is + reorganized into smaller sublists. + + Examples + ======== + + >>> from sympy.unify.core import allcombinations + >>> for x in allcombinations((1, 2, 3), (5, 6), 'associative'): print(x) + (((1,), (2, 3)), ((5,), (6,))) + (((1, 2), (3,)), ((5,), (6,))) + + >>> for x in allcombinations((1, 2, 3), (5, 6), 'commutative'): print(x) + (((1,), (2, 3)), ((5,), (6,))) + (((1, 2), (3,)), ((5,), (6,))) + (((1,), (3, 2)), ((5,), (6,))) + (((1, 3), (2,)), ((5,), (6,))) + (((2,), (1, 3)), ((5,), (6,))) + (((2, 1), (3,)), ((5,), (6,))) + (((2,), (3, 1)), ((5,), (6,))) + (((2, 3), (1,)), ((5,), (6,))) + (((3,), (1, 2)), ((5,), (6,))) + (((3, 1), (2,)), ((5,), (6,))) + (((3,), (2, 1)), ((5,), (6,))) + (((3, 2), (1,)), ((5,), (6,))) + """ + + if ordered == "commutative": + ordered = 11 + if ordered == "associative": + ordered = None + sm, bg = (A, B) if len(A) < len(B) else (B, A) + for part in kbins(list(range(len(bg))), len(sm), ordered=ordered): + if bg == B: + yield tuple((a,) for a in A), partition(B, part) + else: + yield partition(A, part), tuple((b,) for b in B) + +def partition(it, part): + """ Partition a tuple/list into pieces defined by indices. + + Examples + ======== + + >>> from sympy.unify.core import partition + >>> partition((10, 20, 30, 40), [[0, 1, 2], [3]]) + ((10, 20, 30), (40,)) + """ + return type(it)([index(it, ind) for ind in part]) + +def index(it, ind): + """ Fancy indexing into an indexable iterable (tuple, list). + + Examples + ======== + + >>> from sympy.unify.core import index + >>> index([10, 20, 30], (1, 2, 0)) + [20, 30, 10] + """ + return type(it)([it[i] for i in ind]) diff --git a/venv/lib/python3.10/site-packages/sympy/unify/rewrite.py b/venv/lib/python3.10/site-packages/sympy/unify/rewrite.py new file mode 100644 index 0000000000000000000000000000000000000000..95a6fa5ffd6a3fde94d17ee845c03bb2b44cf009 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/unify/rewrite.py @@ -0,0 +1,55 @@ +""" Functions to support rewriting of SymPy expressions """ + +from sympy.core.expr import Expr +from sympy.assumptions import ask +from sympy.strategies.tools import subs +from sympy.unify.usympy import rebuild, unify + +def rewriterule(source, target, variables=(), condition=None, assume=None): + """ Rewrite rule. + + Transform expressions that match source into expressions that match target + treating all ``variables`` as wilds. + + Examples + ======== + + >>> from sympy.abc import w, x, y, z + >>> from sympy.unify.rewrite import rewriterule + >>> from sympy import default_sort_key + >>> rl = rewriterule(x + y, x**y, [x, y]) + >>> sorted(rl(z + 3), key=default_sort_key) + [3**z, z**3] + + Use ``condition`` to specify additional requirements. Inputs are taken in + the same order as is found in variables. + + >>> rl = rewriterule(x + y, x**y, [x, y], lambda x, y: x.is_integer) + >>> list(rl(z + 3)) + [3**z] + + Use ``assume`` to specify additional requirements using new assumptions. + + >>> from sympy.assumptions import Q + >>> rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x)) + >>> list(rl(z + 3)) + [3**z] + + Assumptions for the local context are provided at rule runtime + + >>> list(rl(w + z, Q.integer(z))) + [z**w] + """ + + def rewrite_rl(expr, assumptions=True): + for match in unify(source, expr, {}, variables=variables): + if (condition and + not condition(*[match.get(var, var) for var in variables])): + continue + if (assume and not ask(assume.xreplace(match), assumptions)): + continue + expr2 = subs(match)(target) + if isinstance(expr2, Expr): + expr2 = rebuild(expr2) + yield expr2 + return rewrite_rl diff --git a/venv/lib/python3.10/site-packages/sympy/unify/usympy.py b/venv/lib/python3.10/site-packages/sympy/unify/usympy.py new file mode 100644 index 0000000000000000000000000000000000000000..3942b35ec549e5dbd08a3cf1cad2b2ecea733c7a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sympy/unify/usympy.py @@ -0,0 +1,124 @@ +""" SymPy interface to Unification engine + +See sympy.unify for module level docstring +See sympy.unify.core for algorithmic docstring """ + +from sympy.core import Basic, Add, Mul, Pow +from sympy.core.operations import AssocOp, LatticeOp +from sympy.matrices import MatAdd, MatMul, MatrixExpr +from sympy.sets.sets import Union, Intersection, FiniteSet +from sympy.unify.core import Compound, Variable, CondVariable +from sympy.unify import core + +basic_new_legal = [MatrixExpr] +eval_false_legal = [AssocOp, Pow, FiniteSet] +illegal = [LatticeOp] + +def sympy_associative(op): + assoc_ops = (AssocOp, MatAdd, MatMul, Union, Intersection, FiniteSet) + return any(issubclass(op, aop) for aop in assoc_ops) + +def sympy_commutative(op): + comm_ops = (Add, MatAdd, Union, Intersection, FiniteSet) + return any(issubclass(op, cop) for cop in comm_ops) + +def is_associative(x): + return isinstance(x, Compound) and sympy_associative(x.op) + +def is_commutative(x): + if not isinstance(x, Compound): + return False + if sympy_commutative(x.op): + return True + if issubclass(x.op, Mul): + return all(construct(arg).is_commutative for arg in x.args) + +def mk_matchtype(typ): + def matchtype(x): + return (isinstance(x, typ) or + isinstance(x, Compound) and issubclass(x.op, typ)) + return matchtype + +def deconstruct(s, variables=()): + """ Turn a SymPy object into a Compound """ + if s in variables: + return Variable(s) + if isinstance(s, (Variable, CondVariable)): + return s + if not isinstance(s, Basic) or s.is_Atom: + return s + return Compound(s.__class__, + tuple(deconstruct(arg, variables) for arg in s.args)) + +def construct(t): + """ Turn a Compound into a SymPy object """ + if isinstance(t, (Variable, CondVariable)): + return t.arg + if not isinstance(t, Compound): + return t + if any(issubclass(t.op, cls) for cls in eval_false_legal): + return t.op(*map(construct, t.args), evaluate=False) + elif any(issubclass(t.op, cls) for cls in basic_new_legal): + return Basic.__new__(t.op, *map(construct, t.args)) + else: + return t.op(*map(construct, t.args)) + +def rebuild(s): + """ Rebuild a SymPy expression. + + This removes harm caused by Expr-Rules interactions. + """ + return construct(deconstruct(s)) + +def unify(x, y, s=None, variables=(), **kwargs): + """ Structural unification of two expressions/patterns. + + Examples + ======== + + >>> from sympy.unify.usympy import unify + >>> from sympy import Basic, S + >>> from sympy.abc import x, y, z, p, q + + >>> next(unify(Basic(S(1), S(2)), Basic(S(1), x), variables=[x])) + {x: 2} + + >>> expr = 2*x + y + z + >>> pattern = 2*p + q + >>> next(unify(expr, pattern, {}, variables=(p, q))) + {p: x, q: y + z} + + Unification supports commutative and associative matching + + >>> expr = x + y + z + >>> pattern = p + q + >>> len(list(unify(expr, pattern, {}, variables=(p, q)))) + 12 + + Symbols not indicated to be variables are treated as literal, + else they are wild-like and match anything in a sub-expression. + + >>> expr = x*y*z + 3 + >>> pattern = x*y + 3 + >>> next(unify(expr, pattern, {}, variables=[x, y])) + {x: y, y: x*z} + + The x and y of the pattern above were in a Mul and matched factors + in the Mul of expr. Here, a single symbol matches an entire term: + + >>> expr = x*y + 3 + >>> pattern = p + 3 + >>> next(unify(expr, pattern, {}, variables=[p])) + {p: x*y} + + """ + decons = lambda x: deconstruct(x, variables) + s = s or {} + s = {decons(k): decons(v) for k, v in s.items()} + + ds = core.unify(decons(x), decons(y), s, + is_associative=is_associative, + is_commutative=is_commutative, + **kwargs) + for d in ds: + yield {construct(k): construct(v) for k, v in d.items()}