diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45412acad0ab9e5c7424b1888648a638ef208142 --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da752ff2aae35c5c5370f2f030afee1800454dfc Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2785f1f46379b6b57e301d83de2c11dabf2f60d1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..376c016d8edb6fb7727a726379055cd4763be557 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44223ef35d93823ee5708590c23fc8c1f97ccc95 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92b32006aa3d617587b3f2029f168fd9d087d628 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/holonomic.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/holonomic.py new file mode 100644 index 0000000000000000000000000000000000000000..0065f9e02a607c202f35db960540996f034ff40b --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py new file mode 100644 index 0000000000000000000000000000000000000000..459a94eb25b186e30b9577d972ebc62a36801f6f --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/numerical.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/numerical.py new file mode 100644 index 0000000000000000000000000000000000000000..ed78f6ee78676cd429cb9ad11a28e9046745e5d3 --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/recurrence.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/recurrence.py new file mode 100644 index 0000000000000000000000000000000000000000..4c77ae64453ed6b8b336949515b6f2f6197ca251 --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..498502d97eae20c0e5710d870472197cef7b5b22 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..650b72016e57dbfd8bd2748cf1c4a5ca17bccf9f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f8f797ce1c11c62c4eeeecf31ae8a9f73547f3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py new file mode 100644 index 0000000000000000000000000000000000000000..e5069c89a84ab89c46c95a026c8998089b73fac5 --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py b/env-llmeval/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py new file mode 100644 index 0000000000000000000000000000000000000000..695ca43d9cd81187dc52495db2329e7a347720bc --- /dev/null +++ b/env-llmeval/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/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fea0ea8dd49387175278207f2d948d5fad70e6d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aecc971a5826a34806f2878df16ae0fee6bdca99 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d448aa38e791c5980465e35fd8f9e0d0ee9ede6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a48628c92352f1b0dcc8061fd93a0d2d32adb7ef Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a420698725432e8dbecfe6793bd8291ca238f21 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50346b2aae6fd17ef960f44f1c18a7a408ebf983 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1314283d897cbe839e998b660a0d5962f9f4dc5e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94c207b07375d1429aef2ff5a4166b3ab30f0039 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..686d5ca733bd2cbde80bf154888c37e3cd297727 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f0c07107f4f1beb24f830f2faa79e764c35be49 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_arithmetic.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_arithmetic.py new file mode 100644 index 0000000000000000000000000000000000000000..b828ee57e529e600c12aac37b9346f91995dd89a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_arithmetic.py @@ -0,0 +1,412 @@ +""" +Interval Arithmetic for plotting. +This module does not implement interval arithmetic accurately and +hence cannot be used for purposes other than plotting. If you want +to use interval arithmetic, use mpmath's interval arithmetic. + +The module implements interval arithmetic using numpy and +python floating points. The rounding up and down is not handled +and hence this is not an accurate implementation of interval +arithmetic. + +The module uses numpy for speed which cannot be achieved with mpmath. +""" + +# Q: Why use numpy? Why not simply use mpmath's interval arithmetic? +# A: mpmath's interval arithmetic simulates a floating point unit +# and hence is slow, while numpy evaluations are orders of magnitude +# faster. + +# Q: Why create a separate class for intervals? Why not use SymPy's +# Interval Sets? +# A: The functionalities that will be required for plotting is quite +# different from what Interval Sets implement. + +# Q: Why is rounding up and down according to IEEE754 not handled? +# A: It is not possible to do it in both numpy and python. An external +# library has to used, which defeats the whole purpose i.e., speed. Also +# rounding is handled for very few functions in those libraries. + +# Q Will my plots be affected? +# A It will not affect most of the plots. The interval arithmetic +# module based suffers the same problems as that of floating point +# arithmetic. + +from sympy.core.logic import fuzzy_and +from sympy.simplify.simplify import nsimplify + +from .interval_membership import intervalMembership + + +class interval: + """ Represents an interval containing floating points as start and + end of the interval + The is_valid variable tracks whether the interval obtained as the + result of the function is in the domain and is continuous. + - True: Represents the interval result of a function is continuous and + in the domain of the function. + - False: The interval argument of the function was not in the domain of + the function, hence the is_valid of the result interval is False + - None: The function was not continuous over the interval or + the function's argument interval is partly in the domain of the + function + + A comparison between an interval and a real number, or a + comparison between two intervals may return ``intervalMembership`` + of two 3-valued logic values. + """ + + def __init__(self, *args, is_valid=True, **kwargs): + self.is_valid = is_valid + if len(args) == 1: + if isinstance(args[0], interval): + self.start, self.end = args[0].start, args[0].end + else: + self.start = float(args[0]) + self.end = float(args[0]) + elif len(args) == 2: + if args[0] < args[1]: + self.start = float(args[0]) + self.end = float(args[1]) + else: + self.start = float(args[1]) + self.end = float(args[0]) + + else: + raise ValueError("interval takes a maximum of two float values " + "as arguments") + + @property + def mid(self): + return (self.start + self.end) / 2.0 + + @property + def width(self): + return self.end - self.start + + def __repr__(self): + return "interval(%f, %f)" % (self.start, self.end) + + def __str__(self): + return "[%f, %f]" % (self.start, self.end) + + def __lt__(self, other): + if isinstance(other, (int, float)): + if self.end < other: + return intervalMembership(True, self.is_valid) + elif self.start > other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + + elif isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.end < other. start: + return intervalMembership(True, valid) + if self.start > other.end: + return intervalMembership(False, valid) + return intervalMembership(None, valid) + else: + return NotImplemented + + def __gt__(self, other): + if isinstance(other, (int, float)): + if self.start > other: + return intervalMembership(True, self.is_valid) + elif self.end < other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + elif isinstance(other, interval): + return other.__lt__(self) + else: + return NotImplemented + + def __eq__(self, other): + if isinstance(other, (int, float)): + if self.start == other and self.end == other: + return intervalMembership(True, self.is_valid) + if other in self: + return intervalMembership(None, self.is_valid) + else: + return intervalMembership(False, self.is_valid) + + if isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.start == other.start and self.end == other.end: + return intervalMembership(True, valid) + elif self.__lt__(other)[0] is not None: + return intervalMembership(False, valid) + else: + return intervalMembership(None, valid) + else: + return NotImplemented + + def __ne__(self, other): + if isinstance(other, (int, float)): + if self.start == other and self.end == other: + return intervalMembership(False, self.is_valid) + if other in self: + return intervalMembership(None, self.is_valid) + else: + return intervalMembership(True, self.is_valid) + + if isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.start == other.start and self.end == other.end: + return intervalMembership(False, valid) + if not self.__lt__(other)[0] is None: + return intervalMembership(True, valid) + return intervalMembership(None, valid) + else: + return NotImplemented + + def __le__(self, other): + if isinstance(other, (int, float)): + if self.end <= other: + return intervalMembership(True, self.is_valid) + if self.start > other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + + if isinstance(other, interval): + valid = fuzzy_and([self.is_valid, other.is_valid]) + if self.end <= other.start: + return intervalMembership(True, valid) + if self.start > other.end: + return intervalMembership(False, valid) + return intervalMembership(None, valid) + else: + return NotImplemented + + def __ge__(self, other): + if isinstance(other, (int, float)): + if self.start >= other: + return intervalMembership(True, self.is_valid) + elif self.end < other: + return intervalMembership(False, self.is_valid) + else: + return intervalMembership(None, self.is_valid) + elif isinstance(other, interval): + return other.__le__(self) + + def __add__(self, other): + if isinstance(other, (int, float)): + if self.is_valid: + return interval(self.start + other, self.end + other) + else: + start = self.start + other + end = self.end + other + return interval(start, end, is_valid=self.is_valid) + + elif isinstance(other, interval): + start = self.start + other.start + end = self.end + other.end + valid = fuzzy_and([self.is_valid, other.is_valid]) + return interval(start, end, is_valid=valid) + else: + return NotImplemented + + __radd__ = __add__ + + def __sub__(self, other): + if isinstance(other, (int, float)): + start = self.start - other + end = self.end - other + return interval(start, end, is_valid=self.is_valid) + + elif isinstance(other, interval): + start = self.start - other.end + end = self.end - other.start + valid = fuzzy_and([self.is_valid, other.is_valid]) + return interval(start, end, is_valid=valid) + else: + return NotImplemented + + def __rsub__(self, other): + if isinstance(other, (int, float)): + start = other - self.end + end = other - self.start + return interval(start, end, is_valid=self.is_valid) + elif isinstance(other, interval): + return other.__sub__(self) + else: + return NotImplemented + + def __neg__(self): + if self.is_valid: + return interval(-self.end, -self.start) + else: + return interval(-self.end, -self.start, is_valid=self.is_valid) + + def __mul__(self, other): + if isinstance(other, interval): + if self.is_valid is False or other.is_valid is False: + return interval(-float('inf'), float('inf'), is_valid=False) + elif self.is_valid is None or other.is_valid is None: + return interval(-float('inf'), float('inf'), is_valid=None) + else: + inters = [] + inters.append(self.start * other.start) + inters.append(self.end * other.start) + inters.append(self.start * other.end) + inters.append(self.end * other.end) + start = min(inters) + end = max(inters) + return interval(start, end) + elif isinstance(other, (int, float)): + return interval(self.start*other, self.end*other, is_valid=self.is_valid) + else: + return NotImplemented + + __rmul__ = __mul__ + + def __contains__(self, other): + if isinstance(other, (int, float)): + return self.start <= other and self.end >= other + else: + return self.start <= other.start and other.end <= self.end + + def __rtruediv__(self, other): + if isinstance(other, (int, float)): + other = interval(other) + return other.__truediv__(self) + elif isinstance(other, interval): + return other.__truediv__(self) + else: + return NotImplemented + + def __truediv__(self, other): + # Both None and False are handled + if not self.is_valid: + # Don't divide as the value is not valid + return interval(-float('inf'), float('inf'), is_valid=self.is_valid) + if isinstance(other, (int, float)): + if other == 0: + # Divide by zero encountered. valid nowhere + return interval(-float('inf'), float('inf'), is_valid=False) + else: + return interval(self.start / other, self.end / other) + + elif isinstance(other, interval): + if other.is_valid is False or self.is_valid is False: + return interval(-float('inf'), float('inf'), is_valid=False) + elif other.is_valid is None or self.is_valid is None: + return interval(-float('inf'), float('inf'), is_valid=None) + else: + # denominator contains both signs, i.e. being divided by zero + # return the whole real line with is_valid = None + if 0 in other: + return interval(-float('inf'), float('inf'), is_valid=None) + + # denominator negative + this = self + if other.end < 0: + this = -this + other = -other + + # denominator positive + inters = [] + inters.append(this.start / other.start) + inters.append(this.end / other.start) + inters.append(this.start / other.end) + inters.append(this.end / other.end) + start = max(inters) + end = min(inters) + return interval(start, end) + else: + return NotImplemented + + def __pow__(self, other): + # Implements only power to an integer. + from .lib_interval import exp, log + if not self.is_valid: + return self + if isinstance(other, interval): + return exp(other * log(self)) + elif isinstance(other, (float, int)): + if other < 0: + return 1 / self.__pow__(abs(other)) + else: + if int(other) == other: + return _pow_int(self, other) + else: + return _pow_float(self, other) + else: + return NotImplemented + + def __rpow__(self, other): + if isinstance(other, (float, int)): + if not self.is_valid: + #Don't do anything + return self + elif other < 0: + if self.width > 0: + return interval(-float('inf'), float('inf'), is_valid=False) + else: + power_rational = nsimplify(self.start) + num, denom = power_rational.as_numer_denom() + if denom % 2 == 0: + return interval(-float('inf'), float('inf'), + is_valid=False) + else: + start = -abs(other)**self.start + end = start + return interval(start, end) + else: + return interval(other**self.start, other**self.end) + elif isinstance(other, interval): + return other.__pow__(self) + else: + return NotImplemented + + def __hash__(self): + return hash((self.is_valid, self.start, self.end)) + + +def _pow_float(inter, power): + """Evaluates an interval raised to a floating point.""" + power_rational = nsimplify(power) + num, denom = power_rational.as_numer_denom() + if num % 2 == 0: + start = abs(inter.start)**power + end = abs(inter.end)**power + if start < 0: + ret = interval(0, max(start, end)) + else: + ret = interval(start, end) + return ret + elif denom % 2 == 0: + if inter.end < 0: + return interval(-float('inf'), float('inf'), is_valid=False) + elif inter.start < 0: + return interval(0, inter.end**power, is_valid=None) + else: + return interval(inter.start**power, inter.end**power) + else: + if inter.start < 0: + start = -abs(inter.start)**power + else: + start = inter.start**power + + if inter.end < 0: + end = -abs(inter.end)**power + else: + end = inter.end**power + + return interval(start, end, is_valid=inter.is_valid) + + +def _pow_int(inter, power): + """Evaluates an interval raised to an integer power""" + power = int(power) + if power & 1: + return interval(inter.start**power, inter.end**power) + else: + if inter.start < 0 and inter.end > 0: + start = 0 + end = max(inter.start**power, inter.end**power) + return interval(start, end) + else: + return interval(inter.start**power, inter.end**power) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py new file mode 100644 index 0000000000000000000000000000000000000000..c4887c2d96f0d006b95a8e207a4f4a75940aec23 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py @@ -0,0 +1,78 @@ +from sympy.core.logic import fuzzy_and, fuzzy_or, fuzzy_not, fuzzy_xor + + +class intervalMembership: + """Represents a boolean expression returned by the comparison of + the interval object. + + Parameters + ========== + + (a, b) : (bool, bool) + The first value determines the comparison as follows: + - True: If the comparison is True throughout the intervals. + - False: If the comparison is False throughout the intervals. + - None: If the comparison is True for some part of the intervals. + + The second value is determined as follows: + - True: If both the intervals in comparison are valid. + - False: If at least one of the intervals is False, else + - None + """ + def __init__(self, a, b): + self._wrapped = (a, b) + + def __getitem__(self, i): + try: + return self._wrapped[i] + except IndexError: + raise IndexError( + "{} must be a valid indexing for the 2-tuple." + .format(i)) + + def __len__(self): + return 2 + + def __iter__(self): + return iter(self._wrapped) + + def __str__(self): + return "intervalMembership({}, {})".format(*self) + __repr__ = __str__ + + def __and__(self, other): + if not isinstance(other, intervalMembership): + raise ValueError( + "The comparison is not supported for {}.".format(other)) + + a1, b1 = self + a2, b2 = other + return intervalMembership(fuzzy_and([a1, a2]), fuzzy_and([b1, b2])) + + def __or__(self, other): + if not isinstance(other, intervalMembership): + raise ValueError( + "The comparison is not supported for {}.".format(other)) + + a1, b1 = self + a2, b2 = other + return intervalMembership(fuzzy_or([a1, a2]), fuzzy_and([b1, b2])) + + def __invert__(self): + a, b = self + return intervalMembership(fuzzy_not(a), b) + + def __xor__(self, other): + if not isinstance(other, intervalMembership): + raise ValueError( + "The comparison is not supported for {}.".format(other)) + + a1, b1 = self + a2, b2 = other + return intervalMembership(fuzzy_xor([a1, a2]), fuzzy_and([b1, b2])) + + def __eq__(self, other): + return self._wrapped == other + + def __ne__(self, other): + return self._wrapped != other diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py new file mode 100644 index 0000000000000000000000000000000000000000..7549a05820d747ce057892f8df1fbcbc61cc3f43 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py @@ -0,0 +1,452 @@ +""" The module contains implemented functions for interval arithmetic.""" +from functools import reduce + +from sympy.plotting.intervalmath import interval +from sympy.external import import_module + + +def Abs(x): + if isinstance(x, (int, float)): + return interval(abs(x)) + elif isinstance(x, interval): + if x.start < 0 and x.end > 0: + return interval(0, max(abs(x.start), abs(x.end)), is_valid=x.is_valid) + else: + return interval(abs(x.start), abs(x.end)) + else: + raise NotImplementedError + +#Monotonic + + +def exp(x): + """evaluates the exponential of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.exp(x), np.exp(x)) + elif isinstance(x, interval): + return interval(np.exp(x.start), np.exp(x.end), is_valid=x.is_valid) + else: + raise NotImplementedError + + +#Monotonic +def log(x): + """evaluates the natural logarithm of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + if x <= 0: + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(np.log(x)) + elif isinstance(x, interval): + if not x.is_valid: + return interval(-np.inf, np.inf, is_valid=x.is_valid) + elif x.end <= 0: + return interval(-np.inf, np.inf, is_valid=False) + elif x.start <= 0: + return interval(-np.inf, np.inf, is_valid=None) + + return interval(np.log(x.start), np.log(x.end)) + else: + raise NotImplementedError + + +#Monotonic +def log10(x): + """evaluates the logarithm to the base 10 of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + if x <= 0: + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(np.log10(x)) + elif isinstance(x, interval): + if not x.is_valid: + return interval(-np.inf, np.inf, is_valid=x.is_valid) + elif x.end <= 0: + return interval(-np.inf, np.inf, is_valid=False) + elif x.start <= 0: + return interval(-np.inf, np.inf, is_valid=None) + return interval(np.log10(x.start), np.log10(x.end)) + else: + raise NotImplementedError + + +#Monotonic +def atan(x): + """evaluates the tan inverse of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.arctan(x)) + elif isinstance(x, interval): + start = np.arctan(x.start) + end = np.arctan(x.end) + return interval(start, end, is_valid=x.is_valid) + else: + raise NotImplementedError + + +#periodic +def sin(x): + """evaluates the sine of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.sin(x)) + elif isinstance(x, interval): + if not x.is_valid: + return interval(-1, 1, is_valid=x.is_valid) + na, __ = divmod(x.start, np.pi / 2.0) + nb, __ = divmod(x.end, np.pi / 2.0) + start = min(np.sin(x.start), np.sin(x.end)) + end = max(np.sin(x.start), np.sin(x.end)) + if nb - na > 4: + return interval(-1, 1, is_valid=x.is_valid) + elif na == nb: + return interval(start, end, is_valid=x.is_valid) + else: + if (na - 1) // 4 != (nb - 1) // 4: + #sin has max + end = 1 + if (na - 3) // 4 != (nb - 3) // 4: + #sin has min + start = -1 + return interval(start, end) + else: + raise NotImplementedError + + +#periodic +def cos(x): + """Evaluates the cos of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.sin(x)) + elif isinstance(x, interval): + if not (np.isfinite(x.start) and np.isfinite(x.end)): + return interval(-1, 1, is_valid=x.is_valid) + na, __ = divmod(x.start, np.pi / 2.0) + nb, __ = divmod(x.end, np.pi / 2.0) + start = min(np.cos(x.start), np.cos(x.end)) + end = max(np.cos(x.start), np.cos(x.end)) + if nb - na > 4: + #differ more than 2*pi + return interval(-1, 1, is_valid=x.is_valid) + elif na == nb: + #in the same quadarant + return interval(start, end, is_valid=x.is_valid) + else: + if (na) // 4 != (nb) // 4: + #cos has max + end = 1 + if (na - 2) // 4 != (nb - 2) // 4: + #cos has min + start = -1 + return interval(start, end, is_valid=x.is_valid) + else: + raise NotImplementedError + + +def tan(x): + """Evaluates the tan of an interval""" + return sin(x) / cos(x) + + +#Monotonic +def sqrt(x): + """Evaluates the square root of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + if x > 0: + return interval(np.sqrt(x)) + else: + return interval(-np.inf, np.inf, is_valid=False) + elif isinstance(x, interval): + #Outside the domain + if x.end < 0: + return interval(-np.inf, np.inf, is_valid=False) + #Partially outside the domain + elif x.start < 0: + return interval(-np.inf, np.inf, is_valid=None) + else: + return interval(np.sqrt(x.start), np.sqrt(x.end), + is_valid=x.is_valid) + else: + raise NotImplementedError + + +def imin(*args): + """Evaluates the minimum of a list of intervals""" + np = import_module('numpy') + if not all(isinstance(arg, (int, float, interval)) for arg in args): + return NotImplementedError + else: + new_args = [a for a in args if isinstance(a, (int, float)) + or a.is_valid] + if len(new_args) == 0: + if all(a.is_valid is False for a in args): + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(-np.inf, np.inf, is_valid=None) + start_array = [a if isinstance(a, (int, float)) else a.start + for a in new_args] + + end_array = [a if isinstance(a, (int, float)) else a.end + for a in new_args] + return interval(min(start_array), min(end_array)) + + +def imax(*args): + """Evaluates the maximum of a list of intervals""" + np = import_module('numpy') + if not all(isinstance(arg, (int, float, interval)) for arg in args): + return NotImplementedError + else: + new_args = [a for a in args if isinstance(a, (int, float)) + or a.is_valid] + if len(new_args) == 0: + if all(a.is_valid is False for a in args): + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(-np.inf, np.inf, is_valid=None) + start_array = [a if isinstance(a, (int, float)) else a.start + for a in new_args] + + end_array = [a if isinstance(a, (int, float)) else a.end + for a in new_args] + + return interval(max(start_array), max(end_array)) + + +#Monotonic +def sinh(x): + """Evaluates the hyperbolic sine of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.sinh(x), np.sinh(x)) + elif isinstance(x, interval): + return interval(np.sinh(x.start), np.sinh(x.end), is_valid=x.is_valid) + else: + raise NotImplementedError + + +def cosh(x): + """Evaluates the hyperbolic cos of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.cosh(x), np.cosh(x)) + elif isinstance(x, interval): + #both signs + if x.start < 0 and x.end > 0: + end = max(np.cosh(x.start), np.cosh(x.end)) + return interval(1, end, is_valid=x.is_valid) + else: + #Monotonic + start = np.cosh(x.start) + end = np.cosh(x.end) + return interval(start, end, is_valid=x.is_valid) + else: + raise NotImplementedError + + +#Monotonic +def tanh(x): + """Evaluates the hyperbolic tan of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.tanh(x), np.tanh(x)) + elif isinstance(x, interval): + return interval(np.tanh(x.start), np.tanh(x.end), is_valid=x.is_valid) + else: + raise NotImplementedError + + +def asin(x): + """Evaluates the inverse sine of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + #Outside the domain + if abs(x) > 1: + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(np.arcsin(x), np.arcsin(x)) + elif isinstance(x, interval): + #Outside the domain + if x.is_valid is False or x.start > 1 or x.end < -1: + return interval(-np.inf, np.inf, is_valid=False) + #Partially outside the domain + elif x.start < -1 or x.end > 1: + return interval(-np.inf, np.inf, is_valid=None) + else: + start = np.arcsin(x.start) + end = np.arcsin(x.end) + return interval(start, end, is_valid=x.is_valid) + + +def acos(x): + """Evaluates the inverse cos of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + if abs(x) > 1: + #Outside the domain + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(np.arccos(x), np.arccos(x)) + elif isinstance(x, interval): + #Outside the domain + if x.is_valid is False or x.start > 1 or x.end < -1: + return interval(-np.inf, np.inf, is_valid=False) + #Partially outside the domain + elif x.start < -1 or x.end > 1: + return interval(-np.inf, np.inf, is_valid=None) + else: + start = np.arccos(x.start) + end = np.arccos(x.end) + return interval(start, end, is_valid=x.is_valid) + + +def ceil(x): + """Evaluates the ceiling of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.ceil(x)) + elif isinstance(x, interval): + if x.is_valid is False: + return interval(-np.inf, np.inf, is_valid=False) + else: + start = np.ceil(x.start) + end = np.ceil(x.end) + #Continuous over the interval + if start == end: + return interval(start, end, is_valid=x.is_valid) + else: + #Not continuous over the interval + return interval(start, end, is_valid=None) + else: + return NotImplementedError + + +def floor(x): + """Evaluates the floor of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.floor(x)) + elif isinstance(x, interval): + if x.is_valid is False: + return interval(-np.inf, np.inf, is_valid=False) + else: + start = np.floor(x.start) + end = np.floor(x.end) + #continuous over the argument + if start == end: + return interval(start, end, is_valid=x.is_valid) + else: + #not continuous over the interval + return interval(start, end, is_valid=None) + else: + return NotImplementedError + + +def acosh(x): + """Evaluates the inverse hyperbolic cosine of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + #Outside the domain + if x < 1: + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(np.arccosh(x)) + elif isinstance(x, interval): + #Outside the domain + if x.end < 1: + return interval(-np.inf, np.inf, is_valid=False) + #Partly outside the domain + elif x.start < 1: + return interval(-np.inf, np.inf, is_valid=None) + else: + start = np.arccosh(x.start) + end = np.arccosh(x.end) + return interval(start, end, is_valid=x.is_valid) + else: + return NotImplementedError + + +#Monotonic +def asinh(x): + """Evaluates the inverse hyperbolic sine of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + return interval(np.arcsinh(x)) + elif isinstance(x, interval): + start = np.arcsinh(x.start) + end = np.arcsinh(x.end) + return interval(start, end, is_valid=x.is_valid) + else: + return NotImplementedError + + +def atanh(x): + """Evaluates the inverse hyperbolic tangent of an interval""" + np = import_module('numpy') + if isinstance(x, (int, float)): + #Outside the domain + if abs(x) >= 1: + return interval(-np.inf, np.inf, is_valid=False) + else: + return interval(np.arctanh(x)) + elif isinstance(x, interval): + #outside the domain + if x.is_valid is False or x.start >= 1 or x.end <= -1: + return interval(-np.inf, np.inf, is_valid=False) + #partly outside the domain + elif x.start <= -1 or x.end >= 1: + return interval(-np.inf, np.inf, is_valid=None) + else: + start = np.arctanh(x.start) + end = np.arctanh(x.end) + return interval(start, end, is_valid=x.is_valid) + else: + return NotImplementedError + + +#Three valued logic for interval plotting. + +def And(*args): + """Defines the three valued ``And`` behaviour for a 2-tuple of + three valued logic values""" + def reduce_and(cmp_intervala, cmp_intervalb): + if cmp_intervala[0] is False or cmp_intervalb[0] is False: + first = False + elif cmp_intervala[0] is None or cmp_intervalb[0] is None: + first = None + else: + first = True + if cmp_intervala[1] is False or cmp_intervalb[1] is False: + second = False + elif cmp_intervala[1] is None or cmp_intervalb[1] is None: + second = None + else: + second = True + return (first, second) + return reduce(reduce_and, args) + + +def Or(*args): + """Defines the three valued ``Or`` behaviour for a 2-tuple of + three valued logic values""" + def reduce_or(cmp_intervala, cmp_intervalb): + if cmp_intervala[0] is True or cmp_intervalb[0] is True: + first = True + elif cmp_intervala[0] is None or cmp_intervalb[0] is None: + first = None + else: + first = False + + if cmp_intervala[1] is True or cmp_intervalb[1] is True: + second = True + elif cmp_intervala[1] is None or cmp_intervalb[1] is None: + second = None + else: + second = False + return (first, second) + return reduce(reduce_or, args) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..224e108b7ac4000e9e7fc7669df901113289ac1a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..632205bcfb9dce3a97f462434743ef618216ade2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_membership.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_membership.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..974829f194ff25d39ad6ff802861008ce1b6ad59 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_membership.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_intervalmath.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_intervalmath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf619fca6e36a88c4cf7993a6dd6d5180f9a6c55 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_intervalmath.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_functions.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..861c3660df024d3fbec788a027708348e9929655 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_functions.py @@ -0,0 +1,415 @@ +from sympy.external import import_module +from sympy.plotting.intervalmath import ( + Abs, acos, acosh, And, asin, asinh, atan, atanh, ceil, cos, cosh, + exp, floor, imax, imin, interval, log, log10, Or, sin, sinh, sqrt, + tan, tanh, +) + +np = import_module('numpy') +if not np: + disabled = True + + +#requires Numpy. Hence included in interval_functions + + +def test_interval_pow(): + a = 2**interval(1, 2) == interval(2, 4) + assert a == (True, True) + a = interval(1, 2)**interval(1, 2) == interval(1, 4) + assert a == (True, True) + a = interval(-1, 1)**interval(0.5, 2) + assert a.is_valid is None + a = interval(-2, -1) ** interval(1, 2) + assert a.is_valid is False + a = interval(-2, -1) ** (1.0 / 2) + assert a.is_valid is False + a = interval(-1, 1)**(1.0 / 2) + assert a.is_valid is None + a = interval(-1, 1)**(1.0 / 3) == interval(-1, 1) + assert a == (True, True) + a = interval(-1, 1)**2 == interval(0, 1) + assert a == (True, True) + a = interval(-1, 1) ** (1.0 / 29) == interval(-1, 1) + assert a == (True, True) + a = -2**interval(1, 1) == interval(-2, -2) + assert a == (True, True) + + a = interval(1, 2, is_valid=False)**2 + assert a.is_valid is False + + a = (-3)**interval(1, 2) + assert a.is_valid is False + a = (-4)**interval(0.5, 0.5) + assert a.is_valid is False + assert ((-3)**interval(1, 1) == interval(-3, -3)) == (True, True) + + a = interval(8, 64)**(2.0 / 3) + assert abs(a.start - 4) < 1e-10 # eps + assert abs(a.end - 16) < 1e-10 + a = interval(-8, 64)**(2.0 / 3) + assert abs(a.start - 4) < 1e-10 # eps + assert abs(a.end - 16) < 1e-10 + + +def test_exp(): + a = exp(interval(-np.inf, 0)) + assert a.start == np.exp(-np.inf) + assert a.end == np.exp(0) + a = exp(interval(1, 2)) + assert a.start == np.exp(1) + assert a.end == np.exp(2) + a = exp(1) + assert a.start == np.exp(1) + assert a.end == np.exp(1) + + +def test_log(): + a = log(interval(1, 2)) + assert a.start == 0 + assert a.end == np.log(2) + a = log(interval(-1, 1)) + assert a.is_valid is None + a = log(interval(-3, -1)) + assert a.is_valid is False + a = log(-3) + assert a.is_valid is False + a = log(2) + assert a.start == np.log(2) + assert a.end == np.log(2) + + +def test_log10(): + a = log10(interval(1, 2)) + assert a.start == 0 + assert a.end == np.log10(2) + a = log10(interval(-1, 1)) + assert a.is_valid is None + a = log10(interval(-3, -1)) + assert a.is_valid is False + a = log10(-3) + assert a.is_valid is False + a = log10(2) + assert a.start == np.log10(2) + assert a.end == np.log10(2) + + +def test_atan(): + a = atan(interval(0, 1)) + assert a.start == np.arctan(0) + assert a.end == np.arctan(1) + a = atan(1) + assert a.start == np.arctan(1) + assert a.end == np.arctan(1) + + +def test_sin(): + a = sin(interval(0, np.pi / 4)) + assert a.start == np.sin(0) + assert a.end == np.sin(np.pi / 4) + + a = sin(interval(-np.pi / 4, np.pi / 4)) + assert a.start == np.sin(-np.pi / 4) + assert a.end == np.sin(np.pi / 4) + + a = sin(interval(np.pi / 4, 3 * np.pi / 4)) + assert a.start == np.sin(np.pi / 4) + assert a.end == 1 + + a = sin(interval(7 * np.pi / 6, 7 * np.pi / 4)) + assert a.start == -1 + assert a.end == np.sin(7 * np.pi / 6) + + a = sin(interval(0, 3 * np.pi)) + assert a.start == -1 + assert a.end == 1 + + a = sin(interval(np.pi / 3, 7 * np.pi / 4)) + assert a.start == -1 + assert a.end == 1 + + a = sin(np.pi / 4) + assert a.start == np.sin(np.pi / 4) + assert a.end == np.sin(np.pi / 4) + + a = sin(interval(1, 2, is_valid=False)) + assert a.is_valid is False + + +def test_cos(): + a = cos(interval(0, np.pi / 4)) + assert a.start == np.cos(np.pi / 4) + assert a.end == 1 + + a = cos(interval(-np.pi / 4, np.pi / 4)) + assert a.start == np.cos(-np.pi / 4) + assert a.end == 1 + + a = cos(interval(np.pi / 4, 3 * np.pi / 4)) + assert a.start == np.cos(3 * np.pi / 4) + assert a.end == np.cos(np.pi / 4) + + a = cos(interval(3 * np.pi / 4, 5 * np.pi / 4)) + assert a.start == -1 + assert a.end == np.cos(3 * np.pi / 4) + + a = cos(interval(0, 3 * np.pi)) + assert a.start == -1 + assert a.end == 1 + + a = cos(interval(- np.pi / 3, 5 * np.pi / 4)) + assert a.start == -1 + assert a.end == 1 + + a = cos(interval(1, 2, is_valid=False)) + assert a.is_valid is False + + +def test_tan(): + a = tan(interval(0, np.pi / 4)) + assert a.start == 0 + # must match lib_interval definition of tan: + assert a.end == np.sin(np.pi / 4)/np.cos(np.pi / 4) + + a = tan(interval(np.pi / 4, 3 * np.pi / 4)) + #discontinuity + assert a.is_valid is None + + +def test_sqrt(): + a = sqrt(interval(1, 4)) + assert a.start == 1 + assert a.end == 2 + + a = sqrt(interval(0.01, 1)) + assert a.start == np.sqrt(0.01) + assert a.end == 1 + + a = sqrt(interval(-1, 1)) + assert a.is_valid is None + + a = sqrt(interval(-3, -1)) + assert a.is_valid is False + + a = sqrt(4) + assert (a == interval(2, 2)) == (True, True) + + a = sqrt(-3) + assert a.is_valid is False + + +def test_imin(): + a = imin(interval(1, 3), interval(2, 5), interval(-1, 3)) + assert a.start == -1 + assert a.end == 3 + + a = imin(-2, interval(1, 4)) + assert a.start == -2 + assert a.end == -2 + + a = imin(5, interval(3, 4), interval(-2, 2, is_valid=False)) + assert a.start == 3 + assert a.end == 4 + + +def test_imax(): + a = imax(interval(-2, 2), interval(2, 7), interval(-3, 9)) + assert a.start == 2 + assert a.end == 9 + + a = imax(8, interval(1, 4)) + assert a.start == 8 + assert a.end == 8 + + a = imax(interval(1, 2), interval(3, 4), interval(-2, 2, is_valid=False)) + assert a.start == 3 + assert a.end == 4 + + +def test_sinh(): + a = sinh(interval(-1, 1)) + assert a.start == np.sinh(-1) + assert a.end == np.sinh(1) + + a = sinh(1) + assert a.start == np.sinh(1) + assert a.end == np.sinh(1) + + +def test_cosh(): + a = cosh(interval(1, 2)) + assert a.start == np.cosh(1) + assert a.end == np.cosh(2) + a = cosh(interval(-2, -1)) + assert a.start == np.cosh(-1) + assert a.end == np.cosh(-2) + + a = cosh(interval(-2, 1)) + assert a.start == 1 + assert a.end == np.cosh(-2) + + a = cosh(1) + assert a.start == np.cosh(1) + assert a.end == np.cosh(1) + + +def test_tanh(): + a = tanh(interval(-3, 3)) + assert a.start == np.tanh(-3) + assert a.end == np.tanh(3) + + a = tanh(3) + assert a.start == np.tanh(3) + assert a.end == np.tanh(3) + + +def test_asin(): + a = asin(interval(-0.5, 0.5)) + assert a.start == np.arcsin(-0.5) + assert a.end == np.arcsin(0.5) + + a = asin(interval(-1.5, 1.5)) + assert a.is_valid is None + a = asin(interval(-2, -1.5)) + assert a.is_valid is False + + a = asin(interval(0, 2)) + assert a.is_valid is None + + a = asin(interval(2, 5)) + assert a.is_valid is False + + a = asin(0.5) + assert a.start == np.arcsin(0.5) + assert a.end == np.arcsin(0.5) + + a = asin(1.5) + assert a.is_valid is False + + +def test_acos(): + a = acos(interval(-0.5, 0.5)) + assert a.start == np.arccos(0.5) + assert a.end == np.arccos(-0.5) + + a = acos(interval(-1.5, 1.5)) + assert a.is_valid is None + a = acos(interval(-2, -1.5)) + assert a.is_valid is False + + a = acos(interval(0, 2)) + assert a.is_valid is None + + a = acos(interval(2, 5)) + assert a.is_valid is False + + a = acos(0.5) + assert a.start == np.arccos(0.5) + assert a.end == np.arccos(0.5) + + a = acos(1.5) + assert a.is_valid is False + + +def test_ceil(): + a = ceil(interval(0.2, 0.5)) + assert a.start == 1 + assert a.end == 1 + + a = ceil(interval(0.5, 1.5)) + assert a.start == 1 + assert a.end == 2 + assert a.is_valid is None + + a = ceil(interval(-5, 5)) + assert a.is_valid is None + + a = ceil(5.4) + assert a.start == 6 + assert a.end == 6 + + +def test_floor(): + a = floor(interval(0.2, 0.5)) + assert a.start == 0 + assert a.end == 0 + + a = floor(interval(0.5, 1.5)) + assert a.start == 0 + assert a.end == 1 + assert a.is_valid is None + + a = floor(interval(-5, 5)) + assert a.is_valid is None + + a = floor(5.4) + assert a.start == 5 + assert a.end == 5 + + +def test_asinh(): + a = asinh(interval(1, 2)) + assert a.start == np.arcsinh(1) + assert a.end == np.arcsinh(2) + + a = asinh(0.5) + assert a.start == np.arcsinh(0.5) + assert a.end == np.arcsinh(0.5) + + +def test_acosh(): + a = acosh(interval(3, 5)) + assert a.start == np.arccosh(3) + assert a.end == np.arccosh(5) + + a = acosh(interval(0, 3)) + assert a.is_valid is None + a = acosh(interval(-3, 0.5)) + assert a.is_valid is False + + a = acosh(0.5) + assert a.is_valid is False + + a = acosh(2) + assert a.start == np.arccosh(2) + assert a.end == np.arccosh(2) + + +def test_atanh(): + a = atanh(interval(-0.5, 0.5)) + assert a.start == np.arctanh(-0.5) + assert a.end == np.arctanh(0.5) + + a = atanh(interval(0, 3)) + assert a.is_valid is None + + a = atanh(interval(-3, -2)) + assert a.is_valid is False + + a = atanh(0.5) + assert a.start == np.arctanh(0.5) + assert a.end == np.arctanh(0.5) + + a = atanh(1.5) + assert a.is_valid is False + + +def test_Abs(): + assert (Abs(interval(-0.5, 0.5)) == interval(0, 0.5)) == (True, True) + assert (Abs(interval(-3, -2)) == interval(2, 3)) == (True, True) + assert (Abs(-3) == interval(3, 3)) == (True, True) + + +def test_And(): + args = [(True, True), (True, False), (True, None)] + assert And(*args) == (True, False) + + args = [(False, True), (None, None), (True, True)] + assert And(*args) == (False, None) + + +def test_Or(): + args = [(True, True), (True, False), (False, None)] + assert Or(*args) == (True, True) + args = [(None, None), (False, None), (False, False)] + assert Or(*args) == (None, None) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_membership.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_membership.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7f23680d60a64a6257a84c2476e31a8b5dfce8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_interval_membership.py @@ -0,0 +1,150 @@ +from sympy.core.symbol import Symbol +from sympy.plotting.intervalmath import interval +from sympy.plotting.intervalmath.interval_membership import intervalMembership +from sympy.plotting.experimental_lambdify import experimental_lambdify +from sympy.testing.pytest import raises + + +def test_creation(): + assert intervalMembership(True, True) + raises(TypeError, lambda: intervalMembership(True)) + raises(TypeError, lambda: intervalMembership(True, True, True)) + + +def test_getitem(): + a = intervalMembership(True, False) + assert a[0] is True + assert a[1] is False + raises(IndexError, lambda: a[2]) + + +def test_str(): + a = intervalMembership(True, False) + assert str(a) == 'intervalMembership(True, False)' + assert repr(a) == 'intervalMembership(True, False)' + + +def test_equivalence(): + a = intervalMembership(True, True) + b = intervalMembership(True, False) + assert (a == b) is False + assert (a != b) is True + + a = intervalMembership(True, False) + b = intervalMembership(True, False) + assert (a == b) is True + assert (a != b) is False + + +def test_not(): + x = Symbol('x') + + r1 = x > -1 + r2 = x <= -1 + + i = interval + + f1 = experimental_lambdify((x,), r1) + f2 = experimental_lambdify((x,), r2) + + tt = i(-0.1, 0.1, is_valid=True) + tn = i(-0.1, 0.1, is_valid=None) + tf = i(-0.1, 0.1, is_valid=False) + + assert f1(tt) == ~f2(tt) + assert f1(tn) == ~f2(tn) + assert f1(tf) == ~f2(tf) + + nt = i(0.9, 1.1, is_valid=True) + nn = i(0.9, 1.1, is_valid=None) + nf = i(0.9, 1.1, is_valid=False) + + assert f1(nt) == ~f2(nt) + assert f1(nn) == ~f2(nn) + assert f1(nf) == ~f2(nf) + + ft = i(1.9, 2.1, is_valid=True) + fn = i(1.9, 2.1, is_valid=None) + ff = i(1.9, 2.1, is_valid=False) + + assert f1(ft) == ~f2(ft) + assert f1(fn) == ~f2(fn) + assert f1(ff) == ~f2(ff) + + +def test_boolean(): + # There can be 9*9 test cases in full mapping of the cartesian product. + # But we only consider 3*3 cases for simplicity. + s = [ + intervalMembership(False, False), + intervalMembership(None, None), + intervalMembership(True, True) + ] + + # Reduced tests for 'And' + a1 = [ + intervalMembership(False, False), + intervalMembership(False, False), + intervalMembership(False, False), + intervalMembership(False, False), + intervalMembership(None, None), + intervalMembership(None, None), + intervalMembership(False, False), + intervalMembership(None, None), + intervalMembership(True, True) + ] + a1_iter = iter(a1) + for i in range(len(s)): + for j in range(len(s)): + assert s[i] & s[j] == next(a1_iter) + + # Reduced tests for 'Or' + a1 = [ + intervalMembership(False, False), + intervalMembership(None, False), + intervalMembership(True, False), + intervalMembership(None, False), + intervalMembership(None, None), + intervalMembership(True, None), + intervalMembership(True, False), + intervalMembership(True, None), + intervalMembership(True, True) + ] + a1_iter = iter(a1) + for i in range(len(s)): + for j in range(len(s)): + assert s[i] | s[j] == next(a1_iter) + + # Reduced tests for 'Xor' + a1 = [ + intervalMembership(False, False), + intervalMembership(None, False), + intervalMembership(True, False), + intervalMembership(None, False), + intervalMembership(None, None), + intervalMembership(None, None), + intervalMembership(True, False), + intervalMembership(None, None), + intervalMembership(False, True) + ] + a1_iter = iter(a1) + for i in range(len(s)): + for j in range(len(s)): + assert s[i] ^ s[j] == next(a1_iter) + + # Reduced tests for 'Not' + a1 = [ + intervalMembership(True, False), + intervalMembership(None, None), + intervalMembership(False, True) + ] + a1_iter = iter(a1) + for i in range(len(s)): + assert ~s[i] == next(a1_iter) + + +def test_boolean_errors(): + a = intervalMembership(True, True) + raises(ValueError, lambda: a & 1) + raises(ValueError, lambda: a | 1) + raises(ValueError, lambda: a ^ 1) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_intervalmath.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_intervalmath.py new file mode 100644 index 0000000000000000000000000000000000000000..e30f217a44b4ea795270c0e2c66b6813b05e63ea --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/test_intervalmath.py @@ -0,0 +1,213 @@ +from sympy.plotting.intervalmath import interval +from sympy.testing.pytest import raises + + +def test_interval(): + assert (interval(1, 1) == interval(1, 1, is_valid=True)) == (True, True) + assert (interval(1, 1) == interval(1, 1, is_valid=False)) == (True, False) + assert (interval(1, 1) == interval(1, 1, is_valid=None)) == (True, None) + assert (interval(1, 1.5) == interval(1, 2)) == (None, True) + assert (interval(0, 1) == interval(2, 3)) == (False, True) + assert (interval(0, 1) == interval(1, 2)) == (None, True) + assert (interval(1, 2) != interval(1, 2)) == (False, True) + assert (interval(1, 3) != interval(2, 3)) == (None, True) + assert (interval(1, 3) != interval(-5, -3)) == (True, True) + assert ( + interval(1, 3, is_valid=False) != interval(-5, -3)) == (True, False) + assert (interval(1, 3, is_valid=None) != interval(-5, 3)) == (None, None) + assert (interval(4, 4) != 4) == (False, True) + assert (interval(1, 1) == 1) == (True, True) + assert (interval(1, 3, is_valid=False) == interval(1, 3)) == (True, False) + assert (interval(1, 3, is_valid=None) == interval(1, 3)) == (True, None) + inter = interval(-5, 5) + assert (interval(inter) == interval(-5, 5)) == (True, True) + assert inter.width == 10 + assert 0 in inter + assert -5 in inter + assert 5 in inter + assert interval(0, 3) in inter + assert interval(-6, 2) not in inter + assert -5.05 not in inter + assert 5.3 not in inter + interb = interval(-float('inf'), float('inf')) + assert 0 in inter + assert inter in interb + assert interval(0, float('inf')) in interb + assert interval(-float('inf'), 5) in interb + assert interval(-1e50, 1e50) in interb + assert ( + -interval(-1, -2, is_valid=False) == interval(1, 2)) == (True, False) + raises(ValueError, lambda: interval(1, 2, 3)) + + +def test_interval_add(): + assert (interval(1, 2) + interval(2, 3) == interval(3, 5)) == (True, True) + assert (1 + interval(1, 2) == interval(2, 3)) == (True, True) + assert (interval(1, 2) + 1 == interval(2, 3)) == (True, True) + compare = (1 + interval(0, float('inf')) == interval(1, float('inf'))) + assert compare == (True, True) + a = 1 + interval(2, 5, is_valid=False) + assert a.is_valid is False + a = 1 + interval(2, 5, is_valid=None) + assert a.is_valid is None + a = interval(2, 5, is_valid=False) + interval(3, 5, is_valid=None) + assert a.is_valid is False + a = interval(3, 5) + interval(-1, 1, is_valid=None) + assert a.is_valid is None + a = interval(2, 5, is_valid=False) + 1 + assert a.is_valid is False + + +def test_interval_sub(): + assert (interval(1, 2) - interval(1, 5) == interval(-4, 1)) == (True, True) + assert (interval(1, 2) - 1 == interval(0, 1)) == (True, True) + assert (1 - interval(1, 2) == interval(-1, 0)) == (True, True) + a = 1 - interval(1, 2, is_valid=False) + assert a.is_valid is False + a = interval(1, 4, is_valid=None) - 1 + assert a.is_valid is None + a = interval(1, 3, is_valid=False) - interval(1, 3) + assert a.is_valid is False + a = interval(1, 3, is_valid=None) - interval(1, 3) + assert a.is_valid is None + + +def test_interval_inequality(): + assert (interval(1, 2) < interval(3, 4)) == (True, True) + assert (interval(1, 2) < interval(2, 4)) == (None, True) + assert (interval(1, 2) < interval(-2, 0)) == (False, True) + assert (interval(1, 2) <= interval(2, 4)) == (True, True) + assert (interval(1, 2) <= interval(1.5, 6)) == (None, True) + assert (interval(2, 3) <= interval(1, 2)) == (None, True) + assert (interval(2, 3) <= interval(1, 1.5)) == (False, True) + assert ( + interval(1, 2, is_valid=False) <= interval(-2, 0)) == (False, False) + assert (interval(1, 2, is_valid=None) <= interval(-2, 0)) == (False, None) + assert (interval(1, 2) <= 1.5) == (None, True) + assert (interval(1, 2) <= 3) == (True, True) + assert (interval(1, 2) <= 0) == (False, True) + assert (interval(5, 8) > interval(2, 3)) == (True, True) + assert (interval(2, 5) > interval(1, 3)) == (None, True) + assert (interval(2, 3) > interval(3.1, 5)) == (False, True) + + assert (interval(-1, 1) == 0) == (None, True) + assert (interval(-1, 1) == 2) == (False, True) + assert (interval(-1, 1) != 0) == (None, True) + assert (interval(-1, 1) != 2) == (True, True) + + assert (interval(3, 5) > 2) == (True, True) + assert (interval(3, 5) < 2) == (False, True) + assert (interval(1, 5) < 2) == (None, True) + assert (interval(1, 5) > 2) == (None, True) + assert (interval(0, 1) > 2) == (False, True) + assert (interval(1, 2) >= interval(0, 1)) == (True, True) + assert (interval(1, 2) >= interval(0, 1.5)) == (None, True) + assert (interval(1, 2) >= interval(3, 4)) == (False, True) + assert (interval(1, 2) >= 0) == (True, True) + assert (interval(1, 2) >= 1.2) == (None, True) + assert (interval(1, 2) >= 3) == (False, True) + assert (2 > interval(0, 1)) == (True, True) + a = interval(-1, 1, is_valid=False) < interval(2, 5, is_valid=None) + assert a == (True, False) + a = interval(-1, 1, is_valid=None) < interval(2, 5, is_valid=False) + assert a == (True, False) + a = interval(-1, 1, is_valid=None) < interval(2, 5, is_valid=None) + assert a == (True, None) + a = interval(-1, 1, is_valid=False) > interval(-5, -2, is_valid=None) + assert a == (True, False) + a = interval(-1, 1, is_valid=None) > interval(-5, -2, is_valid=False) + assert a == (True, False) + a = interval(-1, 1, is_valid=None) > interval(-5, -2, is_valid=None) + assert a == (True, None) + + +def test_interval_mul(): + assert ( + interval(1, 5) * interval(2, 10) == interval(2, 50)) == (True, True) + a = interval(-1, 1) * interval(2, 10) == interval(-10, 10) + assert a == (True, True) + + a = interval(-1, 1) * interval(-5, 3) == interval(-5, 5) + assert a == (True, True) + + assert (interval(1, 3) * 2 == interval(2, 6)) == (True, True) + assert (3 * interval(-1, 2) == interval(-3, 6)) == (True, True) + + a = 3 * interval(1, 2, is_valid=False) + assert a.is_valid is False + + a = 3 * interval(1, 2, is_valid=None) + assert a.is_valid is None + + a = interval(1, 5, is_valid=False) * interval(1, 2, is_valid=None) + assert a.is_valid is False + + +def test_interval_div(): + div = interval(1, 2, is_valid=False) / 3 + assert div == interval(-float('inf'), float('inf'), is_valid=False) + + div = interval(1, 2, is_valid=None) / 3 + assert div == interval(-float('inf'), float('inf'), is_valid=None) + + div = 3 / interval(1, 2, is_valid=None) + assert div == interval(-float('inf'), float('inf'), is_valid=None) + a = interval(1, 2) / 0 + assert a.is_valid is False + a = interval(0.5, 1) / interval(-1, 0) + assert a.is_valid is None + a = interval(0, 1) / interval(0, 1) + assert a.is_valid is None + + a = interval(-1, 1) / interval(-1, 1) + assert a.is_valid is None + + a = interval(-1, 2) / interval(0.5, 1) == interval(-2.0, 4.0) + assert a == (True, True) + a = interval(0, 1) / interval(0.5, 1) == interval(0.0, 2.0) + assert a == (True, True) + a = interval(-1, 0) / interval(0.5, 1) == interval(-2.0, 0.0) + assert a == (True, True) + a = interval(-0.5, -0.25) / interval(0.5, 1) == interval(-1.0, -0.25) + assert a == (True, True) + a = interval(0.5, 1) / interval(0.5, 1) == interval(0.5, 2.0) + assert a == (True, True) + a = interval(0.5, 4) / interval(0.5, 1) == interval(0.5, 8.0) + assert a == (True, True) + a = interval(-1, -0.5) / interval(0.5, 1) == interval(-2.0, -0.5) + assert a == (True, True) + a = interval(-4, -0.5) / interval(0.5, 1) == interval(-8.0, -0.5) + assert a == (True, True) + a = interval(-1, 2) / interval(-2, -0.5) == interval(-4.0, 2.0) + assert a == (True, True) + a = interval(0, 1) / interval(-2, -0.5) == interval(-2.0, 0.0) + assert a == (True, True) + a = interval(-1, 0) / interval(-2, -0.5) == interval(0.0, 2.0) + assert a == (True, True) + a = interval(-0.5, -0.25) / interval(-2, -0.5) == interval(0.125, 1.0) + assert a == (True, True) + a = interval(0.5, 1) / interval(-2, -0.5) == interval(-2.0, -0.25) + assert a == (True, True) + a = interval(0.5, 4) / interval(-2, -0.5) == interval(-8.0, -0.25) + assert a == (True, True) + a = interval(-1, -0.5) / interval(-2, -0.5) == interval(0.25, 2.0) + assert a == (True, True) + a = interval(-4, -0.5) / interval(-2, -0.5) == interval(0.25, 8.0) + assert a == (True, True) + a = interval(-5, 5, is_valid=False) / 2 + assert a.is_valid is False + +def test_hashable(): + ''' + test that interval objects are hashable. + this is required in order to be able to put them into the cache, which + appears to be necessary for plotting in py3k. For details, see: + + https://github.com/sympy/sympy/pull/2101 + https://github.com/sympy/sympy/issues/6533 + ''' + hash(interval(1, 1)) + hash(interval(1, 1, is_valid=True)) + hash(interval(-4, -0.5)) + hash(interval(-2, -0.5)) + hash(interval(0.25, 8.0)) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62eb2fca934b8ee65074b276585d2d9d7b6a79dd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a08313403d3c866ccf06ac4a534c0c78746f2f6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8517214c8829f4ab95b8123811a1c1b79953e832 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..487351f104392945c6b7ce4f5bbfbf30509c3615 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9f5335400b3037c95ef5fbcd669f5cb6210d6e1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8f2af6a22f399554c079b9f5b48b4cb1f859fe3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74e4d292ec4dedb7061b692982b9c33ebd08495d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6ce900b29f0a0e1b2d92e1f5c30604cfb7a86ad Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a459e05c23126c57e1df32d0c2d09af3cbd0d54a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82909cfc07b133d0b870208065a3e4f2842f0aa1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6f6c6a6414a28916f72d72a9f701f64a2d8a709 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea3b5545034adf4addfa5c406d262fb69b47893f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f860565ee549a7dceb71fd9956e758e02dc39ad3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df20eefa21f897b4ec841b4170f4bbbbb29fc76b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..707309aa2f1760b98a69f6d43d72572a868f2242 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ed2034e56dfe404446cda714178f6cef3c8e20b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/util.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c57cbe017c11bfd08c083ad14ea9a439a9813c82 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/util.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py new file mode 100644 index 0000000000000000000000000000000000000000..81fa2541b4dd9e13534aabfd2a11bf88c479daf8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py @@ -0,0 +1,106 @@ +from pyglet.window import Window +from pyglet.clock import Clock + +from threading import Thread, Lock + +gl_lock = Lock() + + +class ManagedWindow(Window): + """ + A pyglet window with an event loop which executes automatically + in a separate thread. Behavior is added by creating a subclass + which overrides setup, update, and/or draw. + """ + fps_limit = 30 + default_win_args = {"width": 600, + "height": 500, + "vsync": False, + "resizable": True} + + def __init__(self, **win_args): + """ + It is best not to override this function in the child + class, unless you need to take additional arguments. + Do any OpenGL initialization calls in setup(). + """ + + # check if this is run from the doctester + if win_args.get('runfromdoctester', False): + return + + self.win_args = dict(self.default_win_args, **win_args) + self.Thread = Thread(target=self.__event_loop__) + self.Thread.start() + + def __event_loop__(self, **win_args): + """ + The event loop thread function. Do not override or call + directly (it is called by __init__). + """ + gl_lock.acquire() + try: + try: + super().__init__(**self.win_args) + self.switch_to() + self.setup() + except Exception as e: + print("Window initialization failed: %s" % (str(e))) + self.has_exit = True + finally: + gl_lock.release() + + clock = Clock() + clock.fps_limit = self.fps_limit + while not self.has_exit: + dt = clock.tick() + gl_lock.acquire() + try: + try: + self.switch_to() + self.dispatch_events() + self.clear() + self.update(dt) + self.draw() + self.flip() + except Exception as e: + print("Uncaught exception in event loop: %s" % str(e)) + self.has_exit = True + finally: + gl_lock.release() + super().close() + + def close(self): + """ + Closes the window. + """ + self.has_exit = True + + def setup(self): + """ + Called once before the event loop begins. + Override this method in a child class. This + is the best place to put things like OpenGL + initialization calls. + """ + pass + + def update(self, dt): + """ + Called before draw during each iteration of + the event loop. dt is the elapsed time in + seconds since the last update. OpenGL rendering + calls are best put in draw() rather than here. + """ + pass + + def draw(self): + """ + Called after update during each iteration of + the event loop. Put OpenGL rendering calls + here. + """ + pass + +if __name__ == '__main__': + ManagedWindow() diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3dd3c8d4ce6c660cc07f93a55029eef98e55a2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py @@ -0,0 +1,464 @@ +from threading import RLock + +# it is sufficient to import "pyglet" here once +try: + import pyglet.gl as pgl +except ImportError: + raise ImportError("pyglet is required for plotting.\n " + "visit https://pyglet.org/") + +from sympy.core.numbers import Integer +from sympy.external.gmpy import SYMPY_INTS +from sympy.geometry.entity import GeometryEntity +from sympy.plotting.pygletplot.plot_axes import PlotAxes +from sympy.plotting.pygletplot.plot_mode import PlotMode +from sympy.plotting.pygletplot.plot_object import PlotObject +from sympy.plotting.pygletplot.plot_window import PlotWindow +from sympy.plotting.pygletplot.util import parse_option_string +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.iterables import is_sequence + +from time import sleep +from os import getcwd, listdir + +import ctypes + +@doctest_depends_on(modules=('pyglet',)) +class PygletPlot: + """ + Plot Examples + ============= + + See examples/advanced/pyglet_plotting.py for many more examples. + + >>> from sympy.plotting.pygletplot import PygletPlot as Plot + >>> from sympy.abc import x, y, z + + >>> Plot(x*y**3-y*x**3) + [0]: -x**3*y + x*y**3, 'mode=cartesian' + + >>> p = Plot() + >>> p[1] = x*y + >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4) + + >>> p = Plot() + >>> p[1] = x**2+y**2 + >>> p[2] = -x**2-y**2 + + + Variable Intervals + ================== + + The basic format is [var, min, max, steps], but the + syntax is flexible and arguments left out are taken + from the defaults for the current coordinate mode: + + >>> Plot(x**2) # implies [x,-5,5,100] + [0]: x**2, 'mode=cartesian' + >>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40] + [0]: x**2, 'mode=cartesian' + >>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100] + [0]: x**2 - y**2, 'mode=cartesian' + >>> Plot(x**2, [x,-13,13,100]) + [0]: x**2, 'mode=cartesian' + >>> Plot(x**2, [-13,13]) # [x,-13,13,100] + [0]: x**2, 'mode=cartesian' + >>> Plot(x**2, [x,-13,13]) # [x,-13,13,10] + [0]: x**2, 'mode=cartesian' + >>> Plot(1*x, [], [x], mode='cylindrical') + ... # [unbound_theta,0,2*Pi,40], [x,-1,1,20] + [0]: x, 'mode=cartesian' + + + Coordinate Modes + ================ + + Plot supports several curvilinear coordinate modes, and + they independent for each plotted function. You can specify + a coordinate mode explicitly with the 'mode' named argument, + but it can be automatically determined for Cartesian or + parametric plots, and therefore must only be specified for + polar, cylindrical, and spherical modes. + + Specifically, Plot(function arguments) and Plot[n] = + (function arguments) will interpret your arguments as a + Cartesian plot if you provide one function and a parametric + plot if you provide two or three functions. Similarly, the + arguments will be interpreted as a curve if one variable is + used, and a surface if two are used. + + Supported mode names by number of variables: + + 1: parametric, cartesian, polar + 2: parametric, cartesian, cylindrical = polar, spherical + + >>> Plot(1, mode='spherical') + + + Calculator-like Interface + ========================= + + >>> p = Plot(visible=False) + >>> f = x**2 + >>> p[1] = f + >>> p[2] = f.diff(x) + >>> p[3] = f.diff(x).diff(x) + >>> p + [1]: x**2, 'mode=cartesian' + [2]: 2*x, 'mode=cartesian' + [3]: 2, 'mode=cartesian' + >>> p.show() + >>> p.clear() + >>> p + + >>> p[1] = x**2+y**2 + >>> p[1].style = 'solid' + >>> p[2] = -x**2-y**2 + >>> p[2].style = 'wireframe' + >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4) + >>> p[1].style = 'both' + >>> p[2].style = 'both' + >>> p.close() + + + Plot Window Keyboard Controls + ============================= + + Screen Rotation: + X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2 + Z axis Q,E, Numpad 7,9 + + Model Rotation: + Z axis Z,C, Numpad 1,3 + + Zoom: R,F, PgUp,PgDn, Numpad +,- + + Reset Camera: X, Numpad 5 + + Camera Presets: + XY F1 + XZ F2 + YZ F3 + Perspective F4 + + Sensitivity Modifier: SHIFT + + Axes Toggle: + Visible F5 + Colors F6 + + Close Window: ESCAPE + + ============================= + + """ + + @doctest_depends_on(modules=('pyglet',)) + def __init__(self, *fargs, **win_args): + """ + Positional Arguments + ==================== + + Any given positional arguments are used to + initialize a plot function at index 1. In + other words... + + >>> from sympy.plotting.pygletplot import PygletPlot as Plot + >>> from sympy.abc import x + >>> p = Plot(x**2, visible=False) + + ...is equivalent to... + + >>> p = Plot(visible=False) + >>> p[1] = x**2 + + Note that in earlier versions of the plotting + module, you were able to specify multiple + functions in the initializer. This functionality + has been dropped in favor of better automatic + plot plot_mode detection. + + + Named Arguments + =============== + + axes + An option string of the form + "key1=value1; key2 = value2" which + can use the following options: + + style = ordinate + none OR frame OR box OR ordinate + + stride = 0.25 + val OR (val_x, val_y, val_z) + + overlay = True (draw on top of plot) + True OR False + + colored = False (False uses Black, + True uses colors + R,G,B = X,Y,Z) + True OR False + + label_axes = False (display axis names + at endpoints) + True OR False + + visible = True (show immediately + True OR False + + + The following named arguments are passed as + arguments to window initialization: + + antialiasing = True + True OR False + + ortho = False + True OR False + + invert_mouse_zoom = False + True OR False + + """ + # Register the plot modes + from . import plot_modes # noqa + + self._win_args = win_args + self._window = None + + self._render_lock = RLock() + + self._functions = {} + self._pobjects = [] + self._screenshot = ScreenShot(self) + + axe_options = parse_option_string(win_args.pop('axes', '')) + self.axes = PlotAxes(**axe_options) + self._pobjects.append(self.axes) + + self[0] = fargs + if win_args.get('visible', True): + self.show() + + ## Window Interfaces + + def show(self): + """ + Creates and displays a plot window, or activates it + (gives it focus) if it has already been created. + """ + if self._window and not self._window.has_exit: + self._window.activate() + else: + self._win_args['visible'] = True + self.axes.reset_resources() + + #if hasattr(self, '_doctest_depends_on'): + # self._win_args['runfromdoctester'] = True + + self._window = PlotWindow(self, **self._win_args) + + def close(self): + """ + Closes the plot window. + """ + if self._window: + self._window.close() + + def saveimage(self, outfile=None, format='', size=(600, 500)): + """ + Saves a screen capture of the plot window to an + image file. + + If outfile is given, it can either be a path + or a file object. Otherwise a png image will + be saved to the current working directory. + If the format is omitted, it is determined from + the filename extension. + """ + self._screenshot.save(outfile, format, size) + + ## Function List Interfaces + + def clear(self): + """ + Clears the function list of this plot. + """ + self._render_lock.acquire() + self._functions = {} + self.adjust_all_bounds() + self._render_lock.release() + + def __getitem__(self, i): + """ + Returns the function at position i in the + function list. + """ + return self._functions[i] + + def __setitem__(self, i, args): + """ + Parses and adds a PlotMode to the function + list. + """ + if not (isinstance(i, (SYMPY_INTS, Integer)) and i >= 0): + raise ValueError("Function index must " + "be an integer >= 0.") + + if isinstance(args, PlotObject): + f = args + else: + if (not is_sequence(args)) or isinstance(args, GeometryEntity): + args = [args] + if len(args) == 0: + return # no arguments given + kwargs = {"bounds_callback": self.adjust_all_bounds} + f = PlotMode(*args, **kwargs) + + if f: + self._render_lock.acquire() + self._functions[i] = f + self._render_lock.release() + else: + raise ValueError("Failed to parse '%s'." + % ', '.join(str(a) for a in args)) + + def __delitem__(self, i): + """ + Removes the function in the function list at + position i. + """ + self._render_lock.acquire() + del self._functions[i] + self.adjust_all_bounds() + self._render_lock.release() + + def firstavailableindex(self): + """ + Returns the first unused index in the function list. + """ + i = 0 + self._render_lock.acquire() + while i in self._functions: + i += 1 + self._render_lock.release() + return i + + def append(self, *args): + """ + Parses and adds a PlotMode to the function + list at the first available index. + """ + self.__setitem__(self.firstavailableindex(), args) + + def __len__(self): + """ + Returns the number of functions in the function list. + """ + return len(self._functions) + + def __iter__(self): + """ + Allows iteration of the function list. + """ + return self._functions.itervalues() + + def __repr__(self): + return str(self) + + def __str__(self): + """ + Returns a string containing a new-line separated + list of the functions in the function list. + """ + s = "" + if len(self._functions) == 0: + s += "" + else: + self._render_lock.acquire() + s += "\n".join(["%s[%i]: %s" % ("", i, str(self._functions[i])) + for i in self._functions]) + self._render_lock.release() + return s + + def adjust_all_bounds(self): + self._render_lock.acquire() + self.axes.reset_bounding_box() + for f in self._functions: + self.axes.adjust_bounds(self._functions[f].bounds) + self._render_lock.release() + + def wait_for_calculations(self): + sleep(0) + self._render_lock.acquire() + for f in self._functions: + a = self._functions[f]._get_calculating_verts + b = self._functions[f]._get_calculating_cverts + while a() or b(): + sleep(0) + self._render_lock.release() + +class ScreenShot: + def __init__(self, plot): + self._plot = plot + self.screenshot_requested = False + self.outfile = None + self.format = '' + self.invisibleMode = False + self.flag = 0 + + def __bool__(self): + return self.screenshot_requested + + def _execute_saving(self): + if self.flag < 3: + self.flag += 1 + return + + size_x, size_y = self._plot._window.get_size() + size = size_x*size_y*4*ctypes.sizeof(ctypes.c_ubyte) + image = ctypes.create_string_buffer(size) + pgl.glReadPixels(0, 0, size_x, size_y, pgl.GL_RGBA, pgl.GL_UNSIGNED_BYTE, image) + from PIL import Image + im = Image.frombuffer('RGBA', (size_x, size_y), + image.raw, 'raw', 'RGBA', 0, 1) + im.transpose(Image.FLIP_TOP_BOTTOM).save(self.outfile, self.format) + + self.flag = 0 + self.screenshot_requested = False + if self.invisibleMode: + self._plot._window.close() + + def save(self, outfile=None, format='', size=(600, 500)): + self.outfile = outfile + self.format = format + self.size = size + self.screenshot_requested = True + + if not self._plot._window or self._plot._window.has_exit: + self._plot._win_args['visible'] = False + + self._plot._win_args['width'] = size[0] + self._plot._win_args['height'] = size[1] + + self._plot.axes.reset_resources() + self._plot._window = PlotWindow(self._plot, **self._plot._win_args) + self.invisibleMode = True + + if self.outfile is None: + self.outfile = self._create_unique_path() + print(self.outfile) + + def _create_unique_path(self): + cwd = getcwd() + l = listdir(cwd) + path = '' + i = 0 + while True: + if not 'plot_%s.png' % i in l: + path = cwd + '/plot_%s.png' % i + break + i += 1 + return path diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..6b97dac843f58c76694d424f0b0b7e3499ba5202 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py @@ -0,0 +1,82 @@ +import pyglet.gl as pgl +from sympy.core import S +from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase + + +class PlotCurve(PlotModeBase): + + style_override = 'wireframe' + + def _on_calculate_verts(self): + self.t_interval = self.intervals[0] + self.t_set = list(self.t_interval.frange()) + self.bounds = [[S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0]] + evaluate = self._get_evaluator() + + self._calculating_verts_pos = 0.0 + self._calculating_verts_len = float(self.t_interval.v_len) + + self.verts = [] + b = self.bounds + for t in self.t_set: + try: + _e = evaluate(t) # calculate vertex + except (NameError, ZeroDivisionError): + _e = None + if _e is not None: # update bounding box + for axis in range(3): + b[axis][0] = min([b[axis][0], _e[axis]]) + b[axis][1] = max([b[axis][1], _e[axis]]) + self.verts.append(_e) + self._calculating_verts_pos += 1.0 + + for axis in range(3): + b[axis][2] = b[axis][1] - b[axis][0] + if b[axis][2] == 0.0: + b[axis][2] = 1.0 + + self.push_wireframe(self.draw_verts(False)) + + def _on_calculate_cverts(self): + if not self.verts or not self.color: + return + + def set_work_len(n): + self._calculating_cverts_len = float(n) + + def inc_work_pos(): + self._calculating_cverts_pos += 1.0 + set_work_len(1) + self._calculating_cverts_pos = 0 + self.cverts = self.color.apply_to_curve(self.verts, + self.t_set, + set_len=set_work_len, + inc_pos=inc_work_pos) + self.push_wireframe(self.draw_verts(True)) + + def calculate_one_cvert(self, t): + vert = self.verts[t] + return self.color(vert[0], vert[1], vert[2], + self.t_set[t], None) + + def draw_verts(self, use_cverts): + def f(): + pgl.glBegin(pgl.GL_LINE_STRIP) + for t in range(len(self.t_set)): + p = self.verts[t] + if p is None: + pgl.glEnd() + pgl.glBegin(pgl.GL_LINE_STRIP) + continue + if use_cverts: + c = self.cverts[t] + if c is None: + c = (0, 0, 0) + pgl.glColor3f(*c) + else: + pgl.glColor3f(*self.default_wireframe_color) + pgl.glVertex3f(*p) + pgl.glEnd() + return f diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2c6503650afda122e271bdecb2365c8fa20f2376 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py @@ -0,0 +1,378 @@ +import pyglet.gl as pgl +from sympy.core import S +from sympy.plotting.pygletplot.color_scheme import ColorScheme +from sympy.plotting.pygletplot.plot_mode import PlotMode +from sympy.utilities.iterables import is_sequence +from time import sleep +from threading import Thread, Event, RLock +import warnings + + +class PlotModeBase(PlotMode): + """ + Intended parent class for plotting + modes. Provides base functionality + in conjunction with its parent, + PlotMode. + """ + + ## + ## Class-Level Attributes + ## + + """ + The following attributes are meant + to be set at the class level, and serve + as parameters to the plot mode registry + (in PlotMode). See plot_modes.py for + concrete examples. + """ + + """ + i_vars + 'x' for Cartesian2D + 'xy' for Cartesian3D + etc. + + d_vars + 'y' for Cartesian2D + 'r' for Polar + etc. + """ + i_vars, d_vars = '', '' + + """ + intervals + Default intervals for each i_var, and in the + same order. Specified [min, max, steps]. + No variable can be given (it is bound later). + """ + intervals = [] + + """ + aliases + A list of strings which can be used to + access this mode. + 'cartesian' for Cartesian2D and Cartesian3D + 'polar' for Polar + 'cylindrical', 'polar' for Cylindrical + + Note that _init_mode chooses the first alias + in the list as the mode's primary_alias, which + will be displayed to the end user in certain + contexts. + """ + aliases = [] + + """ + is_default + Whether to set this mode as the default + for arguments passed to PlotMode() containing + the same number of d_vars as this mode and + at most the same number of i_vars. + """ + is_default = False + + """ + All of the above attributes are defined in PlotMode. + The following ones are specific to PlotModeBase. + """ + + """ + A list of the render styles. Do not modify. + """ + styles = {'wireframe': 1, 'solid': 2, 'both': 3} + + """ + style_override + Always use this style if not blank. + """ + style_override = '' + + """ + default_wireframe_color + default_solid_color + Can be used when color is None or being calculated. + Used by PlotCurve and PlotSurface, but not anywhere + in PlotModeBase. + """ + + default_wireframe_color = (0.85, 0.85, 0.85) + default_solid_color = (0.6, 0.6, 0.9) + default_rot_preset = 'xy' + + ## + ## Instance-Level Attributes + ## + + ## 'Abstract' member functions + def _get_evaluator(self): + if self.use_lambda_eval: + try: + e = self._get_lambda_evaluator() + return e + except Exception: + warnings.warn("\nWarning: creating lambda evaluator failed. " + "Falling back on SymPy subs evaluator.") + return self._get_sympy_evaluator() + + def _get_sympy_evaluator(self): + raise NotImplementedError() + + def _get_lambda_evaluator(self): + raise NotImplementedError() + + def _on_calculate_verts(self): + raise NotImplementedError() + + def _on_calculate_cverts(self): + raise NotImplementedError() + + ## Base member functions + def __init__(self, *args, bounds_callback=None, **kwargs): + self.verts = [] + self.cverts = [] + self.bounds = [[S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0]] + self.cbounds = [[S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0]] + + self._draw_lock = RLock() + + self._calculating_verts = Event() + self._calculating_cverts = Event() + self._calculating_verts_pos = 0.0 + self._calculating_verts_len = 0.0 + self._calculating_cverts_pos = 0.0 + self._calculating_cverts_len = 0.0 + + self._max_render_stack_size = 3 + self._draw_wireframe = [-1] + self._draw_solid = [-1] + + self._style = None + self._color = None + + self.predraw = [] + self.postdraw = [] + + self.use_lambda_eval = self.options.pop('use_sympy_eval', None) is None + self.style = self.options.pop('style', '') + self.color = self.options.pop('color', 'rainbow') + self.bounds_callback = bounds_callback + + self._on_calculate() + + def synchronized(f): + def w(self, *args, **kwargs): + self._draw_lock.acquire() + try: + r = f(self, *args, **kwargs) + return r + finally: + self._draw_lock.release() + return w + + @synchronized + def push_wireframe(self, function): + """ + Push a function which performs gl commands + used to build a display list. (The list is + built outside of the function) + """ + assert callable(function) + self._draw_wireframe.append(function) + if len(self._draw_wireframe) > self._max_render_stack_size: + del self._draw_wireframe[1] # leave marker element + + @synchronized + def push_solid(self, function): + """ + Push a function which performs gl commands + used to build a display list. (The list is + built outside of the function) + """ + assert callable(function) + self._draw_solid.append(function) + if len(self._draw_solid) > self._max_render_stack_size: + del self._draw_solid[1] # leave marker element + + def _create_display_list(self, function): + dl = pgl.glGenLists(1) + pgl.glNewList(dl, pgl.GL_COMPILE) + function() + pgl.glEndList() + return dl + + def _render_stack_top(self, render_stack): + top = render_stack[-1] + if top == -1: + return -1 # nothing to display + elif callable(top): + dl = self._create_display_list(top) + render_stack[-1] = (dl, top) + return dl # display newly added list + elif len(top) == 2: + if pgl.GL_TRUE == pgl.glIsList(top[0]): + return top[0] # display stored list + dl = self._create_display_list(top[1]) + render_stack[-1] = (dl, top[1]) + return dl # display regenerated list + + def _draw_solid_display_list(self, dl): + pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT) + pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL) + pgl.glCallList(dl) + pgl.glPopAttrib() + + def _draw_wireframe_display_list(self, dl): + pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT) + pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE) + pgl.glEnable(pgl.GL_POLYGON_OFFSET_LINE) + pgl.glPolygonOffset(-0.005, -50.0) + pgl.glCallList(dl) + pgl.glPopAttrib() + + @synchronized + def draw(self): + for f in self.predraw: + if callable(f): + f() + if self.style_override: + style = self.styles[self.style_override] + else: + style = self.styles[self._style] + # Draw solid component if style includes solid + if style & 2: + dl = self._render_stack_top(self._draw_solid) + if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl): + self._draw_solid_display_list(dl) + # Draw wireframe component if style includes wireframe + if style & 1: + dl = self._render_stack_top(self._draw_wireframe) + if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl): + self._draw_wireframe_display_list(dl) + for f in self.postdraw: + if callable(f): + f() + + def _on_change_color(self, color): + Thread(target=self._calculate_cverts).start() + + def _on_calculate(self): + Thread(target=self._calculate_all).start() + + def _calculate_all(self): + self._calculate_verts() + self._calculate_cverts() + + def _calculate_verts(self): + if self._calculating_verts.is_set(): + return + self._calculating_verts.set() + try: + self._on_calculate_verts() + finally: + self._calculating_verts.clear() + if callable(self.bounds_callback): + self.bounds_callback() + + def _calculate_cverts(self): + if self._calculating_verts.is_set(): + return + while self._calculating_cverts.is_set(): + sleep(0) # wait for previous calculation + self._calculating_cverts.set() + try: + self._on_calculate_cverts() + finally: + self._calculating_cverts.clear() + + def _get_calculating_verts(self): + return self._calculating_verts.is_set() + + def _get_calculating_verts_pos(self): + return self._calculating_verts_pos + + def _get_calculating_verts_len(self): + return self._calculating_verts_len + + def _get_calculating_cverts(self): + return self._calculating_cverts.is_set() + + def _get_calculating_cverts_pos(self): + return self._calculating_cverts_pos + + def _get_calculating_cverts_len(self): + return self._calculating_cverts_len + + ## Property handlers + def _get_style(self): + return self._style + + @synchronized + def _set_style(self, v): + if v is None: + return + if v == '': + step_max = 0 + for i in self.intervals: + if i.v_steps is None: + continue + step_max = max([step_max, int(i.v_steps)]) + v = ['both', 'solid'][step_max > 40] + if v not in self.styles: + raise ValueError("v should be there in self.styles") + if v == self._style: + return + self._style = v + + def _get_color(self): + return self._color + + @synchronized + def _set_color(self, v): + try: + if v is not None: + if is_sequence(v): + v = ColorScheme(*v) + else: + v = ColorScheme(v) + if repr(v) == repr(self._color): + return + self._on_change_color(v) + self._color = v + except Exception as e: + raise RuntimeError("Color change failed. " + "Reason: %s" % (str(e))) + + style = property(_get_style, _set_style) + color = property(_get_color, _set_color) + + calculating_verts = property(_get_calculating_verts) + calculating_verts_pos = property(_get_calculating_verts_pos) + calculating_verts_len = property(_get_calculating_verts_len) + + calculating_cverts = property(_get_calculating_cverts) + calculating_cverts_pos = property(_get_calculating_cverts_pos) + calculating_cverts_len = property(_get_calculating_cverts_len) + + ## String representations + + def __str__(self): + f = ", ".join(str(d) for d in self.d_vars) + o = "'mode=%s'" % (self.primary_alias) + return ", ".join([f, o]) + + def __repr__(self): + f = ", ".join(str(d) for d in self.d_vars) + i = ", ".join(str(i) for i in self.intervals) + d = [('mode', self.primary_alias), + ('color', str(self.color)), + ('style', str(self.style))] + + o = "'%s'" % ("; ".join("%s=%s" % (k, v) + for k, v in d if v != 'None')) + return ", ".join([f, i, o]) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..7f568964997634121946a761b55ef0f916ac633f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py @@ -0,0 +1,68 @@ +try: + from ctypes import c_float +except ImportError: + pass + +import pyglet.gl as pgl +from math import sqrt as _sqrt, acos as _acos + + +def cross(a, b): + return (a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]) + + +def dot(a, b): + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + + +def mag(a): + return _sqrt(a[0]**2 + a[1]**2 + a[2]**2) + + +def norm(a): + m = mag(a) + return (a[0] / m, a[1] / m, a[2] / m) + + +def get_sphere_mapping(x, y, width, height): + x = min([max([x, 0]), width]) + y = min([max([y, 0]), height]) + + sr = _sqrt((width/2)**2 + (height/2)**2) + sx = ((x - width / 2) / sr) + sy = ((y - height / 2) / sr) + + sz = 1.0 - sx**2 - sy**2 + + if sz > 0.0: + sz = _sqrt(sz) + return (sx, sy, sz) + else: + sz = 0 + return norm((sx, sy, sz)) + +rad2deg = 180.0 / 3.141592 + + +def get_spherical_rotatation(p1, p2, width, height, theta_multiplier): + v1 = get_sphere_mapping(p1[0], p1[1], width, height) + v2 = get_sphere_mapping(p2[0], p2[1], width, height) + + d = min(max([dot(v1, v2), -1]), 1) + + if abs(d - 1.0) < 0.000001: + return None + + raxis = norm( cross(v1, v2) ) + rtheta = theta_multiplier * rad2deg * _acos(d) + + pgl.glPushMatrix() + pgl.glLoadIdentity() + pgl.glRotatef(rtheta, *raxis) + mat = (c_float*16)() + pgl.glGetFloatv(pgl.GL_MODELVIEW_MATRIX, mat) + pgl.glPopMatrix() + + return mat diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py new file mode 100644 index 0000000000000000000000000000000000000000..d9df4cc453acb05d7c2d871e9e8efeb36905de5d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py @@ -0,0 +1,144 @@ +from time import perf_counter + + +import pyglet.gl as pgl + +from sympy.plotting.pygletplot.managed_window import ManagedWindow +from sympy.plotting.pygletplot.plot_camera import PlotCamera +from sympy.plotting.pygletplot.plot_controller import PlotController + + +class PlotWindow(ManagedWindow): + + def __init__(self, plot, antialiasing=True, ortho=False, + invert_mouse_zoom=False, linewidth=1.5, caption="SymPy Plot", + **kwargs): + """ + Named Arguments + =============== + + antialiasing = True + True OR False + ortho = False + True OR False + invert_mouse_zoom = False + True OR False + """ + self.plot = plot + + self.camera = None + self._calculating = False + + self.antialiasing = antialiasing + self.ortho = ortho + self.invert_mouse_zoom = invert_mouse_zoom + self.linewidth = linewidth + self.title = caption + self.last_caption_update = 0 + self.caption_update_interval = 0.2 + self.drawing_first_object = True + + super().__init__(**kwargs) + + def setup(self): + self.camera = PlotCamera(self, ortho=self.ortho) + self.controller = PlotController(self, + invert_mouse_zoom=self.invert_mouse_zoom) + self.push_handlers(self.controller) + + pgl.glClearColor(1.0, 1.0, 1.0, 0.0) + pgl.glClearDepth(1.0) + + pgl.glDepthFunc(pgl.GL_LESS) + pgl.glEnable(pgl.GL_DEPTH_TEST) + + pgl.glEnable(pgl.GL_LINE_SMOOTH) + pgl.glShadeModel(pgl.GL_SMOOTH) + pgl.glLineWidth(self.linewidth) + + pgl.glEnable(pgl.GL_BLEND) + pgl.glBlendFunc(pgl.GL_SRC_ALPHA, pgl.GL_ONE_MINUS_SRC_ALPHA) + + if self.antialiasing: + pgl.glHint(pgl.GL_LINE_SMOOTH_HINT, pgl.GL_NICEST) + pgl.glHint(pgl.GL_POLYGON_SMOOTH_HINT, pgl.GL_NICEST) + + self.camera.setup_projection() + + def on_resize(self, w, h): + super().on_resize(w, h) + if self.camera is not None: + self.camera.setup_projection() + + def update(self, dt): + self.controller.update(dt) + + def draw(self): + self.plot._render_lock.acquire() + self.camera.apply_transformation() + + calc_verts_pos, calc_verts_len = 0, 0 + calc_cverts_pos, calc_cverts_len = 0, 0 + + should_update_caption = (perf_counter() - self.last_caption_update > + self.caption_update_interval) + + if len(self.plot._functions.values()) == 0: + self.drawing_first_object = True + + iterfunctions = iter(self.plot._functions.values()) + + for r in iterfunctions: + if self.drawing_first_object: + self.camera.set_rot_preset(r.default_rot_preset) + self.drawing_first_object = False + + pgl.glPushMatrix() + r._draw() + pgl.glPopMatrix() + + # might as well do this while we are + # iterating and have the lock rather + # than locking and iterating twice + # per frame: + + if should_update_caption: + try: + if r.calculating_verts: + calc_verts_pos += r.calculating_verts_pos + calc_verts_len += r.calculating_verts_len + if r.calculating_cverts: + calc_cverts_pos += r.calculating_cverts_pos + calc_cverts_len += r.calculating_cverts_len + except ValueError: + pass + + for r in self.plot._pobjects: + pgl.glPushMatrix() + r._draw() + pgl.glPopMatrix() + + if should_update_caption: + self.update_caption(calc_verts_pos, calc_verts_len, + calc_cverts_pos, calc_cverts_len) + self.last_caption_update = perf_counter() + + if self.plot._screenshot: + self.plot._screenshot._execute_saving() + + self.plot._render_lock.release() + + def update_caption(self, calc_verts_pos, calc_verts_len, + calc_cverts_pos, calc_cverts_len): + caption = self.title + if calc_verts_len or calc_cverts_len: + caption += " (calculating" + if calc_verts_len > 0: + p = (calc_verts_pos / calc_verts_len) * 100 + caption += " vertices %i%%" % (p) + if calc_cverts_len > 0: + p = (calc_cverts_pos / calc_cverts_len) * 100 + caption += " colors %i%%" % (p) + caption += ")" + if self.caption != caption: + self.set_caption(caption) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..792aab1035f7867b9a7e43759e10f23dd5d3d84c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b4367b34c88098031d493996ea8ac7cf5d4930f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc4aaf3621a8c9056ce0d81c89ca6a0a681bbdb --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py @@ -0,0 +1,88 @@ +from sympy.external.importtools import import_module + +disabled = False + +# if pyglet.gl fails to import, e.g. opengl is missing, we disable the tests +pyglet_gl = import_module("pyglet.gl", catch=(OSError,)) +pyglet_window = import_module("pyglet.window", catch=(OSError,)) +if not pyglet_gl or not pyglet_window: + disabled = True + + +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.trigonometric import (cos, sin) +x, y, z = symbols('x, y, z') + + +def test_plot_2d(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(x, [x, -5, 5, 4], visible=False) + p.wait_for_calculations() + + +def test_plot_2d_discontinuous(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(1/x, [x, -1, 1, 2], visible=False) + p.wait_for_calculations() + + +def test_plot_3d(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(x*y, [x, -5, 5, 5], [y, -5, 5, 5], visible=False) + p.wait_for_calculations() + + +def test_plot_3d_discontinuous(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(1/x, [x, -3, 3, 6], [y, -1, 1, 1], visible=False) + p.wait_for_calculations() + + +def test_plot_2d_polar(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(1/x, [x, -1, 1, 4], 'mode=polar', visible=False) + p.wait_for_calculations() + + +def test_plot_3d_cylinder(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot( + 1/y, [x, 0, 6.282, 4], [y, -1, 1, 4], 'mode=polar;style=solid', + visible=False) + p.wait_for_calculations() + + +def test_plot_3d_spherical(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot( + 1, [x, 0, 6.282, 4], [y, 0, 3.141, + 4], 'mode=spherical;style=wireframe', + visible=False) + p.wait_for_calculations() + + +def test_plot_2d_parametric(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(sin(x), cos(x), [x, 0, 6.282, 4], visible=False) + p.wait_for_calculations() + + +def test_plot_3d_parametric(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(sin(x), cos(x), x/5.0, [x, 0, 6.282, 4], visible=False) + p.wait_for_calculations() + + +def _test_plot_log(): + from sympy.plotting.pygletplot import PygletPlot + p = PygletPlot(log(x), [x, 0, 6.282, 4], 'mode=polar', visible=False) + p.wait_for_calculations() + + +def test_plot_integral(): + # Make sure it doesn't treat x as an independent variable + from sympy.plotting.pygletplot import PygletPlot + from sympy.integrals.integrals import Integral + p = PygletPlot(Integral(z*x, (x, 1, z), (z, 1, y)), visible=False) + p.wait_for_calculations() diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/util.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/util.py new file mode 100644 index 0000000000000000000000000000000000000000..43b882ca18274dcdb273cf35680016453db3c698 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/pygletplot/util.py @@ -0,0 +1,188 @@ +try: + from ctypes import c_float, c_int, c_double +except ImportError: + pass + +import pyglet.gl as pgl +from sympy.core import S + + +def get_model_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv): + """ + Returns the current modelview matrix. + """ + m = (array_type*16)() + glGetMethod(pgl.GL_MODELVIEW_MATRIX, m) + return m + + +def get_projection_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv): + """ + Returns the current modelview matrix. + """ + m = (array_type*16)() + glGetMethod(pgl.GL_PROJECTION_MATRIX, m) + return m + + +def get_viewport(): + """ + Returns the current viewport. + """ + m = (c_int*4)() + pgl.glGetIntegerv(pgl.GL_VIEWPORT, m) + return m + + +def get_direction_vectors(): + m = get_model_matrix() + return ((m[0], m[4], m[8]), + (m[1], m[5], m[9]), + (m[2], m[6], m[10])) + + +def get_view_direction_vectors(): + m = get_model_matrix() + return ((m[0], m[1], m[2]), + (m[4], m[5], m[6]), + (m[8], m[9], m[10])) + + +def get_basis_vectors(): + return ((1, 0, 0), (0, 1, 0), (0, 0, 1)) + + +def screen_to_model(x, y, z): + m = get_model_matrix(c_double, pgl.glGetDoublev) + p = get_projection_matrix(c_double, pgl.glGetDoublev) + w = get_viewport() + mx, my, mz = c_double(), c_double(), c_double() + pgl.gluUnProject(x, y, z, m, p, w, mx, my, mz) + return float(mx.value), float(my.value), float(mz.value) + + +def model_to_screen(x, y, z): + m = get_model_matrix(c_double, pgl.glGetDoublev) + p = get_projection_matrix(c_double, pgl.glGetDoublev) + w = get_viewport() + mx, my, mz = c_double(), c_double(), c_double() + pgl.gluProject(x, y, z, m, p, w, mx, my, mz) + return float(mx.value), float(my.value), float(mz.value) + + +def vec_subs(a, b): + return tuple(a[i] - b[i] for i in range(len(a))) + + +def billboard_matrix(): + """ + Removes rotational components of + current matrix so that primitives + are always drawn facing the viewer. + + |1|0|0|x| + |0|1|0|x| + |0|0|1|x| (x means left unchanged) + |x|x|x|x| + """ + m = get_model_matrix() + # XXX: for i in range(11): m[i] = i ? + m[0] = 1 + m[1] = 0 + m[2] = 0 + m[4] = 0 + m[5] = 1 + m[6] = 0 + m[8] = 0 + m[9] = 0 + m[10] = 1 + pgl.glLoadMatrixf(m) + + +def create_bounds(): + return [[S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0], + [S.Infinity, S.NegativeInfinity, 0]] + + +def update_bounds(b, v): + if v is None: + return + for axis in range(3): + b[axis][0] = min([b[axis][0], v[axis]]) + b[axis][1] = max([b[axis][1], v[axis]]) + + +def interpolate(a_min, a_max, a_ratio): + return a_min + a_ratio * (a_max - a_min) + + +def rinterpolate(a_min, a_max, a_value): + a_range = a_max - a_min + if a_max == a_min: + a_range = 1.0 + return (a_value - a_min) / float(a_range) + + +def interpolate_color(color1, color2, ratio): + return tuple(interpolate(color1[i], color2[i], ratio) for i in range(3)) + + +def scale_value(v, v_min, v_len): + return (v - v_min) / v_len + + +def scale_value_list(flist): + v_min, v_max = min(flist), max(flist) + v_len = v_max - v_min + return [scale_value(f, v_min, v_len) for f in flist] + + +def strided_range(r_min, r_max, stride, max_steps=50): + o_min, o_max = r_min, r_max + if abs(r_min - r_max) < 0.001: + return [] + try: + range(int(r_min - r_max)) + except (TypeError, OverflowError): + return [] + if r_min > r_max: + raise ValueError("r_min cannot be greater than r_max") + r_min_s = (r_min % stride) + r_max_s = stride - (r_max % stride) + if abs(r_max_s - stride) < 0.001: + r_max_s = 0.0 + r_min -= r_min_s + r_max += r_max_s + r_steps = int((r_max - r_min)/stride) + if max_steps and r_steps > max_steps: + return strided_range(o_min, o_max, stride*2) + return [r_min] + [r_min + e*stride for e in range(1, r_steps + 1)] + [r_max] + + +def parse_option_string(s): + if not isinstance(s, str): + return None + options = {} + for token in s.split(';'): + pieces = token.split('=') + if len(pieces) == 1: + option, value = pieces[0], "" + elif len(pieces) == 2: + option, value = pieces + else: + raise ValueError("Plot option string '%s' is malformed." % (s)) + options[option.strip()] = value.strip() + return options + + +def dot_product(v1, v2): + return sum(v1[i]*v2[i] for i in range(3)) + + +def vec_sub(v1, v2): + return tuple(v1[i] - v2[i] for i in range(3)) + + +def vec_mag(v): + return sum(v[i]**2 for i in range(3))**(0.5) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68cde185db0a4d832916350800af0ee10d54e1c2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_experimental_lambdify.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_experimental_lambdify.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acc0637f28a96deab08de555e1c2f90a1c1ae10d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_experimental_lambdify.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4098ea79f177c82f7ae9ee62466ee952505e784 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot_implicit.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot_implicit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..944012b380f3be068503c21ed60cc45dcc47092b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_plot_implicit.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_textplot.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_textplot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e98a070b1926d5a789fd94caf79ca3e55a13cc45 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_textplot.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_experimental_lambdify.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_experimental_lambdify.py new file mode 100644 index 0000000000000000000000000000000000000000..95839d668762be7be94d0de5092594306ceeadbd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_experimental_lambdify.py @@ -0,0 +1,77 @@ +from sympy.core.symbol import symbols, Symbol +from sympy.functions import Max +from sympy.plotting.experimental_lambdify import experimental_lambdify +from sympy.plotting.intervalmath.interval_arithmetic import \ + interval, intervalMembership + + +# Tests for exception handling in experimental_lambdify +def test_experimental_lambify(): + x = Symbol('x') + f = experimental_lambdify([x], Max(x, 5)) + # XXX should f be tested? If f(2) is attempted, an + # error is raised because a complex produced during wrapping of the arg + # is being compared with an int. + assert Max(2, 5) == 5 + assert Max(5, 7) == 7 + + x = Symbol('x-3') + f = experimental_lambdify([x], x + 1) + assert f(1) == 2 + + +def test_composite_boolean_region(): + x, y = symbols('x y') + + r1 = (x - 1)**2 + y**2 < 2 + r2 = (x + 1)**2 + y**2 < 2 + + f = experimental_lambdify((x, y), r1 & r2) + a = (interval(-0.1, 0.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(True, True) + a = (interval(-1.1, -0.9), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(0.9, 1.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(-0.1, 0.1), interval(1.9, 2.1)) + assert f(*a) == intervalMembership(False, True) + + f = experimental_lambdify((x, y), r1 | r2) + a = (interval(-0.1, 0.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(True, True) + a = (interval(-1.1, -0.9), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(True, True) + a = (interval(0.9, 1.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(True, True) + a = (interval(-0.1, 0.1), interval(1.9, 2.1)) + assert f(*a) == intervalMembership(False, True) + + f = experimental_lambdify((x, y), r1 & ~r2) + a = (interval(-0.1, 0.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(-1.1, -0.9), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(0.9, 1.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(True, True) + a = (interval(-0.1, 0.1), interval(1.9, 2.1)) + assert f(*a) == intervalMembership(False, True) + + f = experimental_lambdify((x, y), ~r1 & r2) + a = (interval(-0.1, 0.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(-1.1, -0.9), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(True, True) + a = (interval(0.9, 1.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(-0.1, 0.1), interval(1.9, 2.1)) + assert f(*a) == intervalMembership(False, True) + + f = experimental_lambdify((x, y), ~r1 & ~r2) + a = (interval(-0.1, 0.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(-1.1, -0.9), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(0.9, 1.1), interval(-0.1, 0.1)) + assert f(*a) == intervalMembership(False, True) + a = (interval(-0.1, 0.1), interval(1.9, 2.1)) + assert f(*a) == intervalMembership(True, True) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_plot.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..d54caf428cd2e64616ee855cddc4adf9d07743f7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_plot.py @@ -0,0 +1,764 @@ +import os +from tempfile import TemporaryDirectory + +from sympy.concrete.summations import Sum +from sympy.core.numbers import (I, oo, pi) +from sympy.core.relational import Ne +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log) +from sympy.functions.elementary.miscellaneous import (real_root, sqrt) +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.hyper import meijerg +from sympy.integrals.integrals import Integral +from sympy.logic.boolalg import And +from sympy.core.singleton import S +from sympy.core.sympify import sympify +from sympy.external import import_module +from sympy.plotting.plot import ( + Plot, plot, plot_parametric, plot3d_parametric_line, plot3d, + plot3d_parametric_surface) +from sympy.plotting.plot import ( + unset_show, plot_contour, PlotGrid, DefaultBackend, MatplotlibBackend, + TextBackend, BaseBackend) +from sympy.testing.pytest import skip, raises, warns, warns_deprecated_sympy +from sympy.utilities import lambdify as lambdify_ +from sympy.utilities.exceptions import ignore_warnings + + +unset_show() + + +matplotlib = import_module( + 'matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) + + +class DummyBackendNotOk(BaseBackend): + """ Used to verify if users can create their own backends. + This backend is meant to raise NotImplementedError for methods `show`, + `save`, `close`. + """ + pass + + +class DummyBackendOk(BaseBackend): + """ Used to verify if users can create their own backends. + This backend is meant to pass all tests. + """ + def show(self): + pass + + def save(self): + pass + + def close(self): + pass + + +def test_plot_and_save_1(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + y = Symbol('y') + + with TemporaryDirectory(prefix='sympy_') as tmpdir: + ### + # Examples from the 'introduction' notebook + ### + p = plot(x, legend=True, label='f1') + p = plot(x*sin(x), x*cos(x), label='f2') + p.extend(p) + p[0].line_color = lambda a: a + p[1].line_color = 'b' + p.title = 'Big title' + p.xlabel = 'the x axis' + p[1].label = 'straight line' + p.legend = True + p.aspect_ratio = (1, 1) + p.xlim = (-15, 20) + filename = 'test_basic_options_and_colors.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p.extend(plot(x + 1)) + p.append(plot(x + 3, x**2)[1]) + filename = 'test_plot_extend_append.png' + p.save(os.path.join(tmpdir, filename)) + + p[2] = plot(x**2, (x, -2, 3)) + filename = 'test_plot_setitem.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot(sin(x), (x, -2*pi, 4*pi)) + filename = 'test_line_explicit.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot(sin(x)) + filename = 'test_line_default_range.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) + filename = 'test_line_multiple_range.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + raises(ValueError, lambda: plot(x, y)) + + #Piecewise plots + p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1)) + filename = 'test_plot_piecewise.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3)) + filename = 'test_plot_piecewise_2.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # test issue 7471 + p1 = plot(x) + p2 = plot(3) + p1.extend(p2) + filename = 'test_horizontal_line.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # test issue 10925 + f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \ + (x**2, And(0 <= x, x < 1)), (x**3, x >= 1)) + p = plot(f, (x, -3, 3)) + filename = 'test_plot_piecewise_3.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + +def test_plot_and_save_2(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + y = Symbol('y') + z = Symbol('z') + + with TemporaryDirectory(prefix='sympy_') as tmpdir: + #parametric 2d plots. + #Single plot with default range. + p = plot_parametric(sin(x), cos(x)) + filename = 'test_parametric.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + #Single plot with range. + p = plot_parametric( + sin(x), cos(x), (x, -5, 5), legend=True, label='parametric_plot') + filename = 'test_parametric_range.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + #Multiple plots with same range. + p = plot_parametric((sin(x), cos(x)), (x, sin(x))) + filename = 'test_parametric_multiple.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + #Multiple plots with different ranges. + p = plot_parametric( + (sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5))) + filename = 'test_parametric_multiple_ranges.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + #depth of recursion specified. + p = plot_parametric(x, sin(x), depth=13) + filename = 'test_recursion_depth.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + #No adaptive sampling. + p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500) + filename = 'test_adaptive.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + #3d parametric plots + p = plot3d_parametric_line( + sin(x), cos(x), x, legend=True, label='3d_parametric_plot') + filename = 'test_3d_line.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot3d_parametric_line( + (sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3))) + filename = 'test_3d_line_multiple.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30) + filename = 'test_3d_line_points.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # 3d surface single plot. + p = plot3d(x * y) + filename = 'test_surface.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Multiple 3D plots with same range. + p = plot3d(-x * y, x * y, (x, -5, 5)) + filename = 'test_surface_multiple.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Multiple 3D plots with different ranges. + p = plot3d( + (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) + filename = 'test_surface_multiple_ranges.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Single Parametric 3D plot + p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y) + filename = 'test_parametric_surface.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Multiple Parametric 3D plots. + p = plot3d_parametric_surface( + (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)), + (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) + filename = 'test_parametric_surface.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Single Contour plot. + p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5)) + filename = 'test_contour_plot.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Multiple Contour plots with same range. + p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5)) + filename = 'test_contour_plot.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # Multiple Contour plots with different range. + p = plot_contour( + (x**2 + y**2, (x, -5, 5), (y, -5, 5)), + (x**3 + y**3, (x, -3, 3), (y, -3, 3))) + filename = 'test_contour_plot.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + +def test_plot_and_save_3(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + y = Symbol('y') + z = Symbol('z') + + with TemporaryDirectory(prefix='sympy_') as tmpdir: + ### + # Examples from the 'colors' notebook + ### + + p = plot(sin(x)) + p[0].line_color = lambda a: a + filename = 'test_colors_line_arity1.png' + p.save(os.path.join(tmpdir, filename)) + + p[0].line_color = lambda a, b: b + filename = 'test_colors_line_arity2.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot(x*sin(x), x*cos(x), (x, 0, 10)) + p[0].line_color = lambda a: a + filename = 'test_colors_param_line_arity1.png' + p.save(os.path.join(tmpdir, filename)) + + p[0].line_color = lambda a, b: a + filename = 'test_colors_param_line_arity1.png' + p.save(os.path.join(tmpdir, filename)) + + p[0].line_color = lambda a, b: b + filename = 'test_colors_param_line_arity2b.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x), + cos(x) + 0.1*cos(x)*cos(7*x), + 0.1*sin(7*x), + (x, 0, 2*pi)) + p[0].line_color = lambdify_(x, sin(4*x)) + filename = 'test_colors_3d_line_arity1.png' + p.save(os.path.join(tmpdir, filename)) + p[0].line_color = lambda a, b: b + filename = 'test_colors_3d_line_arity2.png' + p.save(os.path.join(tmpdir, filename)) + p[0].line_color = lambda a, b, c: c + filename = 'test_colors_3d_line_arity3.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5)) + p[0].surface_color = lambda a: a + filename = 'test_colors_surface_arity1.png' + p.save(os.path.join(tmpdir, filename)) + p[0].surface_color = lambda a, b: b + filename = 'test_colors_surface_arity2.png' + p.save(os.path.join(tmpdir, filename)) + p[0].surface_color = lambda a, b, c: c + filename = 'test_colors_surface_arity3a.png' + p.save(os.path.join(tmpdir, filename)) + p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2)) + filename = 'test_colors_surface_arity3b.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y, + (x, -1, 1), (y, -1, 1)) + p[0].surface_color = lambda a: a + filename = 'test_colors_param_surf_arity1.png' + p.save(os.path.join(tmpdir, filename)) + p[0].surface_color = lambda a, b: a*b + filename = 'test_colors_param_surf_arity2.png' + p.save(os.path.join(tmpdir, filename)) + p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2)) + filename = 'test_colors_param_surf_arity3.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + +def test_plot_and_save_4(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + y = Symbol('y') + + ### + # Examples from the 'advanced' notebook + ### + + # XXX: This raises the warning "The evaluation of the expression is + # problematic. We are trying a failback method that may still work. Please + # report this as a bug." It has to use the fallback because using evalf() + # is the only way to evaluate the integral. We should perhaps just remove + # that warning. + with TemporaryDirectory(prefix='sympy_') as tmpdir: + with warns( + UserWarning, + match="The evaluation of the expression is problematic", + test_stacklevel=False, + ): + i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y)) + p = plot(i, (y, 1, 5)) + filename = 'test_advanced_integral.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + +def test_plot_and_save_5(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + y = Symbol('y') + + with TemporaryDirectory(prefix='sympy_') as tmpdir: + s = Sum(1/x**y, (x, 1, oo)) + p = plot(s, (y, 2, 10)) + filename = 'test_advanced_inf_sum.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False) + p[0].only_integers = True + p[0].steps = True + filename = 'test_advanced_fin_sum.png' + + # XXX: This should be fixed in experimental_lambdify or by using + # ordinary lambdify so that it doesn't warn. The error results from + # passing an array of values as the integration limit. + # + # UserWarning: The evaluation of the expression is problematic. We are + # trying a failback method that may still work. Please report this as a + # bug. + with ignore_warnings(UserWarning): + p.save(os.path.join(tmpdir, filename)) + + p._backend.close() + + +def test_plot_and_save_6(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + + with TemporaryDirectory(prefix='sympy_') as tmpdir: + filename = 'test.png' + ### + # Test expressions that can not be translated to np and generate complex + # results. + ### + p = plot(sin(x) + I*cos(x)) + p.save(os.path.join(tmpdir, filename)) + + with ignore_warnings(RuntimeWarning): + p = plot(sqrt(sqrt(-x))) + p.save(os.path.join(tmpdir, filename)) + + p = plot(LambertW(x)) + p.save(os.path.join(tmpdir, filename)) + p = plot(sqrt(LambertW(x))) + p.save(os.path.join(tmpdir, filename)) + + #Characteristic function of a StudentT distribution with nu=10 + x1 = 5 * x**2 * exp_polar(-I*pi)/2 + m1 = meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), x1) + x2 = 5*x**2 * exp_polar(I*pi)/2 + m2 = meijerg(((1/2,), ()), ((5, 0, 1/2), ()), x2) + expr = (m1 + m2) / (48 * pi) + p = plot(expr, (x, 1e-6, 1e-2)) + p.save(os.path.join(tmpdir, filename)) + + +def test_plotgrid_and_save(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + y = Symbol('y') + + with TemporaryDirectory(prefix='sympy_') as tmpdir: + p1 = plot(x) + p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False) + p3 = plot_parametric( + cos(x), sin(x), adaptive=False, nb_of_points=500, show=False) + p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False) + # symmetric grid + p = PlotGrid(2, 2, p1, p2, p3, p4) + filename = 'test_grid1.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + # grid size greater than the number of subplots + p = PlotGrid(3, 4, p1, p2, p3, p4) + filename = 'test_grid2.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + p5 = plot(cos(x),(x, -pi, pi), show=False) + p5[0].line_color = lambda a: a + p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False) + p7 = plot_contour( + (x**2 + y**2, (x, -5, 5), (y, -5, 5)), + (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False) + # unsymmetric grid (subplots in one line) + p = PlotGrid(1, 3, p5, p6, p7) + filename = 'test_grid3.png' + p.save(os.path.join(tmpdir, filename)) + p._backend.close() + + +def test_append_issue_7140(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + p1 = plot(x) + p2 = plot(x**2) + plot(x + 2) + + # append a series + p2.append(p1[0]) + assert len(p2._series) == 2 + + with raises(TypeError): + p1.append(p2) + + with raises(TypeError): + p1.append(p2._series) + + +def test_issue_15265(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + eqn = sin(x) + + p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1)) + p._backend.close() + + p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi)) + p._backend.close() + + p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14'))) + p._backend.close() + + p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1)) + p._backend.close() + + raises(ValueError, + lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1))) + + raises(ValueError, + lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit))) + + raises(ValueError, + lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1))) + + raises(ValueError, + lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity))) + + +def test_empty_Plot(): + if not matplotlib: + skip("Matplotlib not the default backend") + + # No exception showing an empty plot + plot() + p = Plot() + p.show() + + +def test_issue_17405(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + f = x**0.3 - 10*x**3 + x**2 + p = plot(f, (x, -10, 10), show=False) + # Random number of segments, probably more than 100, but we want to see + # that there are segments generated, as opposed to when the bug was present + + # RuntimeWarning: invalid value encountered in double_scalars + with ignore_warnings(RuntimeWarning): + assert len(p[0].get_data()[0]) >= 30 + + +def test_logplot_PR_16796(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + p = plot(x, (x, .001, 100), xscale='log', show=False) + # Random number of segments, probably more than 100, but we want to see + # that there are segments generated, as opposed to when the bug was present + assert len(p[0].get_data()[0]) >= 30 + assert p[0].end == 100.0 + assert p[0].start == .001 + + +def test_issue_16572(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + p = plot(LambertW(x), show=False) + # Random number of segments, probably more than 50, but we want to see + # that there are segments generated, as opposed to when the bug was present + assert len(p[0].get_data()[0]) >= 30 + + +def test_issue_11865(): + if not matplotlib: + skip("Matplotlib not the default backend") + + k = Symbol('k', integer=True) + f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True)) + p = plot(f, show=False) + # Random number of segments, probably more than 100, but we want to see + # that there are segments generated, as opposed to when the bug was present + # and that there are no exceptions. + assert len(p[0].get_data()[0]) >= 30 + + +def test_issue_11461(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + p = plot(real_root((log(x/(x-2))), 3), show=False) + # Random number of segments, probably more than 100, but we want to see + # that there are segments generated, as opposed to when the bug was present + # and that there are no exceptions. + assert len(p[0].get_data()[0]) >= 30 + + +def test_issue_11764(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False) + assert p.aspect_ratio == (1, 1) + # Random number of segments, probably more than 100, but we want to see + # that there are segments generated, as opposed to when the bug was present + assert len(p[0].get_data()[0]) >= 30 + + +def test_issue_13516(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + + pm = plot(sin(x), backend="matplotlib", show=False) + assert pm.backend == MatplotlibBackend + assert len(pm[0].get_data()[0]) >= 30 + + pt = plot(sin(x), backend="text", show=False) + assert pt.backend == TextBackend + assert len(pt[0].get_data()[0]) >= 30 + + pd = plot(sin(x), backend="default", show=False) + assert pd.backend == DefaultBackend + assert len(pd[0].get_data()[0]) >= 30 + + p = plot(sin(x), show=False) + assert p.backend == DefaultBackend + assert len(p[0].get_data()[0]) >= 30 + + +def test_plot_limits(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + p = plot(x, x**2, (x, -10, 10)) + backend = p._backend + + xmin, xmax = backend.ax[0].get_xlim() + assert abs(xmin + 10) < 2 + assert abs(xmax - 10) < 2 + ymin, ymax = backend.ax[0].get_ylim() + assert abs(ymin + 10) < 10 + assert abs(ymax - 100) < 10 + + +def test_plot3d_parametric_line_limits(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + + v1 = (2*cos(x), 2*sin(x), 2*x, (x, -5, 5)) + v2 = (sin(x), cos(x), x, (x, -5, 5)) + p = plot3d_parametric_line(v1, v2) + backend = p._backend + + xmin, xmax = backend.ax[0].get_xlim() + assert abs(xmin + 2) < 1e-2 + assert abs(xmax - 2) < 1e-2 + ymin, ymax = backend.ax[0].get_ylim() + assert abs(ymin + 2) < 1e-2 + assert abs(ymax - 2) < 1e-2 + zmin, zmax = backend.ax[0].get_zlim() + assert abs(zmin + 10) < 1e-2 + assert abs(zmax - 10) < 1e-2 + + p = plot3d_parametric_line(v2, v1) + backend = p._backend + + xmin, xmax = backend.ax[0].get_xlim() + assert abs(xmin + 2) < 1e-2 + assert abs(xmax - 2) < 1e-2 + ymin, ymax = backend.ax[0].get_ylim() + assert abs(ymin + 2) < 1e-2 + assert abs(ymax - 2) < 1e-2 + zmin, zmax = backend.ax[0].get_zlim() + assert abs(zmin + 10) < 1e-2 + assert abs(zmax - 10) < 1e-2 + +def test_plot_size(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + + p1 = plot(sin(x), backend="matplotlib", size=(8, 4)) + s1 = p1._backend.fig.get_size_inches() + assert (s1[0] == 8) and (s1[1] == 4) + p2 = plot(sin(x), backend="matplotlib", size=(5, 10)) + s2 = p2._backend.fig.get_size_inches() + assert (s2[0] == 5) and (s2[1] == 10) + p3 = PlotGrid(2, 1, p1, p2, size=(6, 2)) + s3 = p3._backend.fig.get_size_inches() + assert (s3[0] == 6) and (s3[1] == 2) + + with raises(ValueError): + plot(sin(x), backend="matplotlib", size=(-1, 3)) + +def test_issue_20113(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + + # verify the capability to use custom backends + with raises(TypeError): + plot(sin(x), backend=Plot, show=False) + p2 = plot(sin(x), backend=MatplotlibBackend, show=False) + assert p2.backend == MatplotlibBackend + assert len(p2[0].get_data()[0]) >= 30 + p3 = plot(sin(x), backend=DummyBackendOk, show=False) + assert p3.backend == DummyBackendOk + assert len(p3[0].get_data()[0]) >= 30 + + # test for an improper coded backend + p4 = plot(sin(x), backend=DummyBackendNotOk, show=False) + assert p4.backend == DummyBackendNotOk + assert len(p4[0].get_data()[0]) >= 30 + with raises(NotImplementedError): + p4.show() + with raises(NotImplementedError): + p4.save("test/path") + with raises(NotImplementedError): + p4._backend.close() + +def test_custom_coloring(): + x = Symbol('x') + y = Symbol('y') + plot(cos(x), line_color=lambda a: a) + plot(cos(x), line_color=1) + plot(cos(x), line_color="r") + plot_parametric(cos(x), sin(x), line_color=lambda a: a) + plot_parametric(cos(x), sin(x), line_color=1) + plot_parametric(cos(x), sin(x), line_color="r") + plot3d_parametric_line(cos(x), sin(x), x, line_color=lambda a: a) + plot3d_parametric_line(cos(x), sin(x), x, line_color=1) + plot3d_parametric_line(cos(x), sin(x), x, line_color="r") + plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, + (x, -5, 5), (y, -5, 5), + surface_color=lambda a, b: a**2 + b**2) + plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, + (x, -5, 5), (y, -5, 5), + surface_color=1) + plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, + (x, -5, 5), (y, -5, 5), + surface_color="r") + plot3d(x*y, (x, -5, 5), (y, -5, 5), + surface_color=lambda a, b: a**2 + b**2) + plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=1) + plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color="r") + +def test_deprecated_get_segments(): + if not matplotlib: + skip("Matplotlib not the default backend") + + x = Symbol('x') + f = sin(x) + p = plot(f, (x, -10, 10), show=False) + with warns_deprecated_sympy(): + p[0].get_segments() diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_plot_implicit.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_plot_implicit.py new file mode 100644 index 0000000000000000000000000000000000000000..48c093e31aaf320b46dbf9eb5de79b407b6fb0e7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_plot_implicit.py @@ -0,0 +1,146 @@ +from sympy.core.numbers import (I, pi) +from sympy.core.relational import Eq +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import re +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.trigonometric import (cos, sin, tan) +from sympy.logic.boolalg import (And, Or) +from sympy.plotting.plot_implicit import plot_implicit +from sympy.plotting.plot import unset_show +from tempfile import NamedTemporaryFile, mkdtemp +from sympy.testing.pytest import skip, warns, XFAIL +from sympy.external import import_module +from sympy.testing.tmpfiles import TmpFileManager + +import os + +#Set plots not to show +unset_show() + +def tmp_file(dir=None, name=''): + return NamedTemporaryFile( + suffix='.png', dir=dir, delete=False).name + +def plot_and_save(expr, *args, name='', dir=None, **kwargs): + p = plot_implicit(expr, *args, **kwargs) + p.save(tmp_file(dir=dir, name=name)) + # Close the plot to avoid a warning from matplotlib + p._backend.close() + +def plot_implicit_tests(name): + temp_dir = mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + x = Symbol('x') + y = Symbol('y') + #implicit plot tests + plot_and_save(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) + plot_and_save(Eq(y**2, x**3 - x), (x, -5, 5), + (y, -4, 4), name=name, dir=temp_dir) + plot_and_save(y > 1 / x, (x, -5, 5), + (y, -2, 2), name=name, dir=temp_dir) + plot_and_save(y < 1 / tan(x), (x, -5, 5), + (y, -2, 2), name=name, dir=temp_dir) + plot_and_save(y >= 2 * sin(x) * cos(x), (x, -5, 5), + (y, -2, 2), name=name, dir=temp_dir) + plot_and_save(y <= x**2, (x, -3, 3), + (y, -1, 5), name=name, dir=temp_dir) + + #Test all input args for plot_implicit + plot_and_save(Eq(y**2, x**3 - x), dir=temp_dir) + plot_and_save(Eq(y**2, x**3 - x), adaptive=False, dir=temp_dir) + plot_and_save(Eq(y**2, x**3 - x), adaptive=False, points=500, dir=temp_dir) + plot_and_save(y > x, (x, -5, 5), dir=temp_dir) + plot_and_save(And(y > exp(x), y > x + 2), dir=temp_dir) + plot_and_save(Or(y > x, y > -x), dir=temp_dir) + plot_and_save(x**2 - 1, (x, -5, 5), dir=temp_dir) + plot_and_save(x**2 - 1, dir=temp_dir) + plot_and_save(y > x, depth=-5, dir=temp_dir) + plot_and_save(y > x, depth=5, dir=temp_dir) + plot_and_save(y > cos(x), adaptive=False, dir=temp_dir) + plot_and_save(y < cos(x), adaptive=False, dir=temp_dir) + plot_and_save(And(y > cos(x), Or(y > x, Eq(y, x))), dir=temp_dir) + plot_and_save(y - cos(pi / x), dir=temp_dir) + + plot_and_save(x**2 - 1, title='An implicit plot', dir=temp_dir) + +@XFAIL +def test_no_adaptive_meshing(): + matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) + if matplotlib: + try: + temp_dir = mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + x = Symbol('x') + y = Symbol('y') + # Test plots which cannot be rendered using the adaptive algorithm + + # This works, but it triggers a deprecation warning from sympify(). The + # code needs to be updated to detect if interval math is supported without + # relying on random AttributeErrors. + with warns(UserWarning, match="Adaptive meshing could not be applied"): + plot_and_save(Eq(y, re(cos(x) + I*sin(x))), name='test', dir=temp_dir) + finally: + TmpFileManager.cleanup() + else: + skip("Matplotlib not the default backend") +def test_line_color(): + x, y = symbols('x, y') + p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False) + assert p._series[0].line_color == "green" + p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False) + assert p._series[0].line_color == "r" + +def test_matplotlib(): + matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) + if matplotlib: + try: + plot_implicit_tests('test') + test_line_color() + finally: + TmpFileManager.cleanup() + else: + skip("Matplotlib not the default backend") + + +def test_region_and(): + matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) + if not matplotlib: + skip("Matplotlib not the default backend") + + from matplotlib.testing.compare import compare_images + test_directory = os.path.dirname(os.path.abspath(__file__)) + + try: + temp_dir = mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + + x, y = symbols('x y') + + r1 = (x - 1)**2 + y**2 < 2 + r2 = (x + 1)**2 + y**2 < 2 + + test_filename = tmp_file(dir=temp_dir, name="test_region_and") + cmp_filename = os.path.join(test_directory, "test_region_and.png") + p = plot_implicit(r1 & r2, x, y) + p.save(test_filename) + compare_images(cmp_filename, test_filename, 0.005) + + test_filename = tmp_file(dir=temp_dir, name="test_region_or") + cmp_filename = os.path.join(test_directory, "test_region_or.png") + p = plot_implicit(r1 | r2, x, y) + p.save(test_filename) + compare_images(cmp_filename, test_filename, 0.005) + + test_filename = tmp_file(dir=temp_dir, name="test_region_not") + cmp_filename = os.path.join(test_directory, "test_region_not.png") + p = plot_implicit(~r1, x, y) + p.save(test_filename) + compare_images(cmp_filename, test_filename, 0.005) + + test_filename = tmp_file(dir=temp_dir, name="test_region_xor") + cmp_filename = os.path.join(test_directory, "test_region_xor.png") + p = plot_implicit(r1 ^ r2, x, y) + p.save(test_filename) + compare_images(cmp_filename, test_filename, 0.005) + finally: + TmpFileManager.cleanup() diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_textplot.py b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_textplot.py new file mode 100644 index 0000000000000000000000000000000000000000..928085c627e5230f2ac4a8ce0bbac5354ab35d51 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/plotting/tests/test_textplot.py @@ -0,0 +1,203 @@ +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import sin +from sympy.plotting.textplot import textplot_str + +from sympy.utilities.exceptions import ignore_warnings + + +def test_axes_alignment(): + x = Symbol('x') + lines = [ + ' 1 | ..', + ' | ... ', + ' | .. ', + ' | ... ', + ' | ... ', + ' | .. ', + ' | ... ', + ' | ... ', + ' | .. ', + ' | ... ', + ' 0 |--------------------------...--------------------------', + ' | ... ', + ' | .. ', + ' | ... ', + ' | ... ', + ' | .. ', + ' | ... ', + ' | ... ', + ' | .. ', + ' | ... ', + ' -1 |_______________________________________________________', + ' -1 0 1' + ] + assert lines == list(textplot_str(x, -1, 1)) + + lines = [ + ' 1 | ..', + ' | .... ', + ' | ... ', + ' | ... ', + ' | .... ', + ' | ... ', + ' | ... ', + ' | .... ', + ' 0 |--------------------------...--------------------------', + ' | .... ', + ' | ... ', + ' | ... ', + ' | .... ', + ' | ... ', + ' | ... ', + ' | .... ', + ' -1 |_______________________________________________________', + ' -1 0 1' + ] + assert lines == list(textplot_str(x, -1, 1, H=17)) + + +def test_singularity(): + x = Symbol('x') + lines = [ + ' 54 | . ', + ' | ', + ' | ', + ' | ', + ' | ',' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' 27.5 |--.----------------------------------------------------', + ' | ', + ' | ', + ' | ', + ' | . ', + ' | \\ ', + ' | \\ ', + ' | .. ', + ' | ... ', + ' | ............. ', + ' 1 |_______________________________________________________', + ' 0 0.5 1' + ] + assert lines == list(textplot_str(1/x, 0, 1)) + + lines = [ + ' 0 | ......', + ' | ........ ', + ' | ........ ', + ' | ...... ', + ' | ..... ', + ' | .... ', + ' | ... ', + ' | .. ', + ' | ... ', + ' | / ', + ' -2 |-------..----------------------------------------------', + ' | / ', + ' | / ', + ' | / ', + ' | . ', + ' | ', + ' | . ', + ' | ', + ' | ', + ' | ', + ' -4 |_______________________________________________________', + ' 0 0.5 1' + ] + # RuntimeWarning: divide by zero encountered in log + with ignore_warnings(RuntimeWarning): + assert lines == list(textplot_str(log(x), 0, 1)) + + +def test_sinc(): + x = Symbol('x') + lines = [ + ' 1 | . . ', + ' | . . ', + ' | ', + ' | . . ', + ' | ', + ' | . . ', + ' | ', + ' | ', + ' | . . ', + ' | ', + ' 0.4 |-------------------------------------------------------', + ' | . . ', + ' | ', + ' | . . ', + ' | ', + ' | ..... ..... ', + ' | .. \\ . . / .. ', + ' | / \\ / \\ ', + ' |/ \\ . . / \\', + ' | \\ / \\ / ', + ' -0.2 |_______________________________________________________', + ' -10 0 10' + ] + # RuntimeWarning: invalid value encountered in double_scalars + with ignore_warnings(RuntimeWarning): + assert lines == list(textplot_str(sin(x)/x, -10, 10)) + + +def test_imaginary(): + x = Symbol('x') + lines = [ + ' 1 | ..', + ' | .. ', + ' | ... ', + ' | .. ', + ' | .. ', + ' | .. ', + ' | .. ', + ' | .. ', + ' | .. ', + ' | / ', + ' 0.5 |----------------------------------/--------------------', + ' | .. ', + ' | / ', + ' | . ', + ' | ', + ' | . ', + ' | . ', + ' | ', + ' | ', + ' | ', + ' 0 |_______________________________________________________', + ' -1 0 1' + ] + # RuntimeWarning: invalid value encountered in sqrt + with ignore_warnings(RuntimeWarning): + assert list(textplot_str(sqrt(x), -1, 1)) == lines + + lines = [ + ' 1 | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' 0 |-------------------------------------------------------', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' | ', + ' -1 |_______________________________________________________', + ' -1 0 1' + ] + assert list(textplot_str(S.ImaginaryUnit, -1, 1)) == lines