diff --git a/.gitattributes b/.gitattributes index 6d42d5107b645c42fbd940d148f7b623d114ba48..ce95d328ccaef72f9a4382ea36570926cdc90ed3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1068,3 +1068,7 @@ omnilmm/lib/python3.10/lib-dynload/_codecs_tw.cpython-310-x86_64-linux-gnu.so fi omnilmm/lib/python3.10/lib-dynload/_lzma.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text omnilmm/lib/python3.10/__pycache__/turtle.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text wemm/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +vila/lib/python3.10/site-packages/sympy/core/__pycache__/numbers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +vila/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +vila/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +vila/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/__init__.py b/vila/lib/python3.10/site-packages/sympy/algebras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58013d2e0377a016d1a21fbf21c344ee76765189 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/algebras/__init__.py @@ -0,0 +1,3 @@ +from .quaternion import Quaternion + +__all__ = ["Quaternion",] diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/__pycache__/__init__.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/algebras/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..691482710ca3e5a8dff9aefe0943a997d4b737ba Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/algebras/__pycache__/__init__.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/__pycache__/quaternion.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/algebras/__pycache__/quaternion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b34a7213cea5ef87e235031a8f247cf8d7be2fe0 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/algebras/__pycache__/quaternion.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/quaternion.py b/vila/lib/python3.10/site-packages/sympy/algebras/quaternion.py new file mode 100644 index 0000000000000000000000000000000000000000..3251d92af3850abd8b07421d71c0cfc360efcf30 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/algebras/quaternion.py @@ -0,0 +1,1667 @@ +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.relational import is_eq +from sympy.functions.elementary.complexes import (conjugate, im, re, sign) +from sympy.functions.elementary.exponential import (exp, log as ln) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, asin, atan2) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.simplify.trigsimp import trigsimp +from sympy.integrals.integrals import integrate +from sympy.matrices.dense import MutableDenseMatrix as Matrix +from sympy.core.sympify import sympify, _sympify +from sympy.core.expr import Expr +from sympy.core.logic import fuzzy_not, fuzzy_or +from sympy.utilities.misc import as_int + +from mpmath.libmp.libmpf import prec_to_dps + + +def _check_norm(elements, norm): + """validate if input norm is consistent""" + if norm is not None and norm.is_number: + if norm.is_positive is False: + raise ValueError("Input norm must be positive.") + + numerical = all(i.is_number and i.is_real is True for i in elements) + if numerical and is_eq(norm**2, sum(i**2 for i in elements)) is False: + raise ValueError("Incompatible value for norm.") + + +def _is_extrinsic(seq): + """validate seq and return True if seq is lowercase and False if uppercase""" + if type(seq) != str: + raise ValueError('Expected seq to be a string.') + if len(seq) != 3: + raise ValueError("Expected 3 axes, got `{}`.".format(seq)) + + intrinsic = seq.isupper() + extrinsic = seq.islower() + if not (intrinsic or extrinsic): + raise ValueError("seq must either be fully uppercase (for extrinsic " + "rotations), or fully lowercase, for intrinsic " + "rotations).") + + i, j, k = seq.lower() + if (i == j) or (j == k): + raise ValueError("Consecutive axes must be different") + + bad = set(seq) - set('xyzXYZ') + if bad: + raise ValueError("Expected axes from `seq` to be from " + "['x', 'y', 'z'] or ['X', 'Y', 'Z'], " + "got {}".format(''.join(bad))) + + return extrinsic + + +class Quaternion(Expr): + """Provides basic quaternion operations. + Quaternion objects can be instantiated as ``Quaternion(a, b, c, d)`` + as in $q = a + bi + cj + dk$. + + Parameters + ========== + + norm : None or number + Pre-defined quaternion norm. If a value is given, Quaternion.norm + returns this pre-defined value instead of calculating the norm + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q + 1 + 2*i + 3*j + 4*k + + Quaternions over complex fields can be defined as: + + >>> from sympy import Quaternion + >>> from sympy import symbols, I + >>> x = symbols('x') + >>> q1 = Quaternion(x, x**3, x, x**2, real_field = False) + >>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> q1 + x + x**3*i + x*j + x**2*k + >>> q2 + (3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k + + Defining symbolic unit quaternions: + + >>> from sympy import Quaternion + >>> from sympy.abc import w, x, y, z + >>> q = Quaternion(w, x, y, z, norm=1) + >>> q + w + x*i + y*j + z*k + >>> q.norm() + 1 + + References + ========== + + .. [1] https://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/ + .. [2] https://en.wikipedia.org/wiki/Quaternion + + """ + _op_priority = 11.0 + + is_commutative = False + + def __new__(cls, a=0, b=0, c=0, d=0, real_field=True, norm=None): + a, b, c, d = map(sympify, (a, b, c, d)) + + if any(i.is_commutative is False for i in [a, b, c, d]): + raise ValueError("arguments have to be commutative") + obj = super().__new__(cls, a, b, c, d) + obj._real_field = real_field + obj.set_norm(norm) + return obj + + def set_norm(self, norm): + """Sets norm of an already instantiated quaternion. + + Parameters + ========== + + norm : None or number + Pre-defined quaternion norm. If a value is given, Quaternion.norm + returns this pre-defined value instead of calculating the norm + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q = Quaternion(a, b, c, d) + >>> q.norm() + sqrt(a**2 + b**2 + c**2 + d**2) + + Setting the norm: + + >>> q.set_norm(1) + >>> q.norm() + 1 + + Removing set norm: + + >>> q.set_norm(None) + >>> q.norm() + sqrt(a**2 + b**2 + c**2 + d**2) + + """ + norm = sympify(norm) + _check_norm(self.args, norm) + self._norm = norm + + @property + def a(self): + return self.args[0] + + @property + def b(self): + return self.args[1] + + @property + def c(self): + return self.args[2] + + @property + def d(self): + return self.args[3] + + @property + def real_field(self): + return self._real_field + + @property + def product_matrix_left(self): + r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the + left. This can be useful when treating quaternion elements as column + vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d + are real numbers, the product matrix from the left is: + + .. math:: + + M = \begin{bmatrix} a &-b &-c &-d \\ + b & a &-d & c \\ + c & d & a &-b \\ + d &-c & b & a \end{bmatrix} + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q1 = Quaternion(1, 0, 0, 1) + >>> q2 = Quaternion(a, b, c, d) + >>> q1.product_matrix_left + Matrix([ + [1, 0, 0, -1], + [0, 1, -1, 0], + [0, 1, 1, 0], + [1, 0, 0, 1]]) + + >>> q1.product_matrix_left * q2.to_Matrix() + Matrix([ + [a - d], + [b - c], + [b + c], + [a + d]]) + + This is equivalent to: + + >>> (q1 * q2).to_Matrix() + Matrix([ + [a - d], + [b - c], + [b + c], + [a + d]]) + """ + return Matrix([ + [self.a, -self.b, -self.c, -self.d], + [self.b, self.a, -self.d, self.c], + [self.c, self.d, self.a, -self.b], + [self.d, -self.c, self.b, self.a]]) + + @property + def product_matrix_right(self): + r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the + right. This can be useful when treating quaternion elements as column + vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d + are real numbers, the product matrix from the left is: + + .. math:: + + M = \begin{bmatrix} a &-b &-c &-d \\ + b & a & d &-c \\ + c &-d & a & b \\ + d & c &-b & a \end{bmatrix} + + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q1 = Quaternion(a, b, c, d) + >>> q2 = Quaternion(1, 0, 0, 1) + >>> q2.product_matrix_right + Matrix([ + [1, 0, 0, -1], + [0, 1, 1, 0], + [0, -1, 1, 0], + [1, 0, 0, 1]]) + + Note the switched arguments: the matrix represents the quaternion on + the right, but is still considered as a matrix multiplication from the + left. + + >>> q2.product_matrix_right * q1.to_Matrix() + Matrix([ + [ a - d], + [ b + c], + [-b + c], + [ a + d]]) + + This is equivalent to: + + >>> (q1 * q2).to_Matrix() + Matrix([ + [ a - d], + [ b + c], + [-b + c], + [ a + d]]) + """ + return Matrix([ + [self.a, -self.b, -self.c, -self.d], + [self.b, self.a, self.d, -self.c], + [self.c, -self.d, self.a, self.b], + [self.d, self.c, -self.b, self.a]]) + + def to_Matrix(self, vector_only=False): + """Returns elements of quaternion as a column vector. + By default, a ``Matrix`` of length 4 is returned, with the real part as the + first element. + If ``vector_only`` is ``True``, returns only imaginary part as a Matrix of + length 3. + + Parameters + ========== + + vector_only : bool + If True, only imaginary part is returned. + Default value: False + + Returns + ======= + + Matrix + A column vector constructed by the elements of the quaternion. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q = Quaternion(a, b, c, d) + >>> q + a + b*i + c*j + d*k + + >>> q.to_Matrix() + Matrix([ + [a], + [b], + [c], + [d]]) + + + >>> q.to_Matrix(vector_only=True) + Matrix([ + [b], + [c], + [d]]) + + """ + if vector_only: + return Matrix(self.args[1:]) + else: + return Matrix(self.args) + + @classmethod + def from_Matrix(cls, elements): + """Returns quaternion from elements of a column vector`. + If vector_only is True, returns only imaginary part as a Matrix of + length 3. + + Parameters + ========== + + elements : Matrix, list or tuple of length 3 or 4. If length is 3, + assume real part is zero. + Default value: False + + Returns + ======= + + Quaternion + A quaternion created from the input elements. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> q = Quaternion.from_Matrix([a, b, c, d]) + >>> q + a + b*i + c*j + d*k + + >>> q = Quaternion.from_Matrix([b, c, d]) + >>> q + 0 + b*i + c*j + d*k + + """ + length = len(elements) + if length != 3 and length != 4: + raise ValueError("Input elements must have length 3 or 4, got {} " + "elements".format(length)) + + if length == 3: + return Quaternion(0, *elements) + else: + return Quaternion(*elements) + + @classmethod + def from_euler(cls, angles, seq): + """Returns quaternion equivalent to rotation represented by the Euler + angles, in the sequence defined by ``seq``. + + Parameters + ========== + + angles : list, tuple or Matrix of 3 numbers + The Euler angles (in radians). + seq : string of length 3 + Represents the sequence of rotations. + For extrinsic rotations, seq must be all lowercase and its elements + must be from the set ``{'x', 'y', 'z'}`` + For intrinsic rotations, seq must be all uppercase and its elements + must be from the set ``{'X', 'Y', 'Z'}`` + + Returns + ======= + + Quaternion + The normalized rotation quaternion calculated from the Euler angles + in the given sequence. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import pi + >>> q = Quaternion.from_euler([pi/2, 0, 0], 'xyz') + >>> q + sqrt(2)/2 + sqrt(2)/2*i + 0*j + 0*k + + >>> q = Quaternion.from_euler([0, pi/2, pi] , 'zyz') + >>> q + 0 + (-sqrt(2)/2)*i + 0*j + sqrt(2)/2*k + + >>> q = Quaternion.from_euler([0, pi/2, pi] , 'ZYZ') + >>> q + 0 + sqrt(2)/2*i + 0*j + sqrt(2)/2*k + + """ + + if len(angles) != 3: + raise ValueError("3 angles must be given.") + + extrinsic = _is_extrinsic(seq) + i, j, k = seq.lower() + + # get elementary basis vectors + ei = [1 if n == i else 0 for n in 'xyz'] + ej = [1 if n == j else 0 for n in 'xyz'] + ek = [1 if n == k else 0 for n in 'xyz'] + + # calculate distinct quaternions + qi = cls.from_axis_angle(ei, angles[0]) + qj = cls.from_axis_angle(ej, angles[1]) + qk = cls.from_axis_angle(ek, angles[2]) + + if extrinsic: + return trigsimp(qk * qj * qi) + else: + return trigsimp(qi * qj * qk) + + def to_euler(self, seq, angle_addition=True, avoid_square_root=False): + r"""Returns Euler angles representing same rotation as the quaternion, + in the sequence given by ``seq``. This implements the method described + in [1]_. + + For degenerate cases (gymbal lock cases), the third angle is + set to zero. + + Parameters + ========== + + seq : string of length 3 + Represents the sequence of rotations. + For extrinsic rotations, seq must be all lowercase and its elements + must be from the set ``{'x', 'y', 'z'}`` + For intrinsic rotations, seq must be all uppercase and its elements + must be from the set ``{'X', 'Y', 'Z'}`` + + angle_addition : bool + When True, first and third angles are given as an addition and + subtraction of two simpler ``atan2`` expressions. When False, the + first and third angles are each given by a single more complicated + ``atan2`` expression. This equivalent expression is given by: + + .. math:: + + \operatorname{atan_2} (b,a) \pm \operatorname{atan_2} (d,c) = + \operatorname{atan_2} (bc\pm ad, ac\mp bd) + + Default value: True + + avoid_square_root : bool + When True, the second angle is calculated with an expression based + on ``acos``, which is slightly more complicated but avoids a square + root. When False, second angle is calculated with ``atan2``, which + is simpler and can be better for numerical reasons (some + numerical implementations of ``acos`` have problems near zero). + Default value: False + + + Returns + ======= + + Tuple + The Euler angles calculated from the quaternion + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy.abc import a, b, c, d + >>> euler = Quaternion(a, b, c, d).to_euler('zyz') + >>> euler + (-atan2(-b, c) + atan2(d, a), + 2*atan2(sqrt(b**2 + c**2), sqrt(a**2 + d**2)), + atan2(-b, c) + atan2(d, a)) + + + References + ========== + + .. [1] https://doi.org/10.1371/journal.pone.0276302 + + """ + if self.is_zero_quaternion(): + raise ValueError('Cannot convert a quaternion with norm 0.') + + angles = [0, 0, 0] + + extrinsic = _is_extrinsic(seq) + i, j, k = seq.lower() + + # get index corresponding to elementary basis vectors + i = 'xyz'.index(i) + 1 + j = 'xyz'.index(j) + 1 + k = 'xyz'.index(k) + 1 + + if not extrinsic: + i, k = k, i + + # check if sequence is symmetric + symmetric = i == k + if symmetric: + k = 6 - i - j + + # parity of the permutation + sign = (i - j) * (j - k) * (k - i) // 2 + + # permutate elements + elements = [self.a, self.b, self.c, self.d] + a = elements[0] + b = elements[i] + c = elements[j] + d = elements[k] * sign + + if not symmetric: + a, b, c, d = a - c, b + d, c + a, d - b + + if avoid_square_root: + if symmetric: + n2 = self.norm()**2 + angles[1] = acos((a * a + b * b - c * c - d * d) / n2) + else: + n2 = 2 * self.norm()**2 + angles[1] = asin((c * c + d * d - a * a - b * b) / n2) + else: + angles[1] = 2 * atan2(sqrt(c * c + d * d), sqrt(a * a + b * b)) + if not symmetric: + angles[1] -= S.Pi / 2 + + # Check for singularities in numerical cases + case = 0 + if is_eq(c, S.Zero) and is_eq(d, S.Zero): + case = 1 + if is_eq(a, S.Zero) and is_eq(b, S.Zero): + case = 2 + + if case == 0: + if angle_addition: + angles[0] = atan2(b, a) + atan2(d, c) + angles[2] = atan2(b, a) - atan2(d, c) + else: + angles[0] = atan2(b*c + a*d, a*c - b*d) + angles[2] = atan2(b*c - a*d, a*c + b*d) + + else: # any degenerate case + angles[2 * (not extrinsic)] = S.Zero + if case == 1: + angles[2 * extrinsic] = 2 * atan2(b, a) + else: + angles[2 * extrinsic] = 2 * atan2(d, c) + angles[2 * extrinsic] *= (-1 if extrinsic else 1) + + # for Tait-Bryan angles + if not symmetric: + angles[0] *= sign + + if extrinsic: + return tuple(angles[::-1]) + else: + return tuple(angles) + + @classmethod + def from_axis_angle(cls, vector, angle): + """Returns a rotation quaternion given the axis and the angle of rotation. + + Parameters + ========== + + vector : tuple of three numbers + The vector representation of the given axis. + angle : number + The angle by which axis is rotated (in radians). + + Returns + ======= + + Quaternion + The normalized rotation quaternion calculated from the given axis and the angle of rotation. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import pi, sqrt + >>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3) + >>> q + 1/2 + 1/2*i + 1/2*j + 1/2*k + + """ + (x, y, z) = vector + norm = sqrt(x**2 + y**2 + z**2) + (x, y, z) = (x / norm, y / norm, z / norm) + s = sin(angle * S.Half) + a = cos(angle * S.Half) + b = x * s + c = y * s + d = z * s + + # note that this quaternion is already normalized by construction: + # c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1 + # so, what we return is a normalized quaternion + + return cls(a, b, c, d) + + @classmethod + def from_rotation_matrix(cls, M): + """Returns the equivalent quaternion of a matrix. The quaternion will be normalized + only if the matrix is special orthogonal (orthogonal and det(M) = 1). + + Parameters + ========== + + M : Matrix + Input matrix to be converted to equivalent quaternion. M must be special + orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized. + + Returns + ======= + + Quaternion + The quaternion equivalent to given matrix. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import Matrix, symbols, cos, sin, trigsimp + >>> x = symbols('x') + >>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]]) + >>> q = trigsimp(Quaternion.from_rotation_matrix(M)) + >>> q + sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k + + """ + + absQ = M.det()**Rational(1, 3) + + a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2 + b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2 + c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2 + d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2 + + b = b * sign(M[2, 1] - M[1, 2]) + c = c * sign(M[0, 2] - M[2, 0]) + d = d * sign(M[1, 0] - M[0, 1]) + + return Quaternion(a, b, c, d) + + def __add__(self, other): + return self.add(other) + + def __radd__(self, other): + return self.add(other) + + def __sub__(self, other): + return self.add(other*-1) + + def __mul__(self, other): + return self._generic_mul(self, _sympify(other)) + + def __rmul__(self, other): + return self._generic_mul(_sympify(other), self) + + def __pow__(self, p): + return self.pow(p) + + def __neg__(self): + return Quaternion(-self.a, -self.b, -self.c, -self.d) + + def __truediv__(self, other): + return self * sympify(other)**-1 + + def __rtruediv__(self, other): + return sympify(other) * self**-1 + + def _eval_Integral(self, *args): + return self.integrate(*args) + + def diff(self, *symbols, **kwargs): + kwargs.setdefault('evaluate', True) + return self.func(*[a.diff(*symbols, **kwargs) for a in self.args]) + + def add(self, other): + """Adds quaternions. + + Parameters + ========== + + other : Quaternion + The quaternion to add to current (self) quaternion. + + Returns + ======= + + Quaternion + The resultant quaternion after adding self to other + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols + >>> q1 = Quaternion(1, 2, 3, 4) + >>> q2 = Quaternion(5, 6, 7, 8) + >>> q1.add(q2) + 6 + 8*i + 10*j + 12*k + >>> q1 + 5 + 6 + 2*i + 3*j + 4*k + >>> x = symbols('x', real = True) + >>> q1.add(x) + (x + 1) + 2*i + 3*j + 4*k + + Quaternions over complex fields : + + >>> from sympy import Quaternion + >>> from sympy import I + >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> q3.add(2 + 3*I) + (5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k + + """ + q1 = self + q2 = sympify(other) + + # If q2 is a number or a SymPy expression instead of a quaternion + if not isinstance(q2, Quaternion): + if q1.real_field and q2.is_complex: + return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d) + elif q2.is_commutative: + return Quaternion(q1.a + q2, q1.b, q1.c, q1.d) + else: + raise ValueError("Only commutative expressions can be added with a Quaternion.") + + return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + + q2.d) + + def mul(self, other): + """Multiplies quaternions. + + Parameters + ========== + + other : Quaternion or symbol + The quaternion to multiply to current (self) quaternion. + + Returns + ======= + + Quaternion + The resultant quaternion after multiplying self with other + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols + >>> q1 = Quaternion(1, 2, 3, 4) + >>> q2 = Quaternion(5, 6, 7, 8) + >>> q1.mul(q2) + (-60) + 12*i + 30*j + 24*k + >>> q1.mul(2) + 2 + 4*i + 6*j + 8*k + >>> x = symbols('x', real = True) + >>> q1.mul(x) + x + 2*x*i + 3*x*j + 4*x*k + + Quaternions over complex fields : + + >>> from sympy import Quaternion + >>> from sympy import I + >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> q3.mul(2 + 3*I) + (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k + + """ + return self._generic_mul(self, _sympify(other)) + + @staticmethod + def _generic_mul(q1, q2): + """Generic multiplication. + + Parameters + ========== + + q1 : Quaternion or symbol + q2 : Quaternion or symbol + + It is important to note that if neither q1 nor q2 is a Quaternion, + this function simply returns q1 * q2. + + Returns + ======= + + Quaternion + The resultant quaternion after multiplying q1 and q2 + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import Symbol, S + >>> q1 = Quaternion(1, 2, 3, 4) + >>> q2 = Quaternion(5, 6, 7, 8) + >>> Quaternion._generic_mul(q1, q2) + (-60) + 12*i + 30*j + 24*k + >>> Quaternion._generic_mul(q1, S(2)) + 2 + 4*i + 6*j + 8*k + >>> x = Symbol('x', real = True) + >>> Quaternion._generic_mul(q1, x) + x + 2*x*i + 3*x*j + 4*x*k + + Quaternions over complex fields : + + >>> from sympy import I + >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + >>> Quaternion._generic_mul(q3, 2 + 3*I) + (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k + + """ + # None is a Quaternion: + if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion): + return q1 * q2 + + # If q1 is a number or a SymPy expression instead of a quaternion + if not isinstance(q1, Quaternion): + if q2.real_field and q1.is_complex: + return Quaternion(re(q1), im(q1), 0, 0) * q2 + elif q1.is_commutative: + return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d) + else: + raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") + + # If q2 is a number or a SymPy expression instead of a quaternion + if not isinstance(q2, Quaternion): + if q1.real_field and q2.is_complex: + return q1 * Quaternion(re(q2), im(q2), 0, 0) + elif q2.is_commutative: + return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d) + else: + raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") + + # If any of the quaternions has a fixed norm, pre-compute norm + if q1._norm is None and q2._norm is None: + norm = None + else: + norm = q1.norm() * q2.norm() + + return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a, + q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b, + -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c, + q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d, + norm=norm) + + def _eval_conjugate(self): + """Returns the conjugate of the quaternion.""" + q = self + return Quaternion(q.a, -q.b, -q.c, -q.d, norm=q._norm) + + def norm(self): + """Returns the norm of the quaternion.""" + if self._norm is None: # check if norm is pre-defined + q = self + # trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms + # arise when from_axis_angle is used). + return sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2)) + + return self._norm + + def normalize(self): + """Returns the normalized form of the quaternion.""" + q = self + return q * (1/q.norm()) + + def inverse(self): + """Returns the inverse of the quaternion.""" + q = self + if not q.norm(): + raise ValueError("Cannot compute inverse for a quaternion with zero norm") + return conjugate(q) * (1/q.norm()**2) + + def pow(self, p): + """Finds the pth power of the quaternion. + + Parameters + ========== + + p : int + Power to be applied on quaternion. + + Returns + ======= + + Quaternion + Returns the p-th power of the current quaternion. + Returns the inverse if p = -1. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.pow(4) + 668 + (-224)*i + (-336)*j + (-448)*k + + """ + try: + q, p = self, as_int(p) + except ValueError: + return NotImplemented + + if p < 0: + q, p = q.inverse(), -p + + if p == 1: + return q + + res = Quaternion(1, 0, 0, 0) + while p > 0: + if p & 1: + res *= q + q *= q + p >>= 1 + + return res + + def exp(self): + """Returns the exponential of $q$, given by $e^q$. + + Returns + ======= + + Quaternion + The exponential of the quaternion. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.exp() + E*cos(sqrt(29)) + + 2*sqrt(29)*E*sin(sqrt(29))/29*i + + 3*sqrt(29)*E*sin(sqrt(29))/29*j + + 4*sqrt(29)*E*sin(sqrt(29))/29*k + + """ + # exp(q) = e^a(cos||v|| + v/||v||*sin||v||) + q = self + vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) + a = exp(q.a) * cos(vector_norm) + b = exp(q.a) * sin(vector_norm) * q.b / vector_norm + c = exp(q.a) * sin(vector_norm) * q.c / vector_norm + d = exp(q.a) * sin(vector_norm) * q.d / vector_norm + + return Quaternion(a, b, c, d) + + def log(self): + r"""Returns the logarithm of the quaternion, given by $\log q$. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.log() + log(sqrt(30)) + + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + + 4*sqrt(29)*acos(sqrt(30)/30)/29*k + + """ + # log(q) = log||q|| + v/||v||*arccos(a/||q||) + q = self + vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) + q_norm = q.norm() + a = ln(q_norm) + b = q.b * acos(q.a / q_norm) / vector_norm + c = q.c * acos(q.a / q_norm) / vector_norm + d = q.d * acos(q.a / q_norm) / vector_norm + + return Quaternion(a, b, c, d) + + def _eval_subs(self, *args): + elements = [i.subs(*args) for i in self.args] + norm = self._norm + if norm is not None: + norm = norm.subs(*args) + _check_norm(elements, norm) + return Quaternion(*elements, norm=norm) + + def _eval_evalf(self, prec): + """Returns the floating point approximations (decimal numbers) of the quaternion. + + Returns + ======= + + Quaternion + Floating point approximations of quaternion(self) + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import sqrt + >>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4)) + >>> q.evalf() + 1.00000000000000 + + 0.707106781186547*i + + 0.577350269189626*j + + 0.500000000000000*k + + """ + nprec = prec_to_dps(prec) + return Quaternion(*[arg.evalf(n=nprec) for arg in self.args]) + + def pow_cos_sin(self, p): + """Computes the pth power in the cos-sin form. + + Parameters + ========== + + p : int + Power to be applied on quaternion. + + Returns + ======= + + Quaternion + The p-th power in the cos-sin form. + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 2, 3, 4) + >>> q.pow_cos_sin(4) + 900*cos(4*acos(sqrt(30)/30)) + + 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i + + 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j + + 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k + + """ + # q = ||q||*(cos(a) + u*sin(a)) + # q^p = ||q||^p * (cos(p*a) + u*sin(p*a)) + + q = self + (v, angle) = q.to_axis_angle() + q2 = Quaternion.from_axis_angle(v, p * angle) + return q2 * (q.norm()**p) + + def integrate(self, *args): + """Computes integration of quaternion. + + Returns + ======= + + Quaternion + Integration of the quaternion(self) with the given variable. + + Examples + ======== + + Indefinite Integral of quaternion : + + >>> from sympy import Quaternion + >>> from sympy.abc import x + >>> q = Quaternion(1, 2, 3, 4) + >>> q.integrate(x) + x + 2*x*i + 3*x*j + 4*x*k + + Definite integral of quaternion : + + >>> from sympy import Quaternion + >>> from sympy.abc import x + >>> q = Quaternion(1, 2, 3, 4) + >>> q.integrate((x, 1, 5)) + 4 + 8*i + 12*j + 16*k + + """ + # TODO: is this expression correct? + return Quaternion(integrate(self.a, *args), integrate(self.b, *args), + integrate(self.c, *args), integrate(self.d, *args)) + + @staticmethod + def rotate_point(pin, r): + """Returns the coordinates of the point pin (a 3 tuple) after rotation. + + Parameters + ========== + + pin : tuple + A 3-element tuple of coordinates of a point which needs to be + rotated. + r : Quaternion or tuple + Axis and angle of rotation. + + It's important to note that when r is a tuple, it must be of the form + (axis, angle) + + Returns + ======= + + tuple + The coordinates of the point after rotation. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols, trigsimp, cos, sin + >>> x = symbols('x') + >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) + >>> trigsimp(Quaternion.rotate_point((1, 1, 1), q)) + (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) + >>> (axis, angle) = q.to_axis_angle() + >>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle))) + (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) + + """ + if isinstance(r, tuple): + # if r is of the form (vector, angle) + q = Quaternion.from_axis_angle(r[0], r[1]) + else: + # if r is a quaternion + q = r.normalize() + pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q) + return (pout.b, pout.c, pout.d) + + def to_axis_angle(self): + """Returns the axis and angle of rotation of a quaternion. + + Returns + ======= + + tuple + Tuple of (axis, angle) + + Examples + ======== + + >>> from sympy import Quaternion + >>> q = Quaternion(1, 1, 1, 1) + >>> (axis, angle) = q.to_axis_angle() + >>> axis + (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) + >>> angle + 2*pi/3 + + """ + q = self + if q.a.is_negative: + q = q * -1 + + q = q.normalize() + angle = trigsimp(2 * acos(q.a)) + + # Since quaternion is normalised, q.a is less than 1. + s = sqrt(1 - q.a*q.a) + + x = trigsimp(q.b / s) + y = trigsimp(q.c / s) + z = trigsimp(q.d / s) + + v = (x, y, z) + t = (v, angle) + + return t + + def to_rotation_matrix(self, v=None, homogeneous=True): + """Returns the equivalent rotation transformation matrix of the quaternion + which represents rotation about the origin if ``v`` is not passed. + + Parameters + ========== + + v : tuple or None + Default value: None + homogeneous : bool + When True, gives an expression that may be more efficient for + symbolic calculations but less so for direct evaluation. Both + formulas are mathematically equivalent. + Default value: True + + Returns + ======= + + tuple + Returns the equivalent rotation transformation matrix of the quaternion + which represents rotation about the origin if v is not passed. + + Examples + ======== + + >>> from sympy import Quaternion + >>> from sympy import symbols, trigsimp, cos, sin + >>> x = symbols('x') + >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) + >>> trigsimp(q.to_rotation_matrix()) + Matrix([ + [cos(x), -sin(x), 0], + [sin(x), cos(x), 0], + [ 0, 0, 1]]) + + Generates a 4x4 transformation matrix (used for rotation about a point + other than the origin) if the point(v) is passed as an argument. + """ + + q = self + s = q.norm()**-2 + + # diagonal elements are different according to parameter normal + if homogeneous: + m00 = s*(q.a**2 + q.b**2 - q.c**2 - q.d**2) + m11 = s*(q.a**2 - q.b**2 + q.c**2 - q.d**2) + m22 = s*(q.a**2 - q.b**2 - q.c**2 + q.d**2) + else: + m00 = 1 - 2*s*(q.c**2 + q.d**2) + m11 = 1 - 2*s*(q.b**2 + q.d**2) + m22 = 1 - 2*s*(q.b**2 + q.c**2) + + m01 = 2*s*(q.b*q.c - q.d*q.a) + m02 = 2*s*(q.b*q.d + q.c*q.a) + + m10 = 2*s*(q.b*q.c + q.d*q.a) + m12 = 2*s*(q.c*q.d - q.b*q.a) + + m20 = 2*s*(q.b*q.d - q.c*q.a) + m21 = 2*s*(q.c*q.d + q.b*q.a) + + if not v: + return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]]) + + else: + (x, y, z) = v + + m03 = x - x*m00 - y*m01 - z*m02 + m13 = y - x*m10 - y*m11 - z*m12 + m23 = z - x*m20 - y*m21 - z*m22 + m30 = m31 = m32 = 0 + m33 = 1 + + return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13], + [m20, m21, m22, m23], [m30, m31, m32, m33]]) + + def scalar_part(self): + r"""Returns scalar part($\mathbf{S}(q)$) of the quaternion q. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{S}(q) = a$. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(4, 8, 13, 12) + >>> q.scalar_part() + 4 + + """ + + return self.a + + def vector_part(self): + r""" + Returns $\mathbf{V}(q)$, the vector part of the quaternion $q$. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{V}(q) = bi + cj + dk$. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 1, 1, 1) + >>> q.vector_part() + 0 + 1*i + 1*j + 1*k + + >>> q = Quaternion(4, 8, 13, 12) + >>> q.vector_part() + 0 + 8*i + 13*j + 12*k + + """ + + return Quaternion(0, self.b, self.c, self.d) + + def axis(self): + r""" + Returns $\mathbf{Ax}(q)$, the axis of the quaternion $q$. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{Ax}(q)$ i.e., the versor of the vector part of that quaternion + equal to $\mathbf{U}[\mathbf{V}(q)]$. + The axis is always an imaginary unit with square equal to $-1 + 0i + 0j + 0k$. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 1, 1, 1) + >>> q.axis() + 0 + sqrt(3)/3*i + sqrt(3)/3*j + sqrt(3)/3*k + + See Also + ======== + + vector_part + + """ + axis = self.vector_part().normalize() + + return Quaternion(0, axis.b, axis.c, axis.d) + + def is_pure(self): + """ + Returns true if the quaternion is pure, false if the quaternion is not pure + or returns none if it is unknown. + + Explanation + =========== + + A pure quaternion (also a vector quaternion) is a quaternion with scalar + part equal to 0. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(0, 8, 13, 12) + >>> q.is_pure() + True + + See Also + ======== + scalar_part + + """ + + return self.a.is_zero + + def is_zero_quaternion(self): + """ + Returns true if the quaternion is a zero quaternion or false if it is not a zero quaternion + and None if the value is unknown. + + Explanation + =========== + + A zero quaternion is a quaternion with both scalar part and + vector part equal to 0. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 0, 0, 0) + >>> q.is_zero_quaternion() + False + + >>> q = Quaternion(0, 0, 0, 0) + >>> q.is_zero_quaternion() + True + + See Also + ======== + scalar_part + vector_part + + """ + + return self.norm().is_zero + + def angle(self): + r""" + Returns the angle of the quaternion measured in the real-axis plane. + + Explanation + =========== + + Given a quaternion $q = a + bi + cj + dk$ where $a$, $b$, $c$ and $d$ + are real numbers, returns the angle of the quaternion given by + + .. math:: + \theta := 2 \operatorname{atan_2}\left(\sqrt{b^2 + c^2 + d^2}, {a}\right) + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(1, 4, 4, 4) + >>> q.angle() + 2*atan(4*sqrt(3)) + + """ + + return 2 * atan2(self.vector_part().norm(), self.scalar_part()) + + + def arc_coplanar(self, other): + """ + Returns True if the transformation arcs represented by the input quaternions happen in the same plane. + + Explanation + =========== + + Two quaternions are said to be coplanar (in this arc sense) when their axes are parallel. + The plane of a quaternion is the one normal to its axis. + + Parameters + ========== + + other : a Quaternion + + Returns + ======= + + True : if the planes of the two quaternions are the same, apart from its orientation/sign. + False : if the planes of the two quaternions are not the same, apart from its orientation/sign. + None : if plane of either of the quaternion is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q1 = Quaternion(1, 4, 4, 4) + >>> q2 = Quaternion(3, 8, 8, 8) + >>> Quaternion.arc_coplanar(q1, q2) + True + + >>> q1 = Quaternion(2, 8, 13, 12) + >>> Quaternion.arc_coplanar(q1, q2) + False + + See Also + ======== + + vector_coplanar + is_pure + + """ + if (self.is_zero_quaternion()) or (other.is_zero_quaternion()): + raise ValueError('Neither of the given quaternions can be 0') + + return fuzzy_or([(self.axis() - other.axis()).is_zero_quaternion(), (self.axis() + other.axis()).is_zero_quaternion()]) + + @classmethod + def vector_coplanar(cls, q1, q2, q3): + r""" + Returns True if the axis of the pure quaternions seen as 3D vectors + ``q1``, ``q2``, and ``q3`` are coplanar. + + Explanation + =========== + + Three pure quaternions are vector coplanar if the quaternions seen as 3D vectors are coplanar. + + Parameters + ========== + + q1 + A pure Quaternion. + q2 + A pure Quaternion. + q3 + A pure Quaternion. + + Returns + ======= + + True : if the axis of the pure quaternions seen as 3D vectors + q1, q2, and q3 are coplanar. + False : if the axis of the pure quaternions seen as 3D vectors + q1, q2, and q3 are not coplanar. + None : if the axis of the pure quaternions seen as 3D vectors + q1, q2, and q3 are coplanar is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q1 = Quaternion(0, 4, 4, 4) + >>> q2 = Quaternion(0, 8, 8, 8) + >>> q3 = Quaternion(0, 24, 24, 24) + >>> Quaternion.vector_coplanar(q1, q2, q3) + True + + >>> q1 = Quaternion(0, 8, 16, 8) + >>> q2 = Quaternion(0, 8, 3, 12) + >>> Quaternion.vector_coplanar(q1, q2, q3) + False + + See Also + ======== + + axis + is_pure + + """ + + if fuzzy_not(q1.is_pure()) or fuzzy_not(q2.is_pure()) or fuzzy_not(q3.is_pure()): + raise ValueError('The given quaternions must be pure') + + M = Matrix([[q1.b, q1.c, q1.d], [q2.b, q2.c, q2.d], [q3.b, q3.c, q3.d]]).det() + return M.is_zero + + def parallel(self, other): + """ + Returns True if the two pure quaternions seen as 3D vectors are parallel. + + Explanation + =========== + + Two pure quaternions are called parallel when their vector product is commutative which + implies that the quaternions seen as 3D vectors have same direction. + + Parameters + ========== + + other : a Quaternion + + Returns + ======= + + True : if the two pure quaternions seen as 3D vectors are parallel. + False : if the two pure quaternions seen as 3D vectors are not parallel. + None : if the two pure quaternions seen as 3D vectors are parallel is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(0, 4, 4, 4) + >>> q1 = Quaternion(0, 8, 8, 8) + >>> q.parallel(q1) + True + + >>> q1 = Quaternion(0, 8, 13, 12) + >>> q.parallel(q1) + False + + """ + + if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): + raise ValueError('The provided quaternions must be pure') + + return (self*other - other*self).is_zero_quaternion() + + def orthogonal(self, other): + """ + Returns the orthogonality of two quaternions. + + Explanation + =========== + + Two pure quaternions are called orthogonal when their product is anti-commutative. + + Parameters + ========== + + other : a Quaternion + + Returns + ======= + + True : if the two pure quaternions seen as 3D vectors are orthogonal. + False : if the two pure quaternions seen as 3D vectors are not orthogonal. + None : if the two pure quaternions seen as 3D vectors are orthogonal is unknown. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(0, 4, 4, 4) + >>> q1 = Quaternion(0, 8, 8, 8) + >>> q.orthogonal(q1) + False + + >>> q1 = Quaternion(0, 2, 2, 0) + >>> q = Quaternion(0, 2, -2, 0) + >>> q.orthogonal(q1) + True + + """ + + if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): + raise ValueError('The given quaternions must be pure') + + return (self*other + other*self).is_zero_quaternion() + + def index_vector(self): + r""" + Returns the index vector of the quaternion. + + Explanation + =========== + + The index vector is given by $\mathbf{T}(q)$, the norm (or magnitude) of + the quaternion $q$, multiplied by $\mathbf{Ax}(q)$, the axis of $q$. + + Returns + ======= + + Quaternion: representing index vector of the provided quaternion. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(2, 4, 2, 4) + >>> q.index_vector() + 0 + 4*sqrt(10)/3*i + 2*sqrt(10)/3*j + 4*sqrt(10)/3*k + + See Also + ======== + + axis + norm + + """ + + return self.norm() * self.axis() + + def mensor(self): + """ + Returns the natural logarithm of the norm(magnitude) of the quaternion. + + Examples + ======== + + >>> from sympy.algebras.quaternion import Quaternion + >>> q = Quaternion(2, 4, 2, 4) + >>> q.mensor() + log(2*sqrt(10)) + >>> q.norm() + 2*sqrt(10) + + See Also + ======== + + norm + + """ + + return ln(self.norm()) diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/tests/__init__.py b/vila/lib/python3.10/site-packages/sympy/algebras/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dade86924460bb0126128700c1c17ab93bd312a5 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/test_quaternion.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/test_quaternion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14889f37fa299d48cf61581161a70c20e8c055e0 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/algebras/tests/__pycache__/test_quaternion.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/algebras/tests/test_quaternion.py b/vila/lib/python3.10/site-packages/sympy/algebras/tests/test_quaternion.py new file mode 100644 index 0000000000000000000000000000000000000000..87b68f54b5f040eecafaf6ec2a3ebf5ee20bb139 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/algebras/tests/test_quaternion.py @@ -0,0 +1,428 @@ +from sympy.testing.pytest import slow +from sympy.core.function import diff +from sympy.core.function import expand +from sympy.core.numbers import (E, I, Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import (Abs, conjugate, im, re, sign) +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, asin, cos, sin, atan2, atan) +from sympy.integrals.integrals import integrate +from sympy.matrices.dense import Matrix +from sympy.simplify import simplify +from sympy.simplify.trigsimp import trigsimp +from sympy.algebras.quaternion import Quaternion +from sympy.testing.pytest import raises +import math +from itertools import permutations, product + +w, x, y, z = symbols('w:z') +phi = symbols('phi') + +def test_quaternion_construction(): + q = Quaternion(w, x, y, z) + assert q + q == Quaternion(2*w, 2*x, 2*y, 2*z) + + q2 = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), + pi*Rational(2, 3)) + assert q2 == Quaternion(S.Half, S.Half, + S.Half, S.Half) + + M = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) + q3 = trigsimp(Quaternion.from_rotation_matrix(M)) + assert q3 == Quaternion( + sqrt(2)*sqrt(cos(phi) + 1)/2, 0, 0, sqrt(2 - 2*cos(phi))*sign(sin(phi))/2) + + nc = Symbol('nc', commutative=False) + raises(ValueError, lambda: Quaternion(w, x, nc, z)) + + +def test_quaternion_construction_norm(): + q1 = Quaternion(*symbols('a:d')) + + q2 = Quaternion(w, x, y, z) + assert expand((q1*q2).norm()**2 - (q1.norm()**2 * q2.norm()**2)) == 0 + + q3 = Quaternion(w, x, y, z, norm=1) + assert (q1 * q3).norm() == q1.norm() + + +def test_issue_25254(): + # calculating the inverse cached the norm which caused problems + # when multiplying + p = Quaternion(1, 0, 0, 0) + q = Quaternion.from_axis_angle((1, 1, 1), 3 * math.pi/4) + qi = q.inverse() # this operation cached the norm + test = q * p * qi + assert ((test - p).norm() < 1E-10) + + +def test_to_and_from_Matrix(): + q = Quaternion(w, x, y, z) + q_full = Quaternion.from_Matrix(q.to_Matrix()) + q_vect = Quaternion.from_Matrix(q.to_Matrix(True)) + assert (q - q_full).is_zero_quaternion() + assert (q.vector_part() - q_vect).is_zero_quaternion() + + +def test_product_matrices(): + q1 = Quaternion(w, x, y, z) + q2 = Quaternion(*(symbols("a:d"))) + assert (q1 * q2).to_Matrix() == q1.product_matrix_left * q2.to_Matrix() + assert (q1 * q2).to_Matrix() == q2.product_matrix_right * q1.to_Matrix() + + R1 = (q1.product_matrix_left * q1.product_matrix_right.T)[1:, 1:] + R2 = simplify(q1.to_rotation_matrix()*q1.norm()**2) + assert R1 == R2 + + +def test_quaternion_axis_angle(): + + test_data = [ # axis, angle, expected_quaternion + ((1, 0, 0), 0, (1, 0, 0, 0)), + ((1, 0, 0), pi/2, (sqrt(2)/2, sqrt(2)/2, 0, 0)), + ((0, 1, 0), pi/2, (sqrt(2)/2, 0, sqrt(2)/2, 0)), + ((0, 0, 1), pi/2, (sqrt(2)/2, 0, 0, sqrt(2)/2)), + ((1, 0, 0), pi, (0, 1, 0, 0)), + ((0, 1, 0), pi, (0, 0, 1, 0)), + ((0, 0, 1), pi, (0, 0, 0, 1)), + ((1, 1, 1), pi, (0, 1/sqrt(3),1/sqrt(3),1/sqrt(3))), + ((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*2/3, (S.Half, S.Half, S.Half, S.Half)) + ] + + for axis, angle, expected in test_data: + assert Quaternion.from_axis_angle(axis, angle) == Quaternion(*expected) + + +def test_quaternion_axis_angle_simplification(): + result = Quaternion.from_axis_angle((1, 2, 3), asin(4)) + assert result.a == cos(asin(4)/2) + assert result.b == sqrt(14)*sin(asin(4)/2)/14 + assert result.c == sqrt(14)*sin(asin(4)/2)/7 + assert result.d == 3*sqrt(14)*sin(asin(4)/2)/14 + +def test_quaternion_complex_real_addition(): + a = symbols("a", complex=True) + b = symbols("b", real=True) + # This symbol is not complex: + c = symbols("c", commutative=False) + + q = Quaternion(w, x, y, z) + assert a + q == Quaternion(w + re(a), x + im(a), y, z) + assert 1 + q == Quaternion(1 + w, x, y, z) + assert I + q == Quaternion(w, 1 + x, y, z) + assert b + q == Quaternion(w + b, x, y, z) + raises(ValueError, lambda: c + q) + raises(ValueError, lambda: q * c) + raises(ValueError, lambda: c * q) + + assert -q == Quaternion(-w, -x, -y, -z) + + q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + q2 = Quaternion(1, 4, 7, 8) + + assert q1 + (2 + 3*I) == Quaternion(5 + 7*I, 2 + 5*I, 0, 7 + 8*I) + assert q2 + (2 + 3*I) == Quaternion(3, 7, 7, 8) + assert q1 * (2 + 3*I) == \ + Quaternion((2 + 3*I)*(3 + 4*I), (2 + 3*I)*(2 + 5*I), 0, (2 + 3*I)*(7 + 8*I)) + assert q2 * (2 + 3*I) == Quaternion(-10, 11, 38, -5) + + q1 = Quaternion(1, 2, 3, 4) + q0 = Quaternion(0, 0, 0, 0) + assert q1 + q0 == q1 + assert q1 - q0 == q1 + assert q1 - q1 == q0 + + +def test_quaternion_subs(): + q = Quaternion.from_axis_angle((0, 0, 1), phi) + assert q.subs(phi, 0) == Quaternion(1, 0, 0, 0) + + +def test_quaternion_evalf(): + assert (Quaternion(sqrt(2), 0, 0, sqrt(3)).evalf() == + Quaternion(sqrt(2).evalf(), 0, 0, sqrt(3).evalf())) + assert (Quaternion(1/sqrt(2), 0, 0, 1/sqrt(2)).evalf() == + Quaternion((1/sqrt(2)).evalf(), 0, 0, (1/sqrt(2)).evalf())) + + +def test_quaternion_functions(): + q = Quaternion(w, x, y, z) + q1 = Quaternion(1, 2, 3, 4) + q0 = Quaternion(0, 0, 0, 0) + + assert conjugate(q) == Quaternion(w, -x, -y, -z) + assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) + assert q.normalize() == Quaternion(w, x, y, z) / sqrt(w**2 + x**2 + y**2 + z**2) + assert q.inverse() == Quaternion(w, -x, -y, -z) / (w**2 + x**2 + y**2 + z**2) + assert q.inverse() == q.pow(-1) + raises(ValueError, lambda: q0.inverse()) + assert q.pow(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) + assert q**(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) + assert q1.pow(-2) == Quaternion( + Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) + assert q1**(-2) == Quaternion( + Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) + assert q1.pow(-0.5) == NotImplemented + raises(TypeError, lambda: q1**(-0.5)) + + assert q1.exp() == \ + Quaternion(E * cos(sqrt(29)), + 2 * sqrt(29) * E * sin(sqrt(29)) / 29, + 3 * sqrt(29) * E * sin(sqrt(29)) / 29, + 4 * sqrt(29) * E * sin(sqrt(29)) / 29) + assert q1.log() == \ + Quaternion(log(sqrt(30)), + 2 * sqrt(29) * acos(sqrt(30)/30) / 29, + 3 * sqrt(29) * acos(sqrt(30)/30) / 29, + 4 * sqrt(29) * acos(sqrt(30)/30) / 29) + + assert q1.pow_cos_sin(2) == \ + Quaternion(30 * cos(2 * acos(sqrt(30)/30)), + 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, + 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, + 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) + + assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) + + assert integrate(Quaternion(x, x, x, x), x) == \ + Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) + + assert Quaternion.rotate_point((1, 1, 1), q1) == (S.One / 5, 1, S(7) / 5) + n = Symbol('n') + raises(TypeError, lambda: q1**n) + n = Symbol('n', integer=True) + raises(TypeError, lambda: q1**n) + + assert Quaternion(22, 23, 55, 8).scalar_part() == 22 + assert Quaternion(w, x, y, z).scalar_part() == w + + assert Quaternion(22, 23, 55, 8).vector_part() == Quaternion(0, 23, 55, 8) + assert Quaternion(w, x, y, z).vector_part() == Quaternion(0, x, y, z) + + assert q1.axis() == Quaternion(0, 2*sqrt(29)/29, 3*sqrt(29)/29, 4*sqrt(29)/29) + assert q1.axis().pow(2) == Quaternion(-1, 0, 0, 0) + assert q0.axis().scalar_part() == 0 + assert (q.axis() == Quaternion(0, + x/sqrt(x**2 + y**2 + z**2), + y/sqrt(x**2 + y**2 + z**2), + z/sqrt(x**2 + y**2 + z**2))) + + assert q0.is_pure() is True + assert q1.is_pure() is False + assert Quaternion(0, 0, 0, 3).is_pure() is True + assert Quaternion(0, 2, 10, 3).is_pure() is True + assert Quaternion(w, 2, 10, 3).is_pure() is None + + assert q1.angle() == 2*atan(sqrt(29)) + assert q.angle() == 2*atan2(sqrt(x**2 + y**2 + z**2), w) + + assert Quaternion.arc_coplanar(q1, Quaternion(2, 4, 6, 8)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(1, -2, -3, -4)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(1, 8, 12, 16)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(1, 2, 3, 4)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(w, 4, 6, 8)) is True + assert Quaternion.arc_coplanar(q1, Quaternion(2, 7, 4, 1)) is False + assert Quaternion.arc_coplanar(q1, Quaternion(w, x, y, z)) is None + raises(ValueError, lambda: Quaternion.arc_coplanar(q1, q0)) + + assert Quaternion.vector_coplanar( + Quaternion(0, 8, 12, 16), + Quaternion(0, 4, 6, 8), + Quaternion(0, 2, 3, 4)) is True + assert Quaternion.vector_coplanar( + Quaternion(0, 0, 0, 0), Quaternion(0, 4, 6, 8), Quaternion(0, 2, 3, 4)) is True + assert Quaternion.vector_coplanar( + Quaternion(0, 8, 2, 6), Quaternion(0, 1, 6, 6), Quaternion(0, 0, 3, 4)) is False + assert Quaternion.vector_coplanar( + Quaternion(0, 1, 3, 4), + Quaternion(0, 4, w, 6), + Quaternion(0, 6, 8, 1)) is None + raises(ValueError, lambda: + Quaternion.vector_coplanar(q0, Quaternion(0, 4, 6, 8), q1)) + + assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 4, 6)) is True + assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 2, 6)) is False + assert Quaternion(0, 1, 2, 3).parallel(Quaternion(w, x, y, 6)) is None + raises(ValueError, lambda: q0.parallel(q1)) + + assert Quaternion(0, 1, 2, 3).orthogonal(Quaternion(0, -2, 1, 0)) is True + assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(0, 2, 2, 6)) is False + assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(w, x, y, 6)) is None + raises(ValueError, lambda: q0.orthogonal(q1)) + + assert q1.index_vector() == Quaternion( + 0, 2*sqrt(870)/29, + 3*sqrt(870)/29, + 4*sqrt(870)/29) + assert Quaternion(0, 3, 9, 4).index_vector() == Quaternion(0, 3, 9, 4) + + assert Quaternion(4, 3, 9, 4).mensor() == log(sqrt(122)) + assert Quaternion(3, 3, 0, 2).mensor() == log(sqrt(22)) + + assert q0.is_zero_quaternion() is True + assert q1.is_zero_quaternion() is False + assert Quaternion(w, 0, 0, 0).is_zero_quaternion() is None + +def test_quaternion_conversions(): + q1 = Quaternion(1, 2, 3, 4) + + assert q1.to_axis_angle() == ((2 * sqrt(29)/29, + 3 * sqrt(29)/29, + 4 * sqrt(29)/29), + 2 * acos(sqrt(30)/30)) + + assert (q1.to_rotation_matrix() == + Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15)], + [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], + [Rational(1, 3), Rational(14, 15), Rational(2, 15)]])) + + assert (q1.to_rotation_matrix((1, 1, 1)) == + Matrix([ + [Rational(-2, 3), Rational(2, 15), Rational(11, 15), Rational(4, 5)], + [Rational(2, 3), Rational(-1, 3), Rational(2, 3), S.Zero], + [Rational(1, 3), Rational(14, 15), Rational(2, 15), Rational(-2, 5)], + [S.Zero, S.Zero, S.Zero, S.One]])) + + theta = symbols("theta", real=True) + q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) + + assert trigsimp(q2.to_rotation_matrix()) == Matrix([ + [cos(theta), -sin(theta), 0], + [sin(theta), cos(theta), 0], + [0, 0, 1]]) + + assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))), + 2*acos(cos(theta/2))) + + assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([ + [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1], + [sin(theta), cos(theta), 0, -sin(theta) - cos(theta) + 1], + [0, 0, 1, 0], + [0, 0, 0, 1]]) + + +def test_rotation_matrix_homogeneous(): + q = Quaternion(w, x, y, z) + R1 = q.to_rotation_matrix(homogeneous=True) * q.norm()**2 + R2 = simplify(q.to_rotation_matrix(homogeneous=False) * q.norm()**2) + assert R1 == R2 + + +def test_quaternion_rotation_iss1593(): + """ + There was a sign mistake in the definition, + of the rotation matrix. This tests that particular sign mistake. + See issue 1593 for reference. + See wikipedia + https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix + for the correct definition + """ + q = Quaternion(cos(phi/2), sin(phi/2), 0, 0) + assert(trigsimp(q.to_rotation_matrix()) == Matrix([ + [1, 0, 0], + [0, cos(phi), -sin(phi)], + [0, sin(phi), cos(phi)]])) + + +def test_quaternion_multiplication(): + q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) + q2 = Quaternion(1, 2, 3, 5) + q3 = Quaternion(1, 1, 1, y) + + assert Quaternion._generic_mul(S(4), S.One) == 4 + assert (Quaternion._generic_mul(S(4), q1) == + Quaternion(12 + 16*I, 8 + 20*I, 0, 28 + 32*I)) + assert q2.mul(2) == Quaternion(2, 4, 6, 10) + assert q2.mul(q3) == Quaternion(-5*y - 4, 3*y - 2, 9 - 2*y, y + 4) + assert q2.mul(q3) == q2*q3 + + z = symbols('z', complex=True) + z_quat = Quaternion(re(z), im(z), 0, 0) + q = Quaternion(*symbols('q:4', real=True)) + + assert z * q == z_quat * q + assert q * z == q * z_quat + + +def test_issue_16318(): + #for rtruediv + q0 = Quaternion(0, 0, 0, 0) + raises(ValueError, lambda: 1/q0) + #for rotate_point + q = Quaternion(1, 2, 3, 4) + (axis, angle) = q.to_axis_angle() + assert Quaternion.rotate_point((1, 1, 1), (axis, angle)) == (S.One / 5, 1, S(7) / 5) + #test for to_axis_angle + q = Quaternion(-1, 1, 1, 1) + axis = (-sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3) + angle = 2*pi/3 + assert (axis, angle) == q.to_axis_angle() + + +@slow +def test_to_euler(): + q = Quaternion(w, x, y, z) + q_normalized = q.normalize() + + seqs = ['zxy', 'zyx', 'zyz', 'zxz'] + seqs += [seq.upper() for seq in seqs] + + for seq in seqs: + euler_from_q = q.to_euler(seq) + q_back = simplify(Quaternion.from_euler(euler_from_q, seq)) + assert q_back == q_normalized + + +def test_to_euler_iss24504(): + """ + There was a mistake in the degenerate case testing + See issue 24504 for reference. + """ + q = Quaternion.from_euler((phi, 0, 0), 'zyz') + assert trigsimp(q.to_euler('zyz'), inverse=True) == (phi, 0, 0) + + +def test_to_euler_numerical_singilarities(): + + def test_one_case(angles, seq): + q = Quaternion.from_euler(angles, seq) + assert q.to_euler(seq) == angles + + # symmetric + test_one_case((pi/2, 0, 0), 'zyz') + test_one_case((pi/2, 0, 0), 'ZYZ') + test_one_case((pi/2, pi, 0), 'zyz') + test_one_case((pi/2, pi, 0), 'ZYZ') + + # asymmetric + test_one_case((pi/2, pi/2, 0), 'zyx') + test_one_case((pi/2, -pi/2, 0), 'zyx') + test_one_case((pi/2, pi/2, 0), 'ZYX') + test_one_case((pi/2, -pi/2, 0), 'ZYX') + + +@slow +def test_to_euler_options(): + def test_one_case(q): + angles1 = Matrix(q.to_euler(seq, True, True)) + angles2 = Matrix(q.to_euler(seq, False, False)) + angle_errors = simplify(angles1-angles2).evalf() + for angle_error in angle_errors: + # forcing angles to set {-pi, pi} + angle_error = (angle_error + pi) % (2 * pi) - pi + assert angle_error < 10e-7 + + for xyz in ('xyz', 'XYZ'): + for seq_tuple in permutations(xyz): + for symmetric in (True, False): + if symmetric: + seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) + else: + seq = ''.join(seq_tuple) + + for elements in product([-1, 0, 1], repeat=4): + q = Quaternion(*elements) + if not q.is_zero_quaternion(): + test_one_case(q) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/__init__.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57d88c7ab12f5fbf05c2ee172ae85fa8e03482a8 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/__init__.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/ask.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/ask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6b637444265cdd642c56e4d312ad439207fb5cb Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/ask.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/ask_generated.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/ask_generated.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a1f348d27630f657cb80b43da95d591f24cf0bf Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/ask_generated.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/assume.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/assume.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7746a5026a4ace2c25c94d0481519e0c3d46105 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/assume.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/cnf.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/cnf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67684dcfa9a8450e4f3f9d42a7a25a043f1f8000 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/cnf.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/facts.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/facts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd1cfcc867a2743f8982a20e54e3b4cc41a28e49 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/facts.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/lra_satask.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/lra_satask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4889eb817e56e9b15cf4aaf7bbac16d24856a1c Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/lra_satask.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/refine.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/refine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a96f630ee48ae5bfb15cc5e8268a59129179a18 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/refine.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/satask.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/satask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c98afe745a148b5bce6e73f319f70e91e49379f6 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/satask.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/sathandlers.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/sathandlers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d641787618a28cd1893d0bdd46cc0f8c57337484 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/sathandlers.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/wrapper.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db09c8c1bf7c4b42170487ceb0a4c6a423fa3a7b Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/__pycache__/wrapper.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/ask.py b/vila/lib/python3.10/site-packages/sympy/assumptions/ask.py new file mode 100644 index 0000000000000000000000000000000000000000..ec81ec8ecce245c2a798cf9e71af1e9373292bc1 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/ask.py @@ -0,0 +1,651 @@ +"""Module for querying SymPy objects about assumptions.""" + +from sympy.assumptions.assume import (global_assumptions, Predicate, + AppliedPredicate) +from sympy.assumptions.cnf import CNF, EncodedCNF, Literal +from sympy.core import sympify +from sympy.core.kind import BooleanKind +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.logic.inference import satisfiable +from sympy.utilities.decorator import memoize_property +from sympy.utilities.exceptions import (sympy_deprecation_warning, + SymPyDeprecationWarning, + ignore_warnings) + + +# Memoization is necessary for the properties of AssumptionKeys to +# ensure that only one object of Predicate objects are created. +# This is because assumption handlers are registered on those objects. + + +class AssumptionKeys: + """ + This class contains all the supported keys by ``ask``. + It should be accessed via the instance ``sympy.Q``. + + """ + + # DO NOT add methods or properties other than predicate keys. + # SAT solver checks the properties of Q and use them to compute the + # fact system. Non-predicate attributes will break this. + + @memoize_property + def hermitian(self): + from .handlers.sets import HermitianPredicate + return HermitianPredicate() + + @memoize_property + def antihermitian(self): + from .handlers.sets import AntihermitianPredicate + return AntihermitianPredicate() + + @memoize_property + def real(self): + from .handlers.sets import RealPredicate + return RealPredicate() + + @memoize_property + def extended_real(self): + from .handlers.sets import ExtendedRealPredicate + return ExtendedRealPredicate() + + @memoize_property + def imaginary(self): + from .handlers.sets import ImaginaryPredicate + return ImaginaryPredicate() + + @memoize_property + def complex(self): + from .handlers.sets import ComplexPredicate + return ComplexPredicate() + + @memoize_property + def algebraic(self): + from .handlers.sets import AlgebraicPredicate + return AlgebraicPredicate() + + @memoize_property + def transcendental(self): + from .predicates.sets import TranscendentalPredicate + return TranscendentalPredicate() + + @memoize_property + def integer(self): + from .handlers.sets import IntegerPredicate + return IntegerPredicate() + + @memoize_property + def noninteger(self): + from .predicates.sets import NonIntegerPredicate + return NonIntegerPredicate() + + @memoize_property + def rational(self): + from .handlers.sets import RationalPredicate + return RationalPredicate() + + @memoize_property + def irrational(self): + from .handlers.sets import IrrationalPredicate + return IrrationalPredicate() + + @memoize_property + def finite(self): + from .handlers.calculus import FinitePredicate + return FinitePredicate() + + @memoize_property + def infinite(self): + from .handlers.calculus import InfinitePredicate + return InfinitePredicate() + + @memoize_property + def positive_infinite(self): + from .handlers.calculus import PositiveInfinitePredicate + return PositiveInfinitePredicate() + + @memoize_property + def negative_infinite(self): + from .handlers.calculus import NegativeInfinitePredicate + return NegativeInfinitePredicate() + + @memoize_property + def positive(self): + from .handlers.order import PositivePredicate + return PositivePredicate() + + @memoize_property + def negative(self): + from .handlers.order import NegativePredicate + return NegativePredicate() + + @memoize_property + def zero(self): + from .handlers.order import ZeroPredicate + return ZeroPredicate() + + @memoize_property + def extended_positive(self): + from .handlers.order import ExtendedPositivePredicate + return ExtendedPositivePredicate() + + @memoize_property + def extended_negative(self): + from .handlers.order import ExtendedNegativePredicate + return ExtendedNegativePredicate() + + @memoize_property + def nonzero(self): + from .handlers.order import NonZeroPredicate + return NonZeroPredicate() + + @memoize_property + def nonpositive(self): + from .handlers.order import NonPositivePredicate + return NonPositivePredicate() + + @memoize_property + def nonnegative(self): + from .handlers.order import NonNegativePredicate + return NonNegativePredicate() + + @memoize_property + def extended_nonzero(self): + from .handlers.order import ExtendedNonZeroPredicate + return ExtendedNonZeroPredicate() + + @memoize_property + def extended_nonpositive(self): + from .handlers.order import ExtendedNonPositivePredicate + return ExtendedNonPositivePredicate() + + @memoize_property + def extended_nonnegative(self): + from .handlers.order import ExtendedNonNegativePredicate + return ExtendedNonNegativePredicate() + + @memoize_property + def even(self): + from .handlers.ntheory import EvenPredicate + return EvenPredicate() + + @memoize_property + def odd(self): + from .handlers.ntheory import OddPredicate + return OddPredicate() + + @memoize_property + def prime(self): + from .handlers.ntheory import PrimePredicate + return PrimePredicate() + + @memoize_property + def composite(self): + from .handlers.ntheory import CompositePredicate + return CompositePredicate() + + @memoize_property + def commutative(self): + from .handlers.common import CommutativePredicate + return CommutativePredicate() + + @memoize_property + def is_true(self): + from .handlers.common import IsTruePredicate + return IsTruePredicate() + + @memoize_property + def symmetric(self): + from .handlers.matrices import SymmetricPredicate + return SymmetricPredicate() + + @memoize_property + def invertible(self): + from .handlers.matrices import InvertiblePredicate + return InvertiblePredicate() + + @memoize_property + def orthogonal(self): + from .handlers.matrices import OrthogonalPredicate + return OrthogonalPredicate() + + @memoize_property + def unitary(self): + from .handlers.matrices import UnitaryPredicate + return UnitaryPredicate() + + @memoize_property + def positive_definite(self): + from .handlers.matrices import PositiveDefinitePredicate + return PositiveDefinitePredicate() + + @memoize_property + def upper_triangular(self): + from .handlers.matrices import UpperTriangularPredicate + return UpperTriangularPredicate() + + @memoize_property + def lower_triangular(self): + from .handlers.matrices import LowerTriangularPredicate + return LowerTriangularPredicate() + + @memoize_property + def diagonal(self): + from .handlers.matrices import DiagonalPredicate + return DiagonalPredicate() + + @memoize_property + def fullrank(self): + from .handlers.matrices import FullRankPredicate + return FullRankPredicate() + + @memoize_property + def square(self): + from .handlers.matrices import SquarePredicate + return SquarePredicate() + + @memoize_property + def integer_elements(self): + from .handlers.matrices import IntegerElementsPredicate + return IntegerElementsPredicate() + + @memoize_property + def real_elements(self): + from .handlers.matrices import RealElementsPredicate + return RealElementsPredicate() + + @memoize_property + def complex_elements(self): + from .handlers.matrices import ComplexElementsPredicate + return ComplexElementsPredicate() + + @memoize_property + def singular(self): + from .predicates.matrices import SingularPredicate + return SingularPredicate() + + @memoize_property + def normal(self): + from .predicates.matrices import NormalPredicate + return NormalPredicate() + + @memoize_property + def triangular(self): + from .predicates.matrices import TriangularPredicate + return TriangularPredicate() + + @memoize_property + def unit_triangular(self): + from .predicates.matrices import UnitTriangularPredicate + return UnitTriangularPredicate() + + @memoize_property + def eq(self): + from .relation.equality import EqualityPredicate + return EqualityPredicate() + + @memoize_property + def ne(self): + from .relation.equality import UnequalityPredicate + return UnequalityPredicate() + + @memoize_property + def gt(self): + from .relation.equality import StrictGreaterThanPredicate + return StrictGreaterThanPredicate() + + @memoize_property + def ge(self): + from .relation.equality import GreaterThanPredicate + return GreaterThanPredicate() + + @memoize_property + def lt(self): + from .relation.equality import StrictLessThanPredicate + return StrictLessThanPredicate() + + @memoize_property + def le(self): + from .relation.equality import LessThanPredicate + return LessThanPredicate() + + +Q = AssumptionKeys() + +def _extract_all_facts(assump, exprs): + """ + Extract all relevant assumptions from *assump* with respect to given *exprs*. + + Parameters + ========== + + assump : sympy.assumptions.cnf.CNF + + exprs : tuple of expressions + + Returns + ======= + + sympy.assumptions.cnf.CNF + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.ask import _extract_all_facts + >>> from sympy.abc import x, y + >>> assump = CNF.from_prop(Q.positive(x) & Q.integer(y)) + >>> exprs = (x,) + >>> cnf = _extract_all_facts(assump, exprs) + >>> cnf.clauses + {frozenset({Literal(Q.positive, False)})} + + """ + facts = set() + + for clause in assump.clauses: + args = [] + for literal in clause: + if isinstance(literal.lit, AppliedPredicate) and len(literal.lit.arguments) == 1: + if literal.lit.arg in exprs: + # Add literal if it has matching in it + args.append(Literal(literal.lit.function, literal.is_Not)) + else: + # If any of the literals doesn't have matching expr don't add the whole clause. + break + else: + # If any of the literals aren't unary predicate don't add the whole clause. + break + + else: + if args: + facts.add(frozenset(args)) + return CNF(facts) + + +def ask(proposition, assumptions=True, context=global_assumptions): + """ + Function to evaluate the proposition with assumptions. + + Explanation + =========== + + This function evaluates the proposition to ``True`` or ``False`` if + the truth value can be determined. If not, it returns ``None``. + + It should be discerned from :func:`~.refine` which, when applied to a + proposition, simplifies the argument to symbolic ``Boolean`` instead of + Python built-in ``True``, ``False`` or ``None``. + + **Syntax** + + * ask(proposition) + Evaluate the *proposition* in global assumption context. + + * ask(proposition, assumptions) + Evaluate the *proposition* with respect to *assumptions* in + global assumption context. + + Parameters + ========== + + proposition : Boolean + Proposition which will be evaluated to boolean value. If this is + not ``AppliedPredicate``, it will be wrapped by ``Q.is_true``. + + assumptions : Boolean, optional + Local assumptions to evaluate the *proposition*. + + context : AssumptionsContext, optional + Default assumptions to evaluate the *proposition*. By default, + this is ``sympy.assumptions.global_assumptions`` variable. + + Returns + ======= + + ``True``, ``False``, or ``None`` + + Raises + ====== + + TypeError : *proposition* or *assumptions* is not valid logical expression. + + ValueError : assumptions are inconsistent. + + Examples + ======== + + >>> from sympy import ask, Q, pi + >>> from sympy.abc import x, y + >>> ask(Q.rational(pi)) + False + >>> ask(Q.even(x*y), Q.even(x) & Q.integer(y)) + True + >>> ask(Q.prime(4*x), Q.integer(x)) + False + + If the truth value cannot be determined, ``None`` will be returned. + + >>> print(ask(Q.odd(3*x))) # cannot determine unless we know x + None + + ``ValueError`` is raised if assumptions are inconsistent. + + >>> ask(Q.integer(x), Q.even(x) & Q.odd(x)) + Traceback (most recent call last): + ... + ValueError: inconsistent assumptions Q.even(x) & Q.odd(x) + + Notes + ===== + + Relations in assumptions are not implemented (yet), so the following + will not give a meaningful result. + + >>> ask(Q.positive(x), x > 0) + + It is however a work in progress. + + See Also + ======== + + sympy.assumptions.refine.refine : Simplification using assumptions. + Proposition is not reduced to ``None`` if the truth value cannot + be determined. + """ + from sympy.assumptions.satask import satask + from sympy.assumptions.lra_satask import lra_satask + from sympy.logic.algorithms.lra_theory import UnhandledInput + + proposition = sympify(proposition) + assumptions = sympify(assumptions) + + if isinstance(proposition, Predicate) or proposition.kind is not BooleanKind: + raise TypeError("proposition must be a valid logical expression") + + if isinstance(assumptions, Predicate) or assumptions.kind is not BooleanKind: + raise TypeError("assumptions must be a valid logical expression") + + binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + if isinstance(proposition, AppliedPredicate): + key, args = proposition.function, proposition.arguments + elif proposition.func in binrelpreds: + key, args = binrelpreds[type(proposition)], proposition.args + else: + key, args = Q.is_true, (proposition,) + + # convert local and global assumptions to CNF + assump_cnf = CNF.from_prop(assumptions) + assump_cnf.extend(context) + + # extract the relevant facts from assumptions with respect to args + local_facts = _extract_all_facts(assump_cnf, args) + + # convert default facts and assumed facts to encoded CNF + known_facts_cnf = get_all_known_facts() + enc_cnf = EncodedCNF() + enc_cnf.from_cnf(CNF(known_facts_cnf)) + enc_cnf.add_from_cnf(local_facts) + + # check the satisfiability of given assumptions + if local_facts.clauses and satisfiable(enc_cnf) is False: + raise ValueError("inconsistent assumptions %s" % assumptions) + + # quick computation for single fact + res = _ask_single_fact(key, local_facts) + if res is not None: + return res + + # direct resolution method, no logic + res = key(*args)._eval_ask(assumptions) + if res is not None: + return bool(res) + + # using satask (still costly) + res = satask(proposition, assumptions=assumptions, context=context) + if res is not None: + return res + + try: + res = lra_satask(proposition, assumptions=assumptions, context=context) + except UnhandledInput: + return None + + return res + + +def _ask_single_fact(key, local_facts): + """ + Compute the truth value of single predicate using assumptions. + + Parameters + ========== + + key : sympy.assumptions.assume.Predicate + Proposition predicate. + + local_facts : sympy.assumptions.cnf.CNF + Local assumption in CNF form. + + Returns + ======= + + ``True``, ``False`` or ``None`` + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.ask import _ask_single_fact + + If prerequisite of proposition is rejected by the assumption, + return ``False``. + + >>> key, assump = Q.zero, ~Q.zero + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + False + >>> key, assump = Q.zero, ~Q.even + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + False + + If assumption implies the proposition, return ``True``. + + >>> key, assump = Q.even, Q.zero + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + True + + If proposition rejects the assumption, return ``False``. + + >>> key, assump = Q.even, Q.odd + >>> local_facts = CNF.from_prop(assump) + >>> _ask_single_fact(key, local_facts) + False + """ + if local_facts.clauses: + + known_facts_dict = get_known_facts_dict() + + if len(local_facts.clauses) == 1: + cl, = local_facts.clauses + if len(cl) == 1: + f, = cl + prop_facts = known_facts_dict.get(key, None) + prop_req = prop_facts[0] if prop_facts is not None else set() + if f.is_Not and f.arg in prop_req: + # the prerequisite of proposition is rejected + return False + + for clause in local_facts.clauses: + if len(clause) == 1: + f, = clause + prop_facts = known_facts_dict.get(f.arg, None) if not f.is_Not else None + if prop_facts is None: + continue + + prop_req, prop_rej = prop_facts + if key in prop_req: + # assumption implies the proposition + return True + elif key in prop_rej: + # proposition rejects the assumption + return False + + return None + + +def register_handler(key, handler): + """ + Register a handler in the ask system. key must be a string and handler a + class inheriting from AskHandler. + + .. deprecated:: 1.8. + Use multipledispatch handler instead. See :obj:`~.Predicate`. + + """ + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. The register_handler() function + should be replaced with the multipledispatch handler of Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + if isinstance(key, Predicate): + key = key.name.name + Qkey = getattr(Q, key, None) + if Qkey is not None: + Qkey.add_handler(handler) + else: + setattr(Q, key, Predicate(key, handlers=[handler])) + + +def remove_handler(key, handler): + """ + Removes a handler from the ask system. + + .. deprecated:: 1.8. + Use multipledispatch handler instead. See :obj:`~.Predicate`. + + """ + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. The remove_handler() function + should be replaced with the multipledispatch handler of Predicate. + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + if isinstance(key, Predicate): + key = key.name.name + # Don't show the same warning again recursively + with ignore_warnings(SymPyDeprecationWarning): + getattr(Q, key).remove_handler(handler) + + +from sympy.assumptions.ask_generated import (get_all_known_facts, + get_known_facts_dict) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/cnf.py b/vila/lib/python3.10/site-packages/sympy/assumptions/cnf.py new file mode 100644 index 0000000000000000000000000000000000000000..a95d27bed6eeb64c42f4edd9d49bd8e5753069e5 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/cnf.py @@ -0,0 +1,445 @@ +""" +The classes used here are for the internal use of assumptions system +only and should not be used anywhere else as these do not possess the +signatures common to SymPy objects. For general use of logic constructs +please refer to sympy.logic classes And, Or, Not, etc. +""" +from itertools import combinations, product, zip_longest +from sympy.assumptions.assume import AppliedPredicate, Predicate +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.core.singleton import S +from sympy.logic.boolalg import Or, And, Not, Xnor +from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor) + + +class Literal: + """ + The smallest element of a CNF object. + + Parameters + ========== + + lit : Boolean expression + + is_Not : bool + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import Literal + >>> from sympy.abc import x + >>> Literal(Q.even(x)) + Literal(Q.even(x), False) + >>> Literal(~Q.even(x)) + Literal(Q.even(x), True) + """ + + def __new__(cls, lit, is_Not=False): + if isinstance(lit, Not): + lit = lit.args[0] + is_Not = True + elif isinstance(lit, (AND, OR, Literal)): + return ~lit if is_Not else lit + obj = super().__new__(cls) + obj.lit = lit + obj.is_Not = is_Not + return obj + + @property + def arg(self): + return self.lit + + def rcall(self, expr): + if callable(self.lit): + lit = self.lit(expr) + else: + lit = self.lit.apply(expr) + return type(self)(lit, self.is_Not) + + def __invert__(self): + is_Not = not self.is_Not + return Literal(self.lit, is_Not) + + def __str__(self): + return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not) + + __repr__ = __str__ + + def __eq__(self, other): + return self.arg == other.arg and self.is_Not == other.is_Not + + def __hash__(self): + h = hash((type(self).__name__, self.arg, self.is_Not)) + return h + + +class OR: + """ + A low-level implementation for Or + """ + def __init__(self, *args): + self._args = args + + @property + def args(self): + return sorted(self._args, key=str) + + def rcall(self, expr): + return type(self)(*[arg.rcall(expr) + for arg in self._args + ]) + + def __invert__(self): + return AND(*[~arg for arg in self._args]) + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(self, other): + return self.args == other.args + + def __str__(self): + s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')' + return s + + __repr__ = __str__ + + +class AND: + """ + A low-level implementation for And + """ + def __init__(self, *args): + self._args = args + + def __invert__(self): + return OR(*[~arg for arg in self._args]) + + @property + def args(self): + return sorted(self._args, key=str) + + def rcall(self, expr): + return type(self)(*[arg.rcall(expr) + for arg in self._args + ]) + + def __hash__(self): + return hash((type(self).__name__,) + tuple(self.args)) + + def __eq__(self, other): + return self.args == other.args + + def __str__(self): + s = '('+' & '.join([str(arg) for arg in self.args])+')' + return s + + __repr__ = __str__ + + +def to_NNF(expr, composite_map=None): + """ + Generates the Negation Normal Form of any boolean expression in terms + of AND, OR, and Literal objects. + + Examples + ======== + + >>> from sympy import Q, Eq + >>> from sympy.assumptions.cnf import to_NNF + >>> from sympy.abc import x, y + >>> expr = Q.even(x) & ~Q.positive(x) + >>> to_NNF(expr) + (Literal(Q.even(x), False) & Literal(Q.positive(x), True)) + + Supported boolean objects are converted to corresponding predicates. + + >>> to_NNF(Eq(x, y)) + Literal(Q.eq(x, y), False) + + If ``composite_map`` argument is given, ``to_NNF`` decomposes the + specified predicate into a combination of primitive predicates. + + >>> cmap = {Q.nonpositive: Q.negative | Q.zero} + >>> to_NNF(Q.nonpositive, cmap) + (Literal(Q.negative, False) | Literal(Q.zero, False)) + >>> to_NNF(Q.nonpositive(x), cmap) + (Literal(Q.negative(x), False) | Literal(Q.zero(x), False)) + """ + from sympy.assumptions.ask import Q + + if composite_map is None: + composite_map = {} + + + binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + if type(expr) in binrelpreds: + pred = binrelpreds[type(expr)] + expr = pred(*expr.args) + + if isinstance(expr, Not): + arg = expr.args[0] + tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr + return ~tmp + + if isinstance(expr, Or): + return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)]) + + if isinstance(expr, And): + return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)]) + + if isinstance(expr, Nand): + tmp = AND(*[to_NNF(x, composite_map) for x in expr.args]) + return ~tmp + + if isinstance(expr, Nor): + tmp = OR(*[to_NNF(x, composite_map) for x in expr.args]) + return ~tmp + + if isinstance(expr, Xor): + cnfs = [] + for i in range(0, len(expr.args) + 1, 2): + for neg in combinations(expr.args, i): + clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) + for s in expr.args] + cnfs.append(OR(*clause)) + return AND(*cnfs) + + if isinstance(expr, Xnor): + cnfs = [] + for i in range(0, len(expr.args) + 1, 2): + for neg in combinations(expr.args, i): + clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) + for s in expr.args] + cnfs.append(OR(*clause)) + return ~AND(*cnfs) + + if isinstance(expr, Implies): + L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map) + return OR(~L, R) + + if isinstance(expr, Equivalent): + cnfs = [] + for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]): + a = to_NNF(a, composite_map) + b = to_NNF(b, composite_map) + cnfs.append(OR(~a, b)) + return AND(*cnfs) + + if isinstance(expr, ITE): + L = to_NNF(expr.args[0], composite_map) + M = to_NNF(expr.args[1], composite_map) + R = to_NNF(expr.args[2], composite_map) + return AND(OR(~L, M), OR(L, R)) + + if isinstance(expr, AppliedPredicate): + pred, args = expr.function, expr.arguments + newpred = composite_map.get(pred, None) + if newpred is not None: + return to_NNF(newpred.rcall(*args), composite_map) + + if isinstance(expr, Predicate): + newpred = composite_map.get(expr, None) + if newpred is not None: + return to_NNF(newpred, composite_map) + + return Literal(expr) + + +def distribute_AND_over_OR(expr): + """ + Distributes AND over OR in the NNF expression. + Returns the result( Conjunctive Normal Form of expression) + as a CNF object. + """ + if not isinstance(expr, (AND, OR)): + tmp = set() + tmp.add(frozenset((expr,))) + return CNF(tmp) + + if isinstance(expr, OR): + return CNF.all_or(*[distribute_AND_over_OR(arg) + for arg in expr._args]) + + if isinstance(expr, AND): + return CNF.all_and(*[distribute_AND_over_OR(arg) + for arg in expr._args]) + + +class CNF: + """ + Class to represent CNF of a Boolean expression. + Consists of set of clauses, which themselves are stored as + frozenset of Literal objects. + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.abc import x + >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x)) + >>> cnf.clauses + {frozenset({Literal(Q.zero(x), True)}), + frozenset({Literal(Q.negative(x), False), + Literal(Q.positive(x), False), Literal(Q.zero(x), False)})} + """ + def __init__(self, clauses=None): + if not clauses: + clauses = set() + self.clauses = clauses + + def add(self, prop): + clauses = CNF.to_CNF(prop).clauses + self.add_clauses(clauses) + + def __str__(self): + s = ' & '.join( + ['(' + ' | '.join([str(lit) for lit in clause]) +')' + for clause in self.clauses] + ) + return s + + def extend(self, props): + for p in props: + self.add(p) + return self + + def copy(self): + return CNF(set(self.clauses)) + + def add_clauses(self, clauses): + self.clauses |= clauses + + @classmethod + def from_prop(cls, prop): + res = cls() + res.add(prop) + return res + + def __iand__(self, other): + self.add_clauses(other.clauses) + return self + + def all_predicates(self): + predicates = set() + for c in self.clauses: + predicates |= {arg.lit for arg in c} + return predicates + + def _or(self, cnf): + clauses = set() + for a, b in product(self.clauses, cnf.clauses): + tmp = set(a) + tmp.update(b) + clauses.add(frozenset(tmp)) + return CNF(clauses) + + def _and(self, cnf): + clauses = self.clauses.union(cnf.clauses) + return CNF(clauses) + + def _not(self): + clss = list(self.clauses) + ll = {frozenset((~x,)) for x in clss[-1]} + ll = CNF(ll) + + for rest in clss[:-1]: + p = {frozenset((~x,)) for x in rest} + ll = ll._or(CNF(p)) + return ll + + def rcall(self, expr): + clause_list = [] + for clause in self.clauses: + lits = [arg.rcall(expr) for arg in clause] + clause_list.append(OR(*lits)) + expr = AND(*clause_list) + return distribute_AND_over_OR(expr) + + @classmethod + def all_or(cls, *cnfs): + b = cnfs[0].copy() + for rest in cnfs[1:]: + b = b._or(rest) + return b + + @classmethod + def all_and(cls, *cnfs): + b = cnfs[0].copy() + for rest in cnfs[1:]: + b = b._and(rest) + return b + + @classmethod + def to_CNF(cls, expr): + from sympy.assumptions.facts import get_composite_predicates + expr = to_NNF(expr, get_composite_predicates()) + expr = distribute_AND_over_OR(expr) + return expr + + @classmethod + def CNF_to_cnf(cls, cnf): + """ + Converts CNF object to SymPy's boolean expression + retaining the form of expression. + """ + def remove_literal(arg): + return Not(arg.lit) if arg.is_Not else arg.lit + + return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses)) + + +class EncodedCNF: + """ + Class for encoding the CNF expression. + """ + def __init__(self, data=None, encoding=None): + if not data and not encoding: + data = [] + encoding = {} + self.data = data + self.encoding = encoding + self._symbols = list(encoding.keys()) + + def from_cnf(self, cnf): + self._symbols = list(cnf.all_predicates()) + n = len(self._symbols) + self.encoding = dict(zip(self._symbols, range(1, n + 1))) + self.data = [self.encode(clause) for clause in cnf.clauses] + + @property + def symbols(self): + return self._symbols + + @property + def variables(self): + return range(1, len(self._symbols) + 1) + + def copy(self): + new_data = [set(clause) for clause in self.data] + return EncodedCNF(new_data, dict(self.encoding)) + + def add_prop(self, prop): + cnf = CNF.from_prop(prop) + self.add_from_cnf(cnf) + + def add_from_cnf(self, cnf): + clauses = [self.encode(clause) for clause in cnf.clauses] + self.data += clauses + + def encode_arg(self, arg): + literal = arg.lit + value = self.encoding.get(literal, None) + if value is None: + n = len(self._symbols) + self._symbols.append(literal) + value = self.encoding[literal] = n + 1 + if arg.is_Not: + return -value + else: + return value + + def encode(self, clause): + return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause} diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/facts.py b/vila/lib/python3.10/site-packages/sympy/assumptions/facts.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff268677cf74e252ac6c3bc3eecbea08b9414d0 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/facts.py @@ -0,0 +1,270 @@ +""" +Known facts in assumptions module. + +This module defines the facts between unary predicates in ``get_known_facts()``, +and supports functions to generate the contents in +``sympy.assumptions.ask_generated`` file. +""" + +from sympy.assumptions.ask import Q +from sympy.assumptions.assume import AppliedPredicate +from sympy.core.cache import cacheit +from sympy.core.symbol import Symbol +from sympy.logic.boolalg import (to_cnf, And, Not, Implies, Equivalent, + Exclusive,) +from sympy.logic.inference import satisfiable + + +@cacheit +def get_composite_predicates(): + # To reduce the complexity of sat solver, these predicates are + # transformed into the combination of primitive predicates. + return { + Q.real : Q.negative | Q.zero | Q.positive, + Q.integer : Q.even | Q.odd, + Q.nonpositive : Q.negative | Q.zero, + Q.nonzero : Q.negative | Q.positive, + Q.nonnegative : Q.zero | Q.positive, + Q.extended_real : Q.negative_infinite | Q.negative | Q.zero | Q.positive | Q.positive_infinite, + Q.extended_positive: Q.positive | Q.positive_infinite, + Q.extended_negative: Q.negative | Q.negative_infinite, + Q.extended_nonzero: Q.negative_infinite | Q.negative | Q.positive | Q.positive_infinite, + Q.extended_nonpositive: Q.negative_infinite | Q.negative | Q.zero, + Q.extended_nonnegative: Q.zero | Q.positive | Q.positive_infinite, + Q.complex : Q.algebraic | Q.transcendental + } + + +@cacheit +def get_known_facts(x=None): + """ + Facts between unary predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + get_number_facts(x), + get_matrix_facts(x) + ) + return fact + + +@cacheit +def get_number_facts(x = None): + """ + Facts between unary number predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + # primitive predicates for extended real exclude each other. + Exclusive(Q.negative_infinite(x), Q.negative(x), Q.zero(x), + Q.positive(x), Q.positive_infinite(x)), + + # build complex plane + Exclusive(Q.real(x), Q.imaginary(x)), + Implies(Q.real(x) | Q.imaginary(x), Q.complex(x)), + + # other subsets of complex + Exclusive(Q.transcendental(x), Q.algebraic(x)), + Equivalent(Q.real(x), Q.rational(x) | Q.irrational(x)), + Exclusive(Q.irrational(x), Q.rational(x)), + Implies(Q.rational(x), Q.algebraic(x)), + + # integers + Exclusive(Q.even(x), Q.odd(x)), + Implies(Q.integer(x), Q.rational(x)), + Implies(Q.zero(x), Q.even(x)), + Exclusive(Q.composite(x), Q.prime(x)), + Implies(Q.composite(x) | Q.prime(x), Q.integer(x) & Q.positive(x)), + Implies(Q.even(x) & Q.positive(x) & ~Q.prime(x), Q.composite(x)), + + # hermitian and antihermitian + Implies(Q.real(x), Q.hermitian(x)), + Implies(Q.imaginary(x), Q.antihermitian(x)), + Implies(Q.zero(x), Q.hermitian(x) | Q.antihermitian(x)), + + # define finity and infinity, and build extended real line + Exclusive(Q.infinite(x), Q.finite(x)), + Implies(Q.complex(x), Q.finite(x)), + Implies(Q.negative_infinite(x) | Q.positive_infinite(x), Q.infinite(x)), + + # commutativity + Implies(Q.finite(x) | Q.infinite(x), Q.commutative(x)), + ) + return fact + + +@cacheit +def get_matrix_facts(x = None): + """ + Facts between unary matrix predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + # matrices + Implies(Q.orthogonal(x), Q.positive_definite(x)), + Implies(Q.orthogonal(x), Q.unitary(x)), + Implies(Q.unitary(x) & Q.real_elements(x), Q.orthogonal(x)), + Implies(Q.unitary(x), Q.normal(x)), + Implies(Q.unitary(x), Q.invertible(x)), + Implies(Q.normal(x), Q.square(x)), + Implies(Q.diagonal(x), Q.normal(x)), + Implies(Q.positive_definite(x), Q.invertible(x)), + Implies(Q.diagonal(x), Q.upper_triangular(x)), + Implies(Q.diagonal(x), Q.lower_triangular(x)), + Implies(Q.lower_triangular(x), Q.triangular(x)), + Implies(Q.upper_triangular(x), Q.triangular(x)), + Implies(Q.triangular(x), Q.upper_triangular(x) | Q.lower_triangular(x)), + Implies(Q.upper_triangular(x) & Q.lower_triangular(x), Q.diagonal(x)), + Implies(Q.diagonal(x), Q.symmetric(x)), + Implies(Q.unit_triangular(x), Q.triangular(x)), + Implies(Q.invertible(x), Q.fullrank(x)), + Implies(Q.invertible(x), Q.square(x)), + Implies(Q.symmetric(x), Q.square(x)), + Implies(Q.fullrank(x) & Q.square(x), Q.invertible(x)), + Equivalent(Q.invertible(x), ~Q.singular(x)), + Implies(Q.integer_elements(x), Q.real_elements(x)), + Implies(Q.real_elements(x), Q.complex_elements(x)), + ) + return fact + + + +def generate_known_facts_dict(keys, fact): + """ + Computes and returns a dictionary which contains the relations between + unary predicates. + + Each key is a predicate, and item is two groups of predicates. + First group contains the predicates which are implied by the key, and + second group contains the predicates which are rejected by the key. + + All predicates in *keys* and *fact* must be unary and have same placeholder + symbol. + + Parameters + ========== + + keys : list of AppliedPredicate instances. + + fact : Fact between predicates in conjugated normal form. + + Examples + ======== + + >>> from sympy import Q, And, Implies + >>> from sympy.assumptions.facts import generate_known_facts_dict + >>> from sympy.abc import x + >>> keys = [Q.even(x), Q.odd(x), Q.zero(x)] + >>> fact = And(Implies(Q.even(x), ~Q.odd(x)), + ... Implies(Q.zero(x), Q.even(x))) + >>> generate_known_facts_dict(keys, fact) + {Q.even: ({Q.even}, {Q.odd}), + Q.odd: ({Q.odd}, {Q.even, Q.zero}), + Q.zero: ({Q.even, Q.zero}, {Q.odd})} + """ + fact_cnf = to_cnf(fact) + mapping = single_fact_lookup(keys, fact_cnf) + + ret = {} + for key, value in mapping.items(): + implied = set() + rejected = set() + for expr in value: + if isinstance(expr, AppliedPredicate): + implied.add(expr.function) + elif isinstance(expr, Not): + pred = expr.args[0] + rejected.add(pred.function) + ret[key.function] = (implied, rejected) + return ret + + +@cacheit +def get_known_facts_keys(): + """ + Return every unary predicates registered to ``Q``. + + This function is used to generate the keys for + ``generate_known_facts_dict``. + + """ + # exclude polyadic predicates + exclude = {Q.eq, Q.ne, Q.gt, Q.lt, Q.ge, Q.le} + + result = [] + for attr in Q.__class__.__dict__: + if attr.startswith('__'): + continue + pred = getattr(Q, attr) + if pred in exclude: + continue + result.append(pred) + return result + + +def single_fact_lookup(known_facts_keys, known_facts_cnf): + # Return the dictionary for quick lookup of single fact + mapping = {} + for key in known_facts_keys: + mapping[key] = {key} + for other_key in known_facts_keys: + if other_key != key: + if ask_full_inference(other_key, key, known_facts_cnf): + mapping[key].add(other_key) + if ask_full_inference(~other_key, key, known_facts_cnf): + mapping[key].add(~other_key) + return mapping + + +def ask_full_inference(proposition, assumptions, known_facts_cnf): + """ + Method for inferring properties about objects. + + """ + if not satisfiable(And(known_facts_cnf, assumptions, proposition)): + return False + if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))): + return True + return None diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__init__.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbe618eb8b43e252ac8fb0baf1eeee22bf347cc --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__init__.py @@ -0,0 +1,13 @@ +""" +Multipledispatch handlers for ``Predicate`` are implemented here. +Handlers in this module are not directly imported to other modules in +order to avoid circular import problem. +""" + +from .common import (AskHandler, CommonHandler, + test_closed_group) + +__all__ = [ + 'AskHandler', 'CommonHandler', + 'test_closed_group' +] diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e45669f41c26f60464bed0d1b61a652278fab01 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/__init__.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7475d3c7788a38eb386203d93313f39532a71f0 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/calculus.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83119d46a83c21a12b48f85ee67bcbaeb2f62eca Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/common.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/matrices.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0523c28c6f9938773d172084cdd0aeae28fa6fc Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/matrices.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56f3d92938e6b92893e95067ac6f53964a69afd4 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/ntheory.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60310623e105372d350c4750ba23b6767b89f62c Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/order.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f951dbc95f1793041c16653a1d397b70919d284 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/__pycache__/sets.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..263bed6da00cc57e198032d06f835ead374573d2 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py @@ -0,0 +1,258 @@ +""" +This module contains query handlers responsible for calculus queries: +infinitesimal, finite, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Mul, Pow, Symbol +from sympy.core.numbers import (NegativeInfinity, GoldenRatio, + Infinity, Exp1, ComplexInfinity, ImaginaryUnit, NaN, Number, Pi, E, + TribonacciConstant) +from sympy.functions import cos, exp, log, sign, sin +from sympy.logic.boolalg import conjuncts + +from ..predicates.calculus import (FinitePredicate, InfinitePredicate, + PositiveInfinitePredicate, NegativeInfinitePredicate) + + +# FinitePredicate + + +@FinitePredicate.register(Symbol) +def _(expr, assumptions): + """ + Handles Symbol. + """ + if expr.is_finite is not None: + return expr.is_finite + if Q.finite(expr) in conjuncts(assumptions): + return True + return None + +@FinitePredicate.register(Add) +def _(expr, assumptions): + """ + Return True if expr is bounded, False if not and None if unknown. + + Truth Table: + + +-------+-----+-----------+-----------+ + | | | | | + | | B | U | ? | + | | | | | + +-------+-----+---+---+---+---+---+---+ + | | | | | | | | | + | | |'+'|'-'|'x'|'+'|'-'|'x'| + | | | | | | | | | + +-------+-----+---+---+---+---+---+---+ + | | | | | + | B | B | U | ? | + | | | | | + +---+---+-----+---+---+---+---+---+---+ + | | | | | | | | | | + | |'+'| | U | ? | ? | U | ? | ? | + | | | | | | | | | | + | +---+-----+---+---+---+---+---+---+ + | | | | | | | | | | + | U |'-'| | ? | U | ? | ? | U | ? | + | | | | | | | | | | + | +---+-----+---+---+---+---+---+---+ + | | | | | | + | |'x'| | ? | ? | + | | | | | | + +---+---+-----+---+---+---+---+---+---+ + | | | | | + | ? | | | ? | + | | | | | + +-------+-----+-----------+---+---+---+ + + * 'B' = Bounded + + * 'U' = Unbounded + + * '?' = unknown boundedness + + * '+' = positive sign + + * '-' = negative sign + + * 'x' = sign unknown + + * All Bounded -> True + + * 1 Unbounded and the rest Bounded -> False + + * >1 Unbounded, all with same known sign -> False + + * Any Unknown and unknown sign -> None + + * Else -> None + + When the signs are not the same you can have an undefined + result as in oo - oo, hence 'bounded' is also undefined. + """ + sign = -1 # sign of unknown or infinite + result = True + for arg in expr.args: + _bounded = ask(Q.finite(arg), assumptions) + if _bounded: + continue + s = ask(Q.extended_positive(arg), assumptions) + # if there has been more than one sign or if the sign of this arg + # is None and Bounded is None or there was already + # an unknown sign, return None + if sign != -1 and s != sign or \ + s is None and None in (_bounded, sign): + return None + else: + sign = s + # once False, do not change + if result is not False: + result = _bounded + return result + +@FinitePredicate.register(Mul) +def _(expr, assumptions): + """ + Return True if expr is bounded, False if not and None if unknown. + + Truth Table: + + +---+---+---+--------+ + | | | | | + | | B | U | ? | + | | | | | + +---+---+---+---+----+ + | | | | | | + | | | | s | /s | + | | | | | | + +---+---+---+---+----+ + | | | | | + | B | B | U | ? | + | | | | | + +---+---+---+---+----+ + | | | | | | + | U | | U | U | ? | + | | | | | | + +---+---+---+---+----+ + | | | | | + | ? | | | ? | + | | | | | + +---+---+---+---+----+ + + * B = Bounded + + * U = Unbounded + + * ? = unknown boundedness + + * s = signed (hence nonzero) + + * /s = not signed + """ + result = True + for arg in expr.args: + _bounded = ask(Q.finite(arg), assumptions) + if _bounded: + continue + elif _bounded is None: + if result is None: + return None + if ask(Q.extended_nonzero(arg), assumptions) is None: + return None + if result is not False: + result = None + else: + result = False + return result + +@FinitePredicate.register(Pow) +def _(expr, assumptions): + """ + * Unbounded ** NonZero -> Unbounded + + * Bounded ** Bounded -> Bounded + + * Abs()<=1 ** Positive -> Bounded + + * Abs()>=1 ** Negative -> Bounded + + * Otherwise unknown + """ + if expr.base == E: + return ask(Q.finite(expr.exp), assumptions) + + base_bounded = ask(Q.finite(expr.base), assumptions) + exp_bounded = ask(Q.finite(expr.exp), assumptions) + if base_bounded is None and exp_bounded is None: # Common Case + return None + if base_bounded is False and ask(Q.extended_nonzero(expr.exp), assumptions): + return False + if base_bounded and exp_bounded: + return True + if (abs(expr.base) <= 1) == True and ask(Q.extended_positive(expr.exp), assumptions): + return True + if (abs(expr.base) >= 1) == True and ask(Q.extended_negative(expr.exp), assumptions): + return True + if (abs(expr.base) >= 1) == True and exp_bounded is False: + return False + return None + +@FinitePredicate.register(exp) +def _(expr, assumptions): + return ask(Q.finite(expr.exp), assumptions) + +@FinitePredicate.register(log) +def _(expr, assumptions): + # After complex -> finite fact is registered to new assumption system, + # querying Q.infinite may be removed. + if ask(Q.infinite(expr.args[0]), assumptions): + return False + return ask(~Q.zero(expr.args[0]), assumptions) + +@FinitePredicate.register_many(cos, sin, Number, Pi, Exp1, GoldenRatio, + TribonacciConstant, ImaginaryUnit, sign) +def _(expr, assumptions): + return True + +@FinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity) +def _(expr, assumptions): + return False + +@FinitePredicate.register(NaN) +def _(expr, assumptions): + return None + + +# InfinitePredicate + + +@InfinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity) +def _(expr, assumptions): + return True + + +# PositiveInfinitePredicate + + +@PositiveInfinitePredicate.register(Infinity) +def _(expr, assumptions): + return True + + +@PositiveInfinitePredicate.register_many(NegativeInfinity, ComplexInfinity) +def _(expr, assumptions): + return False + + +# NegativeInfinitePredicate + + +@NegativeInfinitePredicate.register(NegativeInfinity) +def _(expr, assumptions): + return True + + +@NegativeInfinitePredicate.register_many(Infinity, ComplexInfinity) +def _(expr, assumptions): + return False diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b89ffe8402e789e6d1e2b42d955bf1096c615237 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py @@ -0,0 +1,156 @@ +""" +This module defines base class for handlers and some core handlers: +``Q.commutative`` and ``Q.is_true``. +""" + +from sympy.assumptions import Q, ask, AppliedPredicate +from sympy.core import Basic, Symbol +from sympy.core.logic import _fuzzy_group +from sympy.core.numbers import NaN, Number +from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts, + Equivalent, Implies, Not, Or) +from sympy.utilities.exceptions import sympy_deprecation_warning + +from ..predicates.common import CommutativePredicate, IsTruePredicate + + +class AskHandler: + """Base class that all Ask Handlers must inherit.""" + def __new__(cls, *args, **kwargs): + sympy_deprecation_warning( + """ + The AskHandler system is deprecated. The AskHandler class should + be replaced with the multipledispatch handler of Predicate + """, + deprecated_since_version="1.8", + active_deprecations_target='deprecated-askhandler', + ) + return super().__new__(cls, *args, **kwargs) + + +class CommonHandler(AskHandler): + # Deprecated + """Defines some useful methods common to most Handlers. """ + + @staticmethod + def AlwaysTrue(expr, assumptions): + return True + + @staticmethod + def AlwaysFalse(expr, assumptions): + return False + + @staticmethod + def AlwaysNone(expr, assumptions): + return None + + NaN = AlwaysFalse + + +# CommutativePredicate + +@CommutativePredicate.register(Symbol) +def _(expr, assumptions): + """Objects are expected to be commutative unless otherwise stated""" + assumps = conjuncts(assumptions) + if expr.is_commutative is not None: + return expr.is_commutative and not ~Q.commutative(expr) in assumps + if Q.commutative(expr) in assumps: + return True + elif ~Q.commutative(expr) in assumps: + return False + return True + +@CommutativePredicate.register(Basic) +def _(expr, assumptions): + for arg in expr.args: + if not ask(Q.commutative(arg), assumptions): + return False + return True + +@CommutativePredicate.register(Number) +def _(expr, assumptions): + return True + +@CommutativePredicate.register(NaN) +def _(expr, assumptions): + return True + + +# IsTruePredicate + +@IsTruePredicate.register(bool) +def _(expr, assumptions): + return expr + +@IsTruePredicate.register(BooleanTrue) +def _(expr, assumptions): + return True + +@IsTruePredicate.register(BooleanFalse) +def _(expr, assumptions): + return False + +@IsTruePredicate.register(AppliedPredicate) +def _(expr, assumptions): + return ask(expr, assumptions) + +@IsTruePredicate.register(Not) +def _(expr, assumptions): + arg = expr.args[0] + if arg.is_Symbol: + # symbol used as abstract boolean object + return None + value = ask(arg, assumptions=assumptions) + if value in (True, False): + return not value + else: + return None + +@IsTruePredicate.register(Or) +def _(expr, assumptions): + result = False + for arg in expr.args: + p = ask(arg, assumptions=assumptions) + if p is True: + return True + if p is None: + result = None + return result + +@IsTruePredicate.register(And) +def _(expr, assumptions): + result = True + for arg in expr.args: + p = ask(arg, assumptions=assumptions) + if p is False: + return False + if p is None: + result = None + return result + +@IsTruePredicate.register(Implies) +def _(expr, assumptions): + p, q = expr.args + return ask(~p | q, assumptions=assumptions) + +@IsTruePredicate.register(Equivalent) +def _(expr, assumptions): + p, q = expr.args + pt = ask(p, assumptions=assumptions) + if pt is None: + return None + qt = ask(q, assumptions=assumptions) + if qt is None: + return None + return pt == qt + + +#### Helper methods +def test_closed_group(expr, assumptions, key): + """ + Test for membership in a group with respect + to the current operation. + """ + return _fuzzy_group( + (ask(key(a), assumptions) for a in expr.args), quick_exit=True) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..3b20385360136629ea037eb7238c45b70ba57fd2 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py @@ -0,0 +1,716 @@ +""" +This module contains query handlers responsible for Matrices queries: +Square, Symmetric, Invertible etc. +""" + +from sympy.logic.boolalg import conjuncts +from sympy.assumptions import Q, ask +from sympy.assumptions.handlers import test_closed_group +from sympy.matrices import MatrixBase +from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant, + DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul, + MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose, + ZeroMatrix) +from sympy.matrices.expressions.blockmatrix import reblock_2x2 +from sympy.matrices.expressions.factorizations import Factorization +from sympy.matrices.expressions.fourier import DFT +from sympy.core.logic import fuzzy_and +from sympy.utilities.iterables import sift +from sympy.core import Basic + +from ..predicates.matrices import (SquarePredicate, SymmetricPredicate, + InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate, + FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate, + LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate, + RealElementsPredicate, ComplexElementsPredicate) + + +def _Factorization(predicate, expr, assumptions): + if predicate in expr.predicates: + return True + + +# SquarePredicate + +@SquarePredicate.register(MatrixExpr) +def _(expr, assumptions): + return expr.shape[0] == expr.shape[1] + + +# SymmetricPredicate + +@SymmetricPredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args): + return True + # TODO: implement sathandlers system for the matrices. + # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). + if ask(Q.diagonal(expr), assumptions): + return True + if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T: + if len(mmul.args) == 2: + return True + return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions) + +@SymmetricPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.symmetric(base), assumptions) + return None + +@SymmetricPredicate.register(MatAdd) +def _(expr, assumptions): + return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args) + +@SymmetricPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if not expr.is_square: + return False + # TODO: implement sathandlers system for the matrices. + # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). + if ask(Q.diagonal(expr), assumptions): + return True + if Q.symmetric(expr) in conjuncts(assumptions): + return True + +@SymmetricPredicate.register_many(OneMatrix, ZeroMatrix) +def _(expr, assumptions): + return ask(Q.square(expr), assumptions) + +@SymmetricPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.symmetric(expr.arg), assumptions) + +@SymmetricPredicate.register(MatrixSlice) +def _(expr, assumptions): + # TODO: implement sathandlers system for the matrices. + # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). + if ask(Q.diagonal(expr), assumptions): + return True + if not expr.on_diag: + return None + else: + return ask(Q.symmetric(expr.parent), assumptions) + +@SymmetricPredicate.register(Identity) +def _(expr, assumptions): + return True + + +# InvertiblePredicate + +@InvertiblePredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args): + return True + if any(ask(Q.invertible(arg), assumptions) is False + for arg in mmul.args): + return False + +@InvertiblePredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + if exp.is_negative == False: + return ask(Q.invertible(base), assumptions) + return None + +@InvertiblePredicate.register(MatAdd) +def _(expr, assumptions): + return None + +@InvertiblePredicate.register(MatrixSymbol) +def _(expr, assumptions): + if not expr.is_square: + return False + if Q.invertible(expr) in conjuncts(assumptions): + return True + +@InvertiblePredicate.register_many(Identity, Inverse) +def _(expr, assumptions): + return True + +@InvertiblePredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@InvertiblePredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@InvertiblePredicate.register(Transpose) +def _(expr, assumptions): + return ask(Q.invertible(expr.arg), assumptions) + +@InvertiblePredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.invertible(expr.parent), assumptions) + +@InvertiblePredicate.register(MatrixBase) +def _(expr, assumptions): + if not expr.is_square: + return False + return expr.rank() == expr.rows + +@InvertiblePredicate.register(MatrixExpr) +def _(expr, assumptions): + if not expr.is_square: + return False + return None + +@InvertiblePredicate.register(BlockMatrix) +def _(expr, assumptions): + if not expr.is_square: + return False + if expr.blockshape == (1, 1): + return ask(Q.invertible(expr.blocks[0, 0]), assumptions) + expr = reblock_2x2(expr) + if expr.blockshape == (2, 2): + [[A, B], [C, D]] = expr.blocks.tolist() + if ask(Q.invertible(A), assumptions) == True: + invertible = ask(Q.invertible(D - C * A.I * B), assumptions) + if invertible is not None: + return invertible + if ask(Q.invertible(B), assumptions) == True: + invertible = ask(Q.invertible(C - D * B.I * A), assumptions) + if invertible is not None: + return invertible + if ask(Q.invertible(C), assumptions) == True: + invertible = ask(Q.invertible(B - A * C.I * D), assumptions) + if invertible is not None: + return invertible + if ask(Q.invertible(D), assumptions) == True: + invertible = ask(Q.invertible(A - B * D.I * C), assumptions) + if invertible is not None: + return invertible + return None + +@InvertiblePredicate.register(BlockDiagMatrix) +def _(expr, assumptions): + if expr.rowblocksizes != expr.colblocksizes: + return None + return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag]) + + +# OrthogonalPredicate + +@OrthogonalPredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and + factor == 1): + return True + if any(ask(Q.invertible(arg), assumptions) is False + for arg in mmul.args): + return False + +@OrthogonalPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if int_exp: + return ask(Q.orthogonal(base), assumptions) + return None + +@OrthogonalPredicate.register(MatAdd) +def _(expr, assumptions): + if (len(expr.args) == 1 and + ask(Q.orthogonal(expr.args[0]), assumptions)): + return True + +@OrthogonalPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if (not expr.is_square or + ask(Q.invertible(expr), assumptions) is False): + return False + if Q.orthogonal(expr) in conjuncts(assumptions): + return True + +@OrthogonalPredicate.register(Identity) +def _(expr, assumptions): + return True + +@OrthogonalPredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@OrthogonalPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.orthogonal(expr.arg), assumptions) + +@OrthogonalPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.orthogonal(expr.parent), assumptions) + +@OrthogonalPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.orthogonal, expr, assumptions) + + +# UnitaryPredicate + +@UnitaryPredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and + abs(factor) == 1): + return True + if any(ask(Q.invertible(arg), assumptions) is False + for arg in mmul.args): + return False + +@UnitaryPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if int_exp: + return ask(Q.unitary(base), assumptions) + return None + +@UnitaryPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if (not expr.is_square or + ask(Q.invertible(expr), assumptions) is False): + return False + if Q.unitary(expr) in conjuncts(assumptions): + return True + +@UnitaryPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.unitary(expr.arg), assumptions) + +@UnitaryPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.unitary(expr.parent), assumptions) + +@UnitaryPredicate.register_many(DFT, Identity) +def _(expr, assumptions): + return True + +@UnitaryPredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@UnitaryPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.unitary, expr, assumptions) + + +# FullRankPredicate + +@FullRankPredicate.register(MatMul) +def _(expr, assumptions): + if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args): + return True + +@FullRankPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if int_exp and ask(~Q.negative(exp), assumptions): + return ask(Q.fullrank(base), assumptions) + return None + +@FullRankPredicate.register(Identity) +def _(expr, assumptions): + return True + +@FullRankPredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@FullRankPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@FullRankPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.fullrank(expr.arg), assumptions) + +@FullRankPredicate.register(MatrixSlice) +def _(expr, assumptions): + if ask(Q.orthogonal(expr.parent), assumptions): + return True + + +# PositiveDefinitePredicate + +@PositiveDefinitePredicate.register(MatMul) +def _(expr, assumptions): + factor, mmul = expr.as_coeff_mmul() + if (all(ask(Q.positive_definite(arg), assumptions) + for arg in mmul.args) and factor > 0): + return True + if (len(mmul.args) >= 2 + and mmul.args[0] == mmul.args[-1].T + and ask(Q.fullrank(mmul.args[0]), assumptions)): + return ask(Q.positive_definite( + MatMul(*mmul.args[1:-1])), assumptions) + +@PositiveDefinitePredicate.register(MatPow) +def _(expr, assumptions): + # a power of a positive definite matrix is positive definite + if ask(Q.positive_definite(expr.args[0]), assumptions): + return True + +@PositiveDefinitePredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.positive_definite(arg), assumptions) + for arg in expr.args): + return True + +@PositiveDefinitePredicate.register(MatrixSymbol) +def _(expr, assumptions): + if not expr.is_square: + return False + if Q.positive_definite(expr) in conjuncts(assumptions): + return True + +@PositiveDefinitePredicate.register(Identity) +def _(expr, assumptions): + return True + +@PositiveDefinitePredicate.register(ZeroMatrix) +def _(expr, assumptions): + return False + +@PositiveDefinitePredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@PositiveDefinitePredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.positive_definite(expr.arg), assumptions) + +@PositiveDefinitePredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.positive_definite(expr.parent), assumptions) + + +# UpperTriangularPredicate + +@UpperTriangularPredicate.register(MatMul) +def _(expr, assumptions): + factor, matrices = expr.as_coeff_matrices() + if all(ask(Q.upper_triangular(m), assumptions) for m in matrices): + return True + +@UpperTriangularPredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args): + return True + +@UpperTriangularPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.upper_triangular(base), assumptions) + return None + +@UpperTriangularPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if Q.upper_triangular(expr) in conjuncts(assumptions): + return True + +@UpperTriangularPredicate.register_many(Identity, ZeroMatrix) +def _(expr, assumptions): + return True + +@UpperTriangularPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@UpperTriangularPredicate.register(Transpose) +def _(expr, assumptions): + return ask(Q.lower_triangular(expr.arg), assumptions) + +@UpperTriangularPredicate.register(Inverse) +def _(expr, assumptions): + return ask(Q.upper_triangular(expr.arg), assumptions) + +@UpperTriangularPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.upper_triangular(expr.parent), assumptions) + +@UpperTriangularPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.upper_triangular, expr, assumptions) + +# LowerTriangularPredicate + +@LowerTriangularPredicate.register(MatMul) +def _(expr, assumptions): + factor, matrices = expr.as_coeff_matrices() + if all(ask(Q.lower_triangular(m), assumptions) for m in matrices): + return True + +@LowerTriangularPredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args): + return True + +@LowerTriangularPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.lower_triangular(base), assumptions) + return None + +@LowerTriangularPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if Q.lower_triangular(expr) in conjuncts(assumptions): + return True + +@LowerTriangularPredicate.register_many(Identity, ZeroMatrix) +def _(expr, assumptions): + return True + +@LowerTriangularPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@LowerTriangularPredicate.register(Transpose) +def _(expr, assumptions): + return ask(Q.upper_triangular(expr.arg), assumptions) + +@LowerTriangularPredicate.register(Inverse) +def _(expr, assumptions): + return ask(Q.lower_triangular(expr.arg), assumptions) + +@LowerTriangularPredicate.register(MatrixSlice) +def _(expr, assumptions): + if not expr.on_diag: + return None + else: + return ask(Q.lower_triangular(expr.parent), assumptions) + +@LowerTriangularPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.lower_triangular, expr, assumptions) + + +# DiagonalPredicate + +def _is_empty_or_1x1(expr): + return expr.shape in ((0, 0), (1, 1)) + +@DiagonalPredicate.register(MatMul) +def _(expr, assumptions): + if _is_empty_or_1x1(expr): + return True + factor, matrices = expr.as_coeff_matrices() + if all(ask(Q.diagonal(m), assumptions) for m in matrices): + return True + +@DiagonalPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.diagonal(base), assumptions) + return None + +@DiagonalPredicate.register(MatAdd) +def _(expr, assumptions): + if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args): + return True + +@DiagonalPredicate.register(MatrixSymbol) +def _(expr, assumptions): + if _is_empty_or_1x1(expr): + return True + if Q.diagonal(expr) in conjuncts(assumptions): + return True + +@DiagonalPredicate.register(OneMatrix) +def _(expr, assumptions): + return expr.shape[0] == 1 and expr.shape[1] == 1 + +@DiagonalPredicate.register_many(Inverse, Transpose) +def _(expr, assumptions): + return ask(Q.diagonal(expr.arg), assumptions) + +@DiagonalPredicate.register(MatrixSlice) +def _(expr, assumptions): + if _is_empty_or_1x1(expr): + return True + if not expr.on_diag: + return None + else: + return ask(Q.diagonal(expr.parent), assumptions) + +@DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix) +def _(expr, assumptions): + return True + +@DiagonalPredicate.register(Factorization) +def _(expr, assumptions): + return _Factorization(Q.diagonal, expr, assumptions) + + +# IntegerElementsPredicate + +def BM_elements(predicate, expr, assumptions): + """ Block Matrix elements. """ + return all(ask(predicate(b), assumptions) for b in expr.blocks) + +def MS_elements(predicate, expr, assumptions): + """ Matrix Slice elements. """ + return ask(predicate(expr.parent), assumptions) + +def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions): + d = sift(expr.args, lambda x: isinstance(x, MatrixExpr)) + factors, matrices = d[False], d[True] + return fuzzy_and([ + test_closed_group(Basic(*factors), assumptions, scalar_predicate), + test_closed_group(Basic(*matrices), assumptions, matrix_predicate)]) + + +@IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd, + Trace, Transpose) +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.integer_elements) + +@IntegerElementsPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + if exp.is_negative == False: + return ask(Q.integer_elements(base), assumptions) + return None + +@IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix) +def _(expr, assumptions): + return True + +@IntegerElementsPredicate.register(MatMul) +def _(expr, assumptions): + return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions) + +@IntegerElementsPredicate.register(MatrixSlice) +def _(expr, assumptions): + return MS_elements(Q.integer_elements, expr, assumptions) + +@IntegerElementsPredicate.register(BlockMatrix) +def _(expr, assumptions): + return BM_elements(Q.integer_elements, expr, assumptions) + + +# RealElementsPredicate + +@RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, + MatAdd, Trace, Transpose) +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.real_elements) + +@RealElementsPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.real_elements(base), assumptions) + return None + +@RealElementsPredicate.register(MatMul) +def _(expr, assumptions): + return MatMul_elements(Q.real_elements, Q.real, expr, assumptions) + +@RealElementsPredicate.register(MatrixSlice) +def _(expr, assumptions): + return MS_elements(Q.real_elements, expr, assumptions) + +@RealElementsPredicate.register(BlockMatrix) +def _(expr, assumptions): + return BM_elements(Q.real_elements, expr, assumptions) + + +# ComplexElementsPredicate + +@ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, + Inverse, MatAdd, Trace, Transpose) +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.complex_elements) + +@ComplexElementsPredicate.register(MatPow) +def _(expr, assumptions): + # only for integer powers + base, exp = expr.args + int_exp = ask(Q.integer(exp), assumptions) + if not int_exp: + return None + non_negative = ask(~Q.negative(exp), assumptions) + if (non_negative or non_negative == False + and ask(Q.invertible(base), assumptions)): + return ask(Q.complex_elements(base), assumptions) + return None + +@ComplexElementsPredicate.register(MatMul) +def _(expr, assumptions): + return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions) + +@ComplexElementsPredicate.register(MatrixSlice) +def _(expr, assumptions): + return MS_elements(Q.complex_elements, expr, assumptions) + +@ComplexElementsPredicate.register(BlockMatrix) +def _(expr, assumptions): + return BM_elements(Q.complex_elements, expr, assumptions) + +@ComplexElementsPredicate.register(DFT) +def _(expr, assumptions): + return True diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb91f726e2ee5c10d915725f60f5093934d4e7b --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py @@ -0,0 +1,269 @@ +""" +Handlers for keys related to number theory: prime, even, odd, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S +from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN, + NegativeInfinity, NumberSymbol, Rational, int_valued) +from sympy.functions import Abs, im, re +from sympy.ntheory import isprime + +from sympy.multipledispatch import MDNotImplementedError + +from ..predicates.ntheory import (PrimePredicate, CompositePredicate, + EvenPredicate, OddPredicate) + + +# PrimePredicate + +def _PrimePredicate_number(expr, assumptions): + # helper method + exact = not expr.atoms(Float) + try: + i = int(expr.round()) + if (expr - i).equals(0) is False: + raise TypeError + except TypeError: + return False + if exact: + return isprime(i) + # when not exact, we won't give a True or False + # since the number represents an approximate value + +@PrimePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_prime + if ret is None: + raise MDNotImplementedError + return ret + +@PrimePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _PrimePredicate_number(expr, assumptions) + +@PrimePredicate.register(Mul) +def _(expr, assumptions): + if expr.is_number: + return _PrimePredicate_number(expr, assumptions) + for arg in expr.args: + if not ask(Q.integer(arg), assumptions): + return None + for arg in expr.args: + if arg.is_number and arg.is_composite: + return False + +@PrimePredicate.register(Pow) +def _(expr, assumptions): + """ + Integer**Integer -> !Prime + """ + if expr.is_number: + return _PrimePredicate_number(expr, assumptions) + if ask(Q.integer(expr.exp), assumptions) and \ + ask(Q.integer(expr.base), assumptions): + return False + +@PrimePredicate.register(Integer) +def _(expr, assumptions): + return isprime(expr) + +@PrimePredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit) +def _(expr, assumptions): + return False + +@PrimePredicate.register(Float) +def _(expr, assumptions): + return _PrimePredicate_number(expr, assumptions) + +@PrimePredicate.register(NumberSymbol) +def _(expr, assumptions): + return _PrimePredicate_number(expr, assumptions) + +@PrimePredicate.register(NaN) +def _(expr, assumptions): + return None + + +# CompositePredicate + +@CompositePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_composite + if ret is None: + raise MDNotImplementedError + return ret + +@CompositePredicate.register(Basic) +def _(expr, assumptions): + _positive = ask(Q.positive(expr), assumptions) + if _positive: + _integer = ask(Q.integer(expr), assumptions) + if _integer: + _prime = ask(Q.prime(expr), assumptions) + if _prime is None: + return + # Positive integer which is not prime is not + # necessarily composite + if expr.equals(1): + return False + return not _prime + else: + return _integer + else: + return _positive + + +# EvenPredicate + +def _EvenPredicate_number(expr, assumptions): + # helper method + if isinstance(expr, (float, Float)): + if int_valued(expr): + return None + return False + try: + i = int(expr.round()) + except TypeError: + return False + if not (expr - i).equals(0): + return False + return i % 2 == 0 + +@EvenPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_even + if ret is None: + raise MDNotImplementedError + return ret + +@EvenPredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + +@EvenPredicate.register(Mul) +def _(expr, assumptions): + """ + Even * Integer -> Even + Even * Odd -> Even + Integer * Odd -> ? + Odd * Odd -> Odd + Even * Even -> Even + Integer * Integer -> Even if Integer + Integer = Odd + otherwise -> ? + """ + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + even, odd, irrational, acc = False, 0, False, 1 + for arg in expr.args: + # check for all integers and at least one even + if ask(Q.integer(arg), assumptions): + if ask(Q.even(arg), assumptions): + even = True + elif ask(Q.odd(arg), assumptions): + odd += 1 + elif not even and acc != 1: + if ask(Q.odd(acc + arg), assumptions): + even = True + elif ask(Q.irrational(arg), assumptions): + # one irrational makes the result False + # two makes it undefined + if irrational: + break + irrational = True + else: + break + acc = arg + else: + if irrational: + return False + if even: + return True + if odd == len(expr.args): + return False + +@EvenPredicate.register(Add) +def _(expr, assumptions): + """ + Even + Odd -> Odd + Even + Even -> Even + Odd + Odd -> Even + + """ + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + _result = True + for arg in expr.args: + if ask(Q.even(arg), assumptions): + pass + elif ask(Q.odd(arg), assumptions): + _result = not _result + else: + break + else: + return _result + +@EvenPredicate.register(Pow) +def _(expr, assumptions): + if expr.is_number: + return _EvenPredicate_number(expr, assumptions) + if ask(Q.integer(expr.exp), assumptions): + if ask(Q.positive(expr.exp), assumptions): + return ask(Q.even(expr.base), assumptions) + elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions): + return False + elif expr.base is S.NegativeOne: + return False + +@EvenPredicate.register(Integer) +def _(expr, assumptions): + return not bool(expr.p & 1) + +@EvenPredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit) +def _(expr, assumptions): + return False + +@EvenPredicate.register(NumberSymbol) +def _(expr, assumptions): + return _EvenPredicate_number(expr, assumptions) + +@EvenPredicate.register(Abs) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return ask(Q.even(expr.args[0]), assumptions) + +@EvenPredicate.register(re) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return ask(Q.even(expr.args[0]), assumptions) + +@EvenPredicate.register(im) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return True + +@EvenPredicate.register(NaN) +def _(expr, assumptions): + return None + + +# OddPredicate + +@OddPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_odd + if ret is None: + raise MDNotImplementedError + return ret + +@OddPredicate.register(Basic) +def _(expr, assumptions): + _integer = ask(Q.integer(expr), assumptions) + if _integer: + _even = ask(Q.even(expr), assumptions) + if _even is None: + return None + return not _even + return _integer diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/order.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/order.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a5378c20a9fcf152914fc5cc9488583f2e39a3 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/order.py @@ -0,0 +1,436 @@ +""" +Handlers related to order relations: positive, negative, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Basic, Expr, Mul, Pow +from sympy.core.logic import fuzzy_not, fuzzy_and, fuzzy_or +from sympy.core.numbers import E, ImaginaryUnit, NaN, I, pi +from sympy.functions import Abs, acos, acot, asin, atan, exp, factorial, log +from sympy.matrices import Determinant, Trace +from sympy.matrices.expressions.matexpr import MatrixElement + +from sympy.multipledispatch import MDNotImplementedError + +from ..predicates.order import (NegativePredicate, NonNegativePredicate, + NonZeroPredicate, ZeroPredicate, NonPositivePredicate, PositivePredicate, + ExtendedNegativePredicate, ExtendedNonNegativePredicate, + ExtendedNonPositivePredicate, ExtendedNonZeroPredicate, + ExtendedPositivePredicate,) + + +# NegativePredicate + +def _NegativePredicate_number(expr, assumptions): + r, i = expr.as_real_imag() + # If the imaginary part can symbolically be shown to be zero then + # we just evaluate the real part; otherwise we evaluate the imaginary + # part to see if it actually evaluates to zero and if it does then + # we make the comparison between the real part and zero. + if not i: + r = r.evalf(2) + if r._prec != 1: + return r < 0 + else: + i = i.evalf(2) + if i._prec != 1: + if i != 0: + return False + r = r.evalf(2) + if r._prec != 1: + return r < 0 + +@NegativePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + +@NegativePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_negative + if ret is None: + raise MDNotImplementedError + return ret + +@NegativePredicate.register(Add) +def _(expr, assumptions): + """ + Positive + Positive -> Positive, + Negative + Negative -> Negative + """ + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + + r = ask(Q.real(expr), assumptions) + if r is not True: + return r + + nonpos = 0 + for arg in expr.args: + if ask(Q.negative(arg), assumptions) is not True: + if ask(Q.positive(arg), assumptions) is False: + nonpos += 1 + else: + break + else: + if nonpos < len(expr.args): + return True + +@NegativePredicate.register(Mul) +def _(expr, assumptions): + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + result = None + for arg in expr.args: + if result is None: + result = False + if ask(Q.negative(arg), assumptions): + result = not result + elif ask(Q.positive(arg), assumptions): + pass + else: + return + return result + +@NegativePredicate.register(Pow) +def _(expr, assumptions): + """ + Real ** Even -> NonNegative + Real ** Odd -> same_as_base + NonNegative ** Positive -> NonNegative + """ + if expr.base == E: + # Exponential is always positive: + if ask(Q.real(expr.exp), assumptions): + return False + return + + if expr.is_number: + return _NegativePredicate_number(expr, assumptions) + if ask(Q.real(expr.base), assumptions): + if ask(Q.positive(expr.base), assumptions): + if ask(Q.real(expr.exp), assumptions): + return False + if ask(Q.even(expr.exp), assumptions): + return False + if ask(Q.odd(expr.exp), assumptions): + return ask(Q.negative(expr.base), assumptions) + +@NegativePredicate.register_many(Abs, ImaginaryUnit) +def _(expr, assumptions): + return False + +@NegativePredicate.register(exp) +def _(expr, assumptions): + if ask(Q.real(expr.exp), assumptions): + return False + raise MDNotImplementedError + + +# NonNegativePredicate + +@NonNegativePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + notnegative = fuzzy_not(_NegativePredicate_number(expr, assumptions)) + if notnegative: + return ask(Q.real(expr), assumptions) + else: + return notnegative + +@NonNegativePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_nonnegative + if ret is None: + raise MDNotImplementedError + return ret + + +# NonZeroPredicate + +@NonZeroPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_nonzero + if ret is None: + raise MDNotImplementedError + return ret + +@NonZeroPredicate.register(Basic) +def _(expr, assumptions): + if ask(Q.real(expr)) is False: + return False + if expr.is_number: + # if there are no symbols just evalf + i = expr.evalf(2) + def nonz(i): + if i._prec != 1: + return i != 0 + return fuzzy_or(nonz(i) for i in i.as_real_imag()) + +@NonZeroPredicate.register(Add) +def _(expr, assumptions): + if all(ask(Q.positive(x), assumptions) for x in expr.args) \ + or all(ask(Q.negative(x), assumptions) for x in expr.args): + return True + +@NonZeroPredicate.register(Mul) +def _(expr, assumptions): + for arg in expr.args: + result = ask(Q.nonzero(arg), assumptions) + if result: + continue + return result + return True + +@NonZeroPredicate.register(Pow) +def _(expr, assumptions): + return ask(Q.nonzero(expr.base), assumptions) + +@NonZeroPredicate.register(Abs) +def _(expr, assumptions): + return ask(Q.nonzero(expr.args[0]), assumptions) + +@NonZeroPredicate.register(NaN) +def _(expr, assumptions): + return None + + +# ZeroPredicate + +@ZeroPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_zero + if ret is None: + raise MDNotImplementedError + return ret + +@ZeroPredicate.register(Basic) +def _(expr, assumptions): + return fuzzy_and([fuzzy_not(ask(Q.nonzero(expr), assumptions)), + ask(Q.real(expr), assumptions)]) + +@ZeroPredicate.register(Mul) +def _(expr, assumptions): + # TODO: This should be deducible from the nonzero handler + return fuzzy_or(ask(Q.zero(arg), assumptions) for arg in expr.args) + + +# NonPositivePredicate + +@NonPositivePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_nonpositive + if ret is None: + raise MDNotImplementedError + return ret + +@NonPositivePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + notpositive = fuzzy_not(_PositivePredicate_number(expr, assumptions)) + if notpositive: + return ask(Q.real(expr), assumptions) + else: + return notpositive + + +# PositivePredicate + +def _PositivePredicate_number(expr, assumptions): + r, i = expr.as_real_imag() + # If the imaginary part can symbolically be shown to be zero then + # we just evaluate the real part; otherwise we evaluate the imaginary + # part to see if it actually evaluates to zero and if it does then + # we make the comparison between the real part and zero. + if not i: + r = r.evalf(2) + if r._prec != 1: + return r > 0 + else: + i = i.evalf(2) + if i._prec != 1: + if i != 0: + return False + r = r.evalf(2) + if r._prec != 1: + return r > 0 + +@PositivePredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_positive + if ret is None: + raise MDNotImplementedError + return ret + +@PositivePredicate.register(Basic) +def _(expr, assumptions): + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + +@PositivePredicate.register(Mul) +def _(expr, assumptions): + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + result = True + for arg in expr.args: + if ask(Q.positive(arg), assumptions): + continue + elif ask(Q.negative(arg), assumptions): + result = result ^ True + else: + return + return result + +@PositivePredicate.register(Add) +def _(expr, assumptions): + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + + r = ask(Q.real(expr), assumptions) + if r is not True: + return r + + nonneg = 0 + for arg in expr.args: + if ask(Q.positive(arg), assumptions) is not True: + if ask(Q.negative(arg), assumptions) is False: + nonneg += 1 + else: + break + else: + if nonneg < len(expr.args): + return True + +@PositivePredicate.register(Pow) +def _(expr, assumptions): + if expr.base == E: + if ask(Q.real(expr.exp), assumptions): + return True + if ask(Q.imaginary(expr.exp), assumptions): + return ask(Q.even(expr.exp/(I*pi)), assumptions) + return + + if expr.is_number: + return _PositivePredicate_number(expr, assumptions) + if ask(Q.positive(expr.base), assumptions): + if ask(Q.real(expr.exp), assumptions): + return True + if ask(Q.negative(expr.base), assumptions): + if ask(Q.even(expr.exp), assumptions): + return True + if ask(Q.odd(expr.exp), assumptions): + return False + +@PositivePredicate.register(exp) +def _(expr, assumptions): + if ask(Q.real(expr.exp), assumptions): + return True + if ask(Q.imaginary(expr.exp), assumptions): + return ask(Q.even(expr.exp/(I*pi)), assumptions) + +@PositivePredicate.register(log) +def _(expr, assumptions): + r = ask(Q.real(expr.args[0]), assumptions) + if r is not True: + return r + if ask(Q.positive(expr.args[0] - 1), assumptions): + return True + if ask(Q.negative(expr.args[0] - 1), assumptions): + return False + +@PositivePredicate.register(factorial) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.integer(x) & Q.positive(x), assumptions): + return True + +@PositivePredicate.register(ImaginaryUnit) +def _(expr, assumptions): + return False + +@PositivePredicate.register(Abs) +def _(expr, assumptions): + return ask(Q.nonzero(expr), assumptions) + +@PositivePredicate.register(Trace) +def _(expr, assumptions): + if ask(Q.positive_definite(expr.arg), assumptions): + return True + +@PositivePredicate.register(Determinant) +def _(expr, assumptions): + if ask(Q.positive_definite(expr.arg), assumptions): + return True + +@PositivePredicate.register(MatrixElement) +def _(expr, assumptions): + if (expr.i == expr.j + and ask(Q.positive_definite(expr.parent), assumptions)): + return True + +@PositivePredicate.register(atan) +def _(expr, assumptions): + return ask(Q.positive(expr.args[0]), assumptions) + +@PositivePredicate.register(asin) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.positive(x) & Q.nonpositive(x - 1), assumptions): + return True + if ask(Q.negative(x) & Q.nonnegative(x + 1), assumptions): + return False + +@PositivePredicate.register(acos) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.nonpositive(x - 1) & Q.nonnegative(x + 1), assumptions): + return True + +@PositivePredicate.register(acot) +def _(expr, assumptions): + return ask(Q.real(expr.args[0]), assumptions) + +@PositivePredicate.register(NaN) +def _(expr, assumptions): + return None + + +# ExtendedNegativePredicate + +@ExtendedNegativePredicate.register(object) +def _(expr, assumptions): + return ask(Q.negative(expr) | Q.negative_infinite(expr), assumptions) + + +# ExtendedPositivePredicate + +@ExtendedPositivePredicate.register(object) +def _(expr, assumptions): + return ask(Q.positive(expr) | Q.positive_infinite(expr), assumptions) + + +# ExtendedNonZeroPredicate + +@ExtendedNonZeroPredicate.register(object) +def _(expr, assumptions): + return ask( + Q.negative_infinite(expr) | Q.negative(expr) | Q.positive(expr) | Q.positive_infinite(expr), + assumptions) + + +# ExtendedNonPositivePredicate + +@ExtendedNonPositivePredicate.register(object) +def _(expr, assumptions): + return ask( + Q.negative_infinite(expr) | Q.negative(expr) | Q.zero(expr), + assumptions) + + +# ExtendedNonNegativePredicate + +@ExtendedNonNegativePredicate.register(object) +def _(expr, assumptions): + return ask( + Q.zero(expr) | Q.positive(expr) | Q.positive_infinite(expr), + assumptions) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/sets.py b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..b53bcfedef30681ea4450c6dad9120bc2ea9016e --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/handlers/sets.py @@ -0,0 +1,772 @@ +""" +Handlers for predicates related to set membership: integer, rational, etc. +""" + +from sympy.assumptions import Q, ask +from sympy.core import Add, Basic, Expr, Mul, Pow, S +from sympy.core.numbers import (AlgebraicNumber, ComplexInfinity, Exp1, Float, + GoldenRatio, ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity, + Number, NumberSymbol, Pi, pi, Rational, TribonacciConstant, E) +from sympy.core.logic import fuzzy_bool +from sympy.functions import (Abs, acos, acot, asin, atan, cos, cot, exp, im, + log, re, sin, tan) +from sympy.core.numbers import I +from sympy.core.relational import Eq +from sympy.functions.elementary.complexes import conjugate +from sympy.matrices import Determinant, MatrixBase, Trace +from sympy.matrices.expressions.matexpr import MatrixElement + +from sympy.multipledispatch import MDNotImplementedError + +from .common import test_closed_group +from ..predicates.sets import (IntegerPredicate, RationalPredicate, + IrrationalPredicate, RealPredicate, ExtendedRealPredicate, + HermitianPredicate, ComplexPredicate, ImaginaryPredicate, + AntihermitianPredicate, AlgebraicPredicate) + + +# IntegerPredicate + +def _IntegerPredicate_number(expr, assumptions): + # helper function + try: + i = int(expr.round()) + if not (expr - i).equals(0): + raise TypeError + return True + except TypeError: + return False + +@IntegerPredicate.register_many(int, Integer) # type:ignore +def _(expr, assumptions): + return True + +@IntegerPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, + NegativeInfinity, Pi, Rational, TribonacciConstant) +def _(expr, assumptions): + return False + +@IntegerPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_integer + if ret is None: + raise MDNotImplementedError + return ret + +@IntegerPredicate.register_many(Add, Pow) +def _(expr, assumptions): + """ + * Integer + Integer -> Integer + * Integer + !Integer -> !Integer + * !Integer + !Integer -> ? + """ + if expr.is_number: + return _IntegerPredicate_number(expr, assumptions) + return test_closed_group(expr, assumptions, Q.integer) + +@IntegerPredicate.register(Mul) +def _(expr, assumptions): + """ + * Integer*Integer -> Integer + * Integer*Irrational -> !Integer + * Odd/Even -> !Integer + * Integer*Rational -> ? + """ + if expr.is_number: + return _IntegerPredicate_number(expr, assumptions) + _output = True + for arg in expr.args: + if not ask(Q.integer(arg), assumptions): + if arg.is_Rational: + if arg.q == 2: + return ask(Q.even(2*expr), assumptions) + if ~(arg.q & 1): + return None + elif ask(Q.irrational(arg), assumptions): + if _output: + _output = False + else: + return + else: + return + + return _output + +@IntegerPredicate.register(Abs) +def _(expr, assumptions): + return ask(Q.integer(expr.args[0]), assumptions) + +@IntegerPredicate.register_many(Determinant, MatrixElement, Trace) +def _(expr, assumptions): + return ask(Q.integer_elements(expr.args[0]), assumptions) + + +# RationalPredicate + +@RationalPredicate.register(Rational) +def _(expr, assumptions): + return True + +@RationalPredicate.register(Float) +def _(expr, assumptions): + return None + +@RationalPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, + NegativeInfinity, Pi, TribonacciConstant) +def _(expr, assumptions): + return False + +@RationalPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_rational + if ret is None: + raise MDNotImplementedError + return ret + +@RationalPredicate.register_many(Add, Mul) +def _(expr, assumptions): + """ + * Rational + Rational -> Rational + * Rational + !Rational -> !Rational + * !Rational + !Rational -> ? + """ + if expr.is_number: + if expr.as_real_imag()[1]: + return False + return test_closed_group(expr, assumptions, Q.rational) + +@RationalPredicate.register(Pow) +def _(expr, assumptions): + """ + * Rational ** Integer -> Rational + * Irrational ** Rational -> Irrational + * Rational ** Irrational -> ? + """ + if expr.base == E: + x = expr.exp + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + return + + if ask(Q.integer(expr.exp), assumptions): + return ask(Q.rational(expr.base), assumptions) + elif ask(Q.rational(expr.exp), assumptions): + if ask(Q.prime(expr.base), assumptions): + return False + +@RationalPredicate.register_many(asin, atan, cos, sin, tan) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@RationalPredicate.register(exp) +def _(expr, assumptions): + x = expr.exp + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@RationalPredicate.register_many(acot, cot) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.rational(x), assumptions): + return False + +@RationalPredicate.register_many(acos, log) +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.rational(x), assumptions): + return ask(~Q.nonzero(x - 1), assumptions) + + +# IrrationalPredicate + +@IrrationalPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_irrational + if ret is None: + raise MDNotImplementedError + return ret + +@IrrationalPredicate.register(Basic) +def _(expr, assumptions): + _real = ask(Q.real(expr), assumptions) + if _real: + _rational = ask(Q.rational(expr), assumptions) + if _rational is None: + return None + return not _rational + else: + return _real + + +# RealPredicate + +def _RealPredicate_number(expr, assumptions): + # let as_real_imag() work first since the expression may + # be simpler to evaluate + i = expr.as_real_imag()[1].evalf(2) + if i._prec != 1: + return not i + # allow None to be returned if we couldn't show for sure + # that i was 0 + +@RealPredicate.register_many(Abs, Exp1, Float, GoldenRatio, im, Pi, Rational, + re, TribonacciConstant) +def _(expr, assumptions): + return True + +@RealPredicate.register_many(ImaginaryUnit, Infinity, NegativeInfinity) +def _(expr, assumptions): + return False + +@RealPredicate.register(Expr) +def _(expr, assumptions): + ret = expr.is_real + if ret is None: + raise MDNotImplementedError + return ret + +@RealPredicate.register(Add) +def _(expr, assumptions): + """ + * Real + Real -> Real + * Real + (Complex & !Real) -> !Real + """ + if expr.is_number: + return _RealPredicate_number(expr, assumptions) + return test_closed_group(expr, assumptions, Q.real) + +@RealPredicate.register(Mul) +def _(expr, assumptions): + """ + * Real*Real -> Real + * Real*Imaginary -> !Real + * Imaginary*Imaginary -> Real + """ + if expr.is_number: + return _RealPredicate_number(expr, assumptions) + result = True + for arg in expr.args: + if ask(Q.real(arg), assumptions): + pass + elif ask(Q.imaginary(arg), assumptions): + result = result ^ True + else: + break + else: + return result + +@RealPredicate.register(Pow) +def _(expr, assumptions): + """ + * Real**Integer -> Real + * Positive**Real -> Real + * Real**(Integer/Even) -> Real if base is nonnegative + * Real**(Integer/Odd) -> Real + * Imaginary**(Integer/Even) -> Real + * Imaginary**(Integer/Odd) -> not Real + * Imaginary**Real -> ? since Real could be 0 (giving real) + or 1 (giving imaginary) + * b**Imaginary -> Real if log(b) is imaginary and b != 0 + and exponent != integer multiple of + I*pi/log(b) + * Real**Real -> ? e.g. sqrt(-1) is imaginary and + sqrt(2) is not + """ + if expr.is_number: + return _RealPredicate_number(expr, assumptions) + + if expr.base == E: + return ask( + Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions + ) + + if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E): + if ask(Q.imaginary(expr.base.exp), assumptions): + if ask(Q.imaginary(expr.exp), assumptions): + return True + # If the i = (exp's arg)/(I*pi) is an integer or half-integer + # multiple of I*pi then 2*i will be an integer. In addition, + # exp(i*I*pi) = (-1)**i so the overall realness of the expr + # can be determined by replacing exp(i*I*pi) with (-1)**i. + i = expr.base.exp/I/pi + if ask(Q.integer(2*i), assumptions): + return ask(Q.real((S.NegativeOne**i)**expr.exp), assumptions) + return + + if ask(Q.imaginary(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + odd = ask(Q.odd(expr.exp), assumptions) + if odd is not None: + return not odd + return + + if ask(Q.imaginary(expr.exp), assumptions): + imlog = ask(Q.imaginary(log(expr.base)), assumptions) + if imlog is not None: + # I**i -> real, log(I) is imag; + # (2*I)**i -> complex, log(2*I) is not imag + return imlog + + if ask(Q.real(expr.base), assumptions): + if ask(Q.real(expr.exp), assumptions): + if expr.exp.is_Rational and \ + ask(Q.even(expr.exp.q), assumptions): + return ask(Q.positive(expr.base), assumptions) + elif ask(Q.integer(expr.exp), assumptions): + return True + elif ask(Q.positive(expr.base), assumptions): + return True + elif ask(Q.negative(expr.base), assumptions): + return False + +@RealPredicate.register_many(cos, sin) +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + return True + +@RealPredicate.register(exp) +def _(expr, assumptions): + return ask( + Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions + ) + +@RealPredicate.register(log) +def _(expr, assumptions): + return ask(Q.positive(expr.args[0]), assumptions) + +@RealPredicate.register_many(Determinant, MatrixElement, Trace) +def _(expr, assumptions): + return ask(Q.real_elements(expr.args[0]), assumptions) + + +# ExtendedRealPredicate + +@ExtendedRealPredicate.register(object) +def _(expr, assumptions): + return ask(Q.negative_infinite(expr) + | Q.negative(expr) + | Q.zero(expr) + | Q.positive(expr) + | Q.positive_infinite(expr), + assumptions) + +@ExtendedRealPredicate.register_many(Infinity, NegativeInfinity) +def _(expr, assumptions): + return True + +@ExtendedRealPredicate.register_many(Add, Mul, Pow) # type:ignore +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.extended_real) + + +# HermitianPredicate + +@HermitianPredicate.register(object) # type:ignore +def _(expr, assumptions): + if isinstance(expr, MatrixBase): + return None + return ask(Q.real(expr), assumptions) + +@HermitianPredicate.register(Add) # type:ignore +def _(expr, assumptions): + """ + * Hermitian + Hermitian -> Hermitian + * Hermitian + !Hermitian -> !Hermitian + """ + if expr.is_number: + raise MDNotImplementedError + return test_closed_group(expr, assumptions, Q.hermitian) + +@HermitianPredicate.register(Mul) # type:ignore +def _(expr, assumptions): + """ + As long as there is at most only one noncommutative term: + + * Hermitian*Hermitian -> Hermitian + * Hermitian*Antihermitian -> !Hermitian + * Antihermitian*Antihermitian -> Hermitian + """ + if expr.is_number: + raise MDNotImplementedError + nccount = 0 + result = True + for arg in expr.args: + if ask(Q.antihermitian(arg), assumptions): + result = result ^ True + elif not ask(Q.hermitian(arg), assumptions): + break + if ask(~Q.commutative(arg), assumptions): + nccount += 1 + if nccount > 1: + break + else: + return result + +@HermitianPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + """ + * Hermitian**Integer -> Hermitian + """ + if expr.is_number: + raise MDNotImplementedError + if expr.base == E: + if ask(Q.hermitian(expr.exp), assumptions): + return True + raise MDNotImplementedError + if ask(Q.hermitian(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + return True + raise MDNotImplementedError + +@HermitianPredicate.register_many(cos, sin) # type:ignore +def _(expr, assumptions): + if ask(Q.hermitian(expr.args[0]), assumptions): + return True + raise MDNotImplementedError + +@HermitianPredicate.register(exp) # type:ignore +def _(expr, assumptions): + if ask(Q.hermitian(expr.exp), assumptions): + return True + raise MDNotImplementedError + +@HermitianPredicate.register(MatrixBase) # type:ignore +def _(mat, assumptions): + rows, cols = mat.shape + ret_val = True + for i in range(rows): + for j in range(i, cols): + cond = fuzzy_bool(Eq(mat[i, j], conjugate(mat[j, i]))) + if cond is None: + ret_val = None + if cond == False: + return False + if ret_val is None: + raise MDNotImplementedError + return ret_val + + +# ComplexPredicate + +@ComplexPredicate.register_many(Abs, cos, exp, im, ImaginaryUnit, log, Number, # type:ignore + NumberSymbol, re, sin) +def _(expr, assumptions): + return True + +@ComplexPredicate.register_many(Infinity, NegativeInfinity) # type:ignore +def _(expr, assumptions): + return False + +@ComplexPredicate.register(Expr) # type:ignore +def _(expr, assumptions): + ret = expr.is_complex + if ret is None: + raise MDNotImplementedError + return ret + +@ComplexPredicate.register_many(Add, Mul) # type:ignore +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.complex) + +@ComplexPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + if expr.base == E: + return True + return test_closed_group(expr, assumptions, Q.complex) + +@ComplexPredicate.register_many(Determinant, MatrixElement, Trace) # type:ignore +def _(expr, assumptions): + return ask(Q.complex_elements(expr.args[0]), assumptions) + +@ComplexPredicate.register(NaN) # type:ignore +def _(expr, assumptions): + return None + + +# ImaginaryPredicate + +def _Imaginary_number(expr, assumptions): + # let as_real_imag() work first since the expression may + # be simpler to evaluate + r = expr.as_real_imag()[0].evalf(2) + if r._prec != 1: + return not r + # allow None to be returned if we couldn't show for sure + # that r was 0 + +@ImaginaryPredicate.register(ImaginaryUnit) # type:ignore +def _(expr, assumptions): + return True + +@ImaginaryPredicate.register(Expr) # type:ignore +def _(expr, assumptions): + ret = expr.is_imaginary + if ret is None: + raise MDNotImplementedError + return ret + +@ImaginaryPredicate.register(Add) # type:ignore +def _(expr, assumptions): + """ + * Imaginary + Imaginary -> Imaginary + * Imaginary + Complex -> ? + * Imaginary + Real -> !Imaginary + """ + if expr.is_number: + return _Imaginary_number(expr, assumptions) + + reals = 0 + for arg in expr.args: + if ask(Q.imaginary(arg), assumptions): + pass + elif ask(Q.real(arg), assumptions): + reals += 1 + else: + break + else: + if reals == 0: + return True + if reals in (1, len(expr.args)): + # two reals could sum 0 thus giving an imaginary + return False + +@ImaginaryPredicate.register(Mul) # type:ignore +def _(expr, assumptions): + """ + * Real*Imaginary -> Imaginary + * Imaginary*Imaginary -> Real + """ + if expr.is_number: + return _Imaginary_number(expr, assumptions) + result = False + reals = 0 + for arg in expr.args: + if ask(Q.imaginary(arg), assumptions): + result = result ^ True + elif not ask(Q.real(arg), assumptions): + break + else: + if reals == len(expr.args): + return False + return result + +@ImaginaryPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + """ + * Imaginary**Odd -> Imaginary + * Imaginary**Even -> Real + * b**Imaginary -> !Imaginary if exponent is an integer + multiple of I*pi/log(b) + * Imaginary**Real -> ? + * Positive**Real -> Real + * Negative**Integer -> Real + * Negative**(Integer/2) -> Imaginary + * Negative**Real -> not Imaginary if exponent is not Rational + """ + if expr.is_number: + return _Imaginary_number(expr, assumptions) + + if expr.base == E: + a = expr.exp/I/pi + return ask(Q.integer(2*a) & ~Q.integer(a), assumptions) + + if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E): + if ask(Q.imaginary(expr.base.exp), assumptions): + if ask(Q.imaginary(expr.exp), assumptions): + return False + i = expr.base.exp/I/pi + if ask(Q.integer(2*i), assumptions): + return ask(Q.imaginary((S.NegativeOne**i)**expr.exp), assumptions) + + if ask(Q.imaginary(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + odd = ask(Q.odd(expr.exp), assumptions) + if odd is not None: + return odd + return + + if ask(Q.imaginary(expr.exp), assumptions): + imlog = ask(Q.imaginary(log(expr.base)), assumptions) + if imlog is not None: + # I**i -> real; (2*I)**i -> complex ==> not imaginary + return False + + if ask(Q.real(expr.base) & Q.real(expr.exp), assumptions): + if ask(Q.positive(expr.base), assumptions): + return False + else: + rat = ask(Q.rational(expr.exp), assumptions) + if not rat: + return rat + if ask(Q.integer(expr.exp), assumptions): + return False + else: + half = ask(Q.integer(2*expr.exp), assumptions) + if half: + return ask(Q.negative(expr.base), assumptions) + return half + +@ImaginaryPredicate.register(log) # type:ignore +def _(expr, assumptions): + if ask(Q.real(expr.args[0]), assumptions): + if ask(Q.positive(expr.args[0]), assumptions): + return False + return + # XXX it should be enough to do + # return ask(Q.nonpositive(expr.args[0]), assumptions) + # but ask(Q.nonpositive(exp(x)), Q.imaginary(x)) -> None; + # it should return True since exp(x) will be either 0 or complex + if expr.args[0].func == exp or (expr.args[0].is_Pow and expr.args[0].base == E): + if expr.args[0].exp in [I, -I]: + return True + im = ask(Q.imaginary(expr.args[0]), assumptions) + if im is False: + return False + +@ImaginaryPredicate.register(exp) # type:ignore +def _(expr, assumptions): + a = expr.exp/I/pi + return ask(Q.integer(2*a) & ~Q.integer(a), assumptions) + +@ImaginaryPredicate.register_many(Number, NumberSymbol) # type:ignore +def _(expr, assumptions): + return not (expr.as_real_imag()[1] == 0) + +@ImaginaryPredicate.register(NaN) # type:ignore +def _(expr, assumptions): + return None + + +# AntihermitianPredicate + +@AntihermitianPredicate.register(object) # type:ignore +def _(expr, assumptions): + if isinstance(expr, MatrixBase): + return None + if ask(Q.zero(expr), assumptions): + return True + return ask(Q.imaginary(expr), assumptions) + +@AntihermitianPredicate.register(Add) # type:ignore +def _(expr, assumptions): + """ + * Antihermitian + Antihermitian -> Antihermitian + * Antihermitian + !Antihermitian -> !Antihermitian + """ + if expr.is_number: + raise MDNotImplementedError + return test_closed_group(expr, assumptions, Q.antihermitian) + +@AntihermitianPredicate.register(Mul) # type:ignore +def _(expr, assumptions): + """ + As long as there is at most only one noncommutative term: + + * Hermitian*Hermitian -> !Antihermitian + * Hermitian*Antihermitian -> Antihermitian + * Antihermitian*Antihermitian -> !Antihermitian + """ + if expr.is_number: + raise MDNotImplementedError + nccount = 0 + result = False + for arg in expr.args: + if ask(Q.antihermitian(arg), assumptions): + result = result ^ True + elif not ask(Q.hermitian(arg), assumptions): + break + if ask(~Q.commutative(arg), assumptions): + nccount += 1 + if nccount > 1: + break + else: + return result + +@AntihermitianPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + """ + * Hermitian**Integer -> !Antihermitian + * Antihermitian**Even -> !Antihermitian + * Antihermitian**Odd -> Antihermitian + """ + if expr.is_number: + raise MDNotImplementedError + if ask(Q.hermitian(expr.base), assumptions): + if ask(Q.integer(expr.exp), assumptions): + return False + elif ask(Q.antihermitian(expr.base), assumptions): + if ask(Q.even(expr.exp), assumptions): + return False + elif ask(Q.odd(expr.exp), assumptions): + return True + raise MDNotImplementedError + +@AntihermitianPredicate.register(MatrixBase) # type:ignore +def _(mat, assumptions): + rows, cols = mat.shape + ret_val = True + for i in range(rows): + for j in range(i, cols): + cond = fuzzy_bool(Eq(mat[i, j], -conjugate(mat[j, i]))) + if cond is None: + ret_val = None + if cond == False: + return False + if ret_val is None: + raise MDNotImplementedError + return ret_val + + +# AlgebraicPredicate + +@AlgebraicPredicate.register_many(AlgebraicNumber, Float, GoldenRatio, # type:ignore + ImaginaryUnit, TribonacciConstant) +def _(expr, assumptions): + return True + +@AlgebraicPredicate.register_many(ComplexInfinity, Exp1, Infinity, # type:ignore + NegativeInfinity, Pi) +def _(expr, assumptions): + return False + +@AlgebraicPredicate.register_many(Add, Mul) # type:ignore +def _(expr, assumptions): + return test_closed_group(expr, assumptions, Q.algebraic) + +@AlgebraicPredicate.register(Pow) # type:ignore +def _(expr, assumptions): + if expr.base == E: + if ask(Q.algebraic(expr.exp), assumptions): + return ask(~Q.nonzero(expr.exp), assumptions) + return + return expr.exp.is_Rational and ask(Q.algebraic(expr.base), assumptions) + +@AlgebraicPredicate.register(Rational) # type:ignore +def _(expr, assumptions): + return expr.q != 0 + +@AlgebraicPredicate.register_many(asin, atan, cos, sin, tan) # type:ignore +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.algebraic(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@AlgebraicPredicate.register(exp) # type:ignore +def _(expr, assumptions): + x = expr.exp + if ask(Q.algebraic(x), assumptions): + return ask(~Q.nonzero(x), assumptions) + +@AlgebraicPredicate.register_many(acot, cot) # type:ignore +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.algebraic(x), assumptions): + return False + +@AlgebraicPredicate.register_many(acos, log) # type:ignore +def _(expr, assumptions): + x = expr.args[0] + if ask(Q.algebraic(x), assumptions): + return ask(~Q.nonzero(x - 1), assumptions) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__init__.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e294544bfdce13633ecff762ff42861aa12719f --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__init__.py @@ -0,0 +1,5 @@ +""" +Module to implement predicate classes. + +Class of every predicate registered to ``Q`` is defined here. +""" diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/__init__.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c15e46e5e624c463cd985d1f503ebde902a7f53 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/__init__.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/calculus.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/calculus.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0178707e16158d717288f20e6489790cc42b6e40 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/calculus.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/common.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65ba5803014364004462e4a9f0b9929a32837a4f Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/common.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/matrices.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bd5f33468d42785672f4be305da6b340c3e94cb Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/matrices.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/ntheory.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/ntheory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..370089475b4efebba637bb36ba3676568b9cacaa Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/ntheory.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/order.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/order.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e82b04641e988231470cd1a799e5274a3a0cedd Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/order.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/sets.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/sets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee7142259a91a610d1bf963bbd11a339c6e834d Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/__pycache__/sets.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/calculus.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/calculus.py new file mode 100644 index 0000000000000000000000000000000000000000..f300703788683c07649ee3a0afd6e9d4eabd4567 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/calculus.py @@ -0,0 +1,82 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + +class FinitePredicate(Predicate): + """ + Finite number predicate. + + Explanation + =========== + + ``Q.finite(x)`` is true if ``x`` is a number but neither an infinity + nor a ``NaN``. In other words, ``ask(Q.finite(x))`` is true for all + numerical ``x`` having a bounded absolute value. + + Examples + ======== + + >>> from sympy import Q, ask, S, oo, I, zoo + >>> from sympy.abc import x + >>> ask(Q.finite(oo)) + False + >>> ask(Q.finite(-oo)) + False + >>> ask(Q.finite(zoo)) + False + >>> ask(Q.finite(1)) + True + >>> ask(Q.finite(2 + 3*I)) + True + >>> ask(Q.finite(x), Q.positive(x)) + True + >>> print(ask(Q.finite(S.NaN))) + None + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Finite + + """ + name = 'finite' + handler = Dispatcher( + "FiniteHandler", + doc=("Handler for Q.finite. Test that an expression is bounded respect" + " to all its variables.") + ) + + +class InfinitePredicate(Predicate): + """ + Infinite number predicate. + + ``Q.infinite(x)`` is true iff the absolute value of ``x`` is + infinity. + + """ + # TODO: Add examples + name = 'infinite' + handler = Dispatcher( + "InfiniteHandler", + doc="""Handler for Q.infinite key.""" + ) + + +class PositiveInfinitePredicate(Predicate): + """ + Positive infinity predicate. + + ``Q.positive_infinite(x)`` is true iff ``x`` is positive infinity ``oo``. + """ + name = 'positive_infinite' + handler = Dispatcher("PositiveInfiniteHandler") + + +class NegativeInfinitePredicate(Predicate): + """ + Negative infinity predicate. + + ``Q.negative_infinite(x)`` is true iff ``x`` is negative infinity ``-oo``. + """ + name = 'negative_infinite' + handler = Dispatcher("NegativeInfiniteHandler") diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/common.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a53892747131b03636abeb8f563c4f76cf3e281e --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/common.py @@ -0,0 +1,81 @@ +from sympy.assumptions import Predicate, AppliedPredicate, Q +from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le +from sympy.multipledispatch import Dispatcher + + +class CommutativePredicate(Predicate): + """ + Commutative predicate. + + Explanation + =========== + + ``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other + object with respect to multiplication operation. + + """ + # TODO: Add examples + name = 'commutative' + handler = Dispatcher("CommutativeHandler", doc="Handler for key 'commutative'.") + + +binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} + +class IsTruePredicate(Predicate): + """ + Generic predicate. + + Explanation + =========== + + ``ask(Q.is_true(x))`` is true iff ``x`` is true. This only makes + sense if ``x`` is a boolean object. + + Examples + ======== + + >>> from sympy import ask, Q + >>> from sympy.abc import x, y + >>> ask(Q.is_true(True)) + True + + Wrapping another applied predicate just returns the applied predicate. + + >>> Q.is_true(Q.even(x)) + Q.even(x) + + Wrapping binary relation classes in SymPy core returns applied binary + relational predicates. + + >>> from sympy import Eq, Gt + >>> Q.is_true(Eq(x, y)) + Q.eq(x, y) + >>> Q.is_true(Gt(x, y)) + Q.gt(x, y) + + Notes + ===== + + This class is designed to wrap the boolean objects so that they can + behave as if they are applied predicates. Consequently, wrapping another + applied predicate is unnecessary and thus it just returns the argument. + Also, binary relation classes in SymPy core have binary predicates to + represent themselves and thus wrapping them with ``Q.is_true`` converts them + to these applied predicates. + + """ + name = 'is_true' + handler = Dispatcher( + "IsTrueHandler", + doc="Wrapper allowing to query the truth value of a boolean expression." + ) + + def __call__(self, arg): + # No need to wrap another predicate + if isinstance(arg, AppliedPredicate): + return arg + # Convert relational predicates instead of wrapping them + if getattr(arg, "is_Relational", False): + pred = binrelpreds[type(arg)] + return pred(*arg.args) + return super().__call__(arg) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/matrices.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..151e78c4ff345800e1d2f17973fb0591b8d379d2 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/matrices.py @@ -0,0 +1,511 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + +class SquarePredicate(Predicate): + """ + Square matrix predicate. + + Explanation + =========== + + ``Q.square(x)`` is true iff ``x`` is a square matrix. A square matrix + is a matrix with the same number of rows and columns. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('X', 2, 3) + >>> ask(Q.square(X)) + True + >>> ask(Q.square(Y)) + False + >>> ask(Q.square(ZeroMatrix(3, 3))) + True + >>> ask(Q.square(Identity(3))) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Square_matrix + + """ + name = 'square' + handler = Dispatcher("SquareHandler", doc="Handler for Q.square.") + + +class SymmetricPredicate(Predicate): + """ + Symmetric matrix predicate. + + Explanation + =========== + + ``Q.symmetric(x)`` is true iff ``x`` is a square matrix and is equal to + its transpose. Every square diagonal matrix is a symmetric matrix. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) + True + >>> ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) + True + >>> ask(Q.symmetric(Y)) + False + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Symmetric_matrix + + """ + # TODO: Add handlers to make these keys work with + # actual matrices and add more examples in the docstring. + name = 'symmetric' + handler = Dispatcher("SymmetricHandler", doc="Handler for Q.symmetric.") + + +class InvertiblePredicate(Predicate): + """ + Invertible matrix predicate. + + Explanation + =========== + + ``Q.invertible(x)`` is true iff ``x`` is an invertible matrix. + A square matrix is called invertible only if its determinant is 0. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.invertible(X*Y), Q.invertible(X)) + False + >>> ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) + True + >>> ask(Q.invertible(X), Q.fullrank(X) & Q.square(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Invertible_matrix + + """ + name = 'invertible' + handler = Dispatcher("InvertibleHandler", doc="Handler for Q.invertible.") + + +class OrthogonalPredicate(Predicate): + """ + Orthogonal matrix predicate. + + Explanation + =========== + + ``Q.orthogonal(x)`` is true iff ``x`` is an orthogonal matrix. + A square matrix ``M`` is an orthogonal matrix if it satisfies + ``M^TM = MM^T = I`` where ``M^T`` is the transpose matrix of + ``M`` and ``I`` is an identity matrix. Note that an orthogonal + matrix is necessarily invertible. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.orthogonal(Y)) + False + >>> ask(Q.orthogonal(X*Z*X), Q.orthogonal(X) & Q.orthogonal(Z)) + True + >>> ask(Q.orthogonal(Identity(3))) + True + >>> ask(Q.invertible(X), Q.orthogonal(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Orthogonal_matrix + + """ + name = 'orthogonal' + handler = Dispatcher("OrthogonalHandler", doc="Handler for key 'orthogonal'.") + + +class UnitaryPredicate(Predicate): + """ + Unitary matrix predicate. + + Explanation + =========== + + ``Q.unitary(x)`` is true iff ``x`` is a unitary matrix. + Unitary matrix is an analogue to orthogonal matrix. A square + matrix ``M`` with complex elements is unitary if :math:``M^TM = MM^T= I`` + where :math:``M^T`` is the conjugate transpose matrix of ``M``. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.unitary(Y)) + False + >>> ask(Q.unitary(X*Z*X), Q.unitary(X) & Q.unitary(Z)) + True + >>> ask(Q.unitary(Identity(3))) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Unitary_matrix + + """ + name = 'unitary' + handler = Dispatcher("UnitaryHandler", doc="Handler for key 'unitary'.") + + +class FullRankPredicate(Predicate): + """ + Fullrank matrix predicate. + + Explanation + =========== + + ``Q.fullrank(x)`` is true iff ``x`` is a full rank matrix. + A matrix is full rank if all rows and columns of the matrix + are linearly independent. A square matrix is full rank iff + its determinant is nonzero. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> ask(Q.fullrank(X.T), Q.fullrank(X)) + True + >>> ask(Q.fullrank(ZeroMatrix(3, 3))) + False + >>> ask(Q.fullrank(Identity(3))) + True + + """ + name = 'fullrank' + handler = Dispatcher("FullRankHandler", doc="Handler for key 'fullrank'.") + + +class PositiveDefinitePredicate(Predicate): + r""" + Positive definite matrix predicate. + + Explanation + =========== + + If $M$ is a :math:`n \times n` symmetric real matrix, it is said + to be positive definite if :math:`Z^TMZ` is positive for + every non-zero column vector $Z$ of $n$ real numbers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, Identity + >>> X = MatrixSymbol('X', 2, 2) + >>> Y = MatrixSymbol('Y', 2, 3) + >>> Z = MatrixSymbol('Z', 2, 2) + >>> ask(Q.positive_definite(Y)) + False + >>> ask(Q.positive_definite(Identity(3))) + True + >>> ask(Q.positive_definite(X + Z), Q.positive_definite(X) & + ... Q.positive_definite(Z)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Positive-definite_matrix + + """ + name = "positive_definite" + handler = Dispatcher("PositiveDefiniteHandler", doc="Handler for key 'positive_definite'.") + + +class UpperTriangularPredicate(Predicate): + """ + Upper triangular matrix predicate. + + Explanation + =========== + + A matrix $M$ is called upper triangular matrix if :math:`M_{ij}=0` + for :math:`i>> from sympy import Q, ask, ZeroMatrix, Identity + >>> ask(Q.upper_triangular(Identity(3))) + True + >>> ask(Q.upper_triangular(ZeroMatrix(3, 3))) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/UpperTriangularMatrix.html + + """ + name = "upper_triangular" + handler = Dispatcher("UpperTriangularHandler", doc="Handler for key 'upper_triangular'.") + + +class LowerTriangularPredicate(Predicate): + """ + Lower triangular matrix predicate. + + Explanation + =========== + + A matrix $M$ is called lower triangular matrix if :math:`M_{ij}=0` + for :math:`i>j`. + + Examples + ======== + + >>> from sympy import Q, ask, ZeroMatrix, Identity + >>> ask(Q.lower_triangular(Identity(3))) + True + >>> ask(Q.lower_triangular(ZeroMatrix(3, 3))) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/LowerTriangularMatrix.html + + """ + name = "lower_triangular" + handler = Dispatcher("LowerTriangularHandler", doc="Handler for key 'lower_triangular'.") + + +class DiagonalPredicate(Predicate): + """ + Diagonal matrix predicate. + + Explanation + =========== + + ``Q.diagonal(x)`` is true iff ``x`` is a diagonal matrix. A diagonal + matrix is a matrix in which the entries outside the main diagonal + are all zero. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix + >>> X = MatrixSymbol('X', 2, 2) + >>> ask(Q.diagonal(ZeroMatrix(3, 3))) + True + >>> ask(Q.diagonal(X), Q.lower_triangular(X) & + ... Q.upper_triangular(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Diagonal_matrix + + """ + name = "diagonal" + handler = Dispatcher("DiagonalHandler", doc="Handler for key 'diagonal'.") + + +class IntegerElementsPredicate(Predicate): + """ + Integer elements matrix predicate. + + Explanation + =========== + + ``Q.integer_elements(x)`` is true iff all the elements of ``x`` + are integers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.integer(X[1, 2]), Q.integer_elements(X)) + True + + """ + name = "integer_elements" + handler = Dispatcher("IntegerElementsHandler", doc="Handler for key 'integer_elements'.") + + +class RealElementsPredicate(Predicate): + """ + Real elements matrix predicate. + + Explanation + =========== + + ``Q.real_elements(x)`` is true iff all the elements of ``x`` + are real numbers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.real(X[1, 2]), Q.real_elements(X)) + True + + """ + name = "real_elements" + handler = Dispatcher("RealElementsHandler", doc="Handler for key 'real_elements'.") + + +class ComplexElementsPredicate(Predicate): + """ + Complex elements matrix predicate. + + Explanation + =========== + + ``Q.complex_elements(x)`` is true iff all the elements of ``x`` + are complex numbers. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.complex(X[1, 2]), Q.complex_elements(X)) + True + >>> ask(Q.complex_elements(X), Q.integer_elements(X)) + True + + """ + name = "complex_elements" + handler = Dispatcher("ComplexElementsHandler", doc="Handler for key 'complex_elements'.") + + +class SingularPredicate(Predicate): + """ + Singular matrix predicate. + + A matrix is singular iff the value of its determinant is 0. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.singular(X), Q.invertible(X)) + False + >>> ask(Q.singular(X), ~Q.invertible(X)) + True + + References + ========== + + .. [1] https://mathworld.wolfram.com/SingularMatrix.html + + """ + name = "singular" + handler = Dispatcher("SingularHandler", doc="Predicate fore key 'singular'.") + + +class NormalPredicate(Predicate): + """ + Normal matrix predicate. + + A matrix is normal if it commutes with its conjugate transpose. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.normal(X), Q.unitary(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Normal_matrix + + """ + name = "normal" + handler = Dispatcher("NormalHandler", doc="Predicate fore key 'normal'.") + + +class TriangularPredicate(Predicate): + """ + Triangular matrix predicate. + + Explanation + =========== + + ``Q.triangular(X)`` is true if ``X`` is one that is either lower + triangular or upper triangular. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.triangular(X), Q.upper_triangular(X)) + True + >>> ask(Q.triangular(X), Q.lower_triangular(X)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Triangular_matrix + + """ + name = "triangular" + handler = Dispatcher("TriangularHandler", doc="Predicate fore key 'triangular'.") + + +class UnitTriangularPredicate(Predicate): + """ + Unit triangular matrix predicate. + + Explanation + =========== + + A unit triangular matrix is a triangular matrix with 1s + on the diagonal. + + Examples + ======== + + >>> from sympy import Q, ask, MatrixSymbol + >>> X = MatrixSymbol('X', 4, 4) + >>> ask(Q.triangular(X), Q.unit_triangular(X)) + True + + """ + name = "unit_triangular" + handler = Dispatcher("UnitTriangularHandler", doc="Predicate fore key 'unit_triangular'.") diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/ntheory.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/ntheory.py new file mode 100644 index 0000000000000000000000000000000000000000..6c598e0ed1bd4a1170aa28044f9ae6de2fa1a1e0 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/ntheory.py @@ -0,0 +1,126 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + + +class PrimePredicate(Predicate): + """ + Prime number predicate. + + Explanation + =========== + + ``ask(Q.prime(x))`` is true iff ``x`` is a natural number greater + than 1 that has no positive divisors other than ``1`` and the + number itself. + + Examples + ======== + + >>> from sympy import Q, ask + >>> ask(Q.prime(0)) + False + >>> ask(Q.prime(1)) + False + >>> ask(Q.prime(2)) + True + >>> ask(Q.prime(20)) + False + >>> ask(Q.prime(-3)) + False + + """ + name = 'prime' + handler = Dispatcher( + "PrimeHandler", + doc=("Handler for key 'prime'. Test that an expression represents a prime" + " number. When the expression is an exact number, the result (when True)" + " is subject to the limitations of isprime() which is used to return the " + "result.") + ) + + +class CompositePredicate(Predicate): + """ + Composite number predicate. + + Explanation + =========== + + ``ask(Q.composite(x))`` is true iff ``x`` is a positive integer and has + at least one positive divisor other than ``1`` and the number itself. + + Examples + ======== + + >>> from sympy import Q, ask + >>> ask(Q.composite(0)) + False + >>> ask(Q.composite(1)) + False + >>> ask(Q.composite(2)) + False + >>> ask(Q.composite(20)) + True + + """ + name = 'composite' + handler = Dispatcher("CompositeHandler", doc="Handler for key 'composite'.") + + +class EvenPredicate(Predicate): + """ + Even number predicate. + + Explanation + =========== + + ``ask(Q.even(x))`` is true iff ``x`` belongs to the set of even + integers. + + Examples + ======== + + >>> from sympy import Q, ask, pi + >>> ask(Q.even(0)) + True + >>> ask(Q.even(2)) + True + >>> ask(Q.even(3)) + False + >>> ask(Q.even(pi)) + False + + """ + name = 'even' + handler = Dispatcher("EvenHandler", doc="Handler for key 'even'.") + + +class OddPredicate(Predicate): + """ + Odd number predicate. + + Explanation + =========== + + ``ask(Q.odd(x))`` is true iff ``x`` belongs to the set of odd numbers. + + Examples + ======== + + >>> from sympy import Q, ask, pi + >>> ask(Q.odd(0)) + False + >>> ask(Q.odd(2)) + False + >>> ask(Q.odd(3)) + True + >>> ask(Q.odd(pi)) + False + + """ + name = 'odd' + handler = Dispatcher( + "OddHandler", + doc=("Handler for key 'odd'. Test that an expression represents an odd" + " number.") + ) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/order.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/order.py new file mode 100644 index 0000000000000000000000000000000000000000..86bfb2ae49789efd5b0df99e2cfc63984e956dd0 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/order.py @@ -0,0 +1,390 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + + +class NegativePredicate(Predicate): + r""" + Negative number predicate. + + Explanation + =========== + + ``Q.negative(x)`` is true iff ``x`` is a real number and :math:`x < 0`, that is, + it is in the interval :math:`(-\infty, 0)`. Note in particular that negative + infinity is not negative. + + A few important facts about negative numbers: + + - Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same + thing. ``~Q.negative(x)`` simply means that ``x`` is not negative, + whereas ``Q.nonnegative(x)`` means that ``x`` is real and not + negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to + ``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is + true, whereas ``Q.nonnegative(I)`` is false. + + - See the documentation of ``Q.real`` for more information about + related facts. + + Examples + ======== + + >>> from sympy import Q, ask, symbols, I + >>> x = symbols('x') + >>> ask(Q.negative(x), Q.real(x) & ~Q.positive(x) & ~Q.zero(x)) + True + >>> ask(Q.negative(-1)) + True + >>> ask(Q.nonnegative(I)) + False + >>> ask(~Q.negative(I)) + True + + """ + name = 'negative' + handler = Dispatcher( + "NegativeHandler", + doc=("Handler for Q.negative. Test that an expression is strictly less" + " than zero.") + ) + + +class NonNegativePredicate(Predicate): + """ + Nonnegative real number predicate. + + Explanation + =========== + + ``ask(Q.nonnegative(x))`` is true iff ``x`` belongs to the set of + positive numbers including zero. + + - Note that ``Q.nonnegative`` and ``~Q.negative`` are *not* the same + thing. ``~Q.negative(x)`` simply means that ``x`` is not negative, + whereas ``Q.nonnegative(x)`` means that ``x`` is real and not + negative, i.e., ``Q.nonnegative(x)`` is logically equivalent to + ``Q.zero(x) | Q.positive(x)``. So for example, ``~Q.negative(I)`` is + true, whereas ``Q.nonnegative(I)`` is false. + + Examples + ======== + + >>> from sympy import Q, ask, I + >>> ask(Q.nonnegative(1)) + True + >>> ask(Q.nonnegative(0)) + True + >>> ask(Q.nonnegative(-1)) + False + >>> ask(Q.nonnegative(I)) + False + >>> ask(Q.nonnegative(-I)) + False + + """ + name = 'nonnegative' + handler = Dispatcher( + "NonNegativeHandler", + doc=("Handler for Q.nonnegative.") + ) + + +class NonZeroPredicate(Predicate): + """ + Nonzero real number predicate. + + Explanation + =========== + + ``ask(Q.nonzero(x))`` is true iff ``x`` is real and ``x`` is not zero. Note in + particular that ``Q.nonzero(x)`` is false if ``x`` is not real. Use + ``~Q.zero(x)`` if you want the negation of being zero without any real + assumptions. + + A few important facts about nonzero numbers: + + - ``Q.nonzero`` is logically equivalent to ``Q.positive | Q.negative``. + + - See the documentation of ``Q.real`` for more information about + related facts. + + Examples + ======== + + >>> from sympy import Q, ask, symbols, I, oo + >>> x = symbols('x') + >>> print(ask(Q.nonzero(x), ~Q.zero(x))) + None + >>> ask(Q.nonzero(x), Q.positive(x)) + True + >>> ask(Q.nonzero(x), Q.zero(x)) + False + >>> ask(Q.nonzero(0)) + False + >>> ask(Q.nonzero(I)) + False + >>> ask(~Q.zero(I)) + True + >>> ask(Q.nonzero(oo)) + False + + """ + name = 'nonzero' + handler = Dispatcher( + "NonZeroHandler", + doc=("Handler for key 'nonzero'. Test that an expression is not identically" + " zero.") + ) + + +class ZeroPredicate(Predicate): + """ + Zero number predicate. + + Explanation + =========== + + ``ask(Q.zero(x))`` is true iff the value of ``x`` is zero. + + Examples + ======== + + >>> from sympy import ask, Q, oo, symbols + >>> x, y = symbols('x, y') + >>> ask(Q.zero(0)) + True + >>> ask(Q.zero(1/oo)) + True + >>> print(ask(Q.zero(0*oo))) + None + >>> ask(Q.zero(1)) + False + >>> ask(Q.zero(x*y), Q.zero(x) | Q.zero(y)) + True + + """ + name = 'zero' + handler = Dispatcher( + "ZeroHandler", + doc="Handler for key 'zero'." + ) + + +class NonPositivePredicate(Predicate): + """ + Nonpositive real number predicate. + + Explanation + =========== + + ``ask(Q.nonpositive(x))`` is true iff ``x`` belongs to the set of + negative numbers including zero. + + - Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same + thing. ``~Q.positive(x)`` simply means that ``x`` is not positive, + whereas ``Q.nonpositive(x)`` means that ``x`` is real and not + positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to + `Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is + true, whereas ``Q.nonpositive(I)`` is false. + + Examples + ======== + + >>> from sympy import Q, ask, I + + >>> ask(Q.nonpositive(-1)) + True + >>> ask(Q.nonpositive(0)) + True + >>> ask(Q.nonpositive(1)) + False + >>> ask(Q.nonpositive(I)) + False + >>> ask(Q.nonpositive(-I)) + False + + """ + name = 'nonpositive' + handler = Dispatcher( + "NonPositiveHandler", + doc="Handler for key 'nonpositive'." + ) + + +class PositivePredicate(Predicate): + r""" + Positive real number predicate. + + Explanation + =========== + + ``Q.positive(x)`` is true iff ``x`` is real and `x > 0`, that is if ``x`` + is in the interval `(0, \infty)`. In particular, infinity is not + positive. + + A few important facts about positive numbers: + + - Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same + thing. ``~Q.positive(x)`` simply means that ``x`` is not positive, + whereas ``Q.nonpositive(x)`` means that ``x`` is real and not + positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to + `Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is + true, whereas ``Q.nonpositive(I)`` is false. + + - See the documentation of ``Q.real`` for more information about + related facts. + + Examples + ======== + + >>> from sympy import Q, ask, symbols, I + >>> x = symbols('x') + >>> ask(Q.positive(x), Q.real(x) & ~Q.negative(x) & ~Q.zero(x)) + True + >>> ask(Q.positive(1)) + True + >>> ask(Q.nonpositive(I)) + False + >>> ask(~Q.positive(I)) + True + + """ + name = 'positive' + handler = Dispatcher( + "PositiveHandler", + doc=("Handler for key 'positive'. Test that an expression is strictly" + " greater than zero.") + ) + + +class ExtendedPositivePredicate(Predicate): + r""" + Positive extended real number predicate. + + Explanation + =========== + + ``Q.extended_positive(x)`` is true iff ``x`` is extended real and + `x > 0`, that is if ``x`` is in the interval `(0, \infty]`. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_positive(1)) + True + >>> ask(Q.extended_positive(oo)) + True + >>> ask(Q.extended_positive(I)) + False + + """ + name = 'extended_positive' + handler = Dispatcher("ExtendedPositiveHandler") + + +class ExtendedNegativePredicate(Predicate): + r""" + Negative extended real number predicate. + + Explanation + =========== + + ``Q.extended_negative(x)`` is true iff ``x`` is extended real and + `x < 0`, that is if ``x`` is in the interval `[-\infty, 0)`. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_negative(-1)) + True + >>> ask(Q.extended_negative(-oo)) + True + >>> ask(Q.extended_negative(-I)) + False + + """ + name = 'extended_negative' + handler = Dispatcher("ExtendedNegativeHandler") + + +class ExtendedNonZeroPredicate(Predicate): + """ + Nonzero extended real number predicate. + + Explanation + =========== + + ``ask(Q.extended_nonzero(x))`` is true iff ``x`` is extended real and + ``x`` is not zero. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_nonzero(-1)) + True + >>> ask(Q.extended_nonzero(oo)) + True + >>> ask(Q.extended_nonzero(I)) + False + + """ + name = 'extended_nonzero' + handler = Dispatcher("ExtendedNonZeroHandler") + + +class ExtendedNonPositivePredicate(Predicate): + """ + Nonpositive extended real number predicate. + + Explanation + =========== + + ``ask(Q.extended_nonpositive(x))`` is true iff ``x`` is extended real and + ``x`` is not positive. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_nonpositive(-1)) + True + >>> ask(Q.extended_nonpositive(oo)) + False + >>> ask(Q.extended_nonpositive(0)) + True + >>> ask(Q.extended_nonpositive(I)) + False + + """ + name = 'extended_nonpositive' + handler = Dispatcher("ExtendedNonPositiveHandler") + + +class ExtendedNonNegativePredicate(Predicate): + """ + Nonnegative extended real number predicate. + + Explanation + =========== + + ``ask(Q.extended_nonnegative(x))`` is true iff ``x`` is extended real and + ``x`` is not negative. + + Examples + ======== + + >>> from sympy import ask, I, oo, Q + >>> ask(Q.extended_nonnegative(-1)) + False + >>> ask(Q.extended_nonnegative(oo)) + True + >>> ask(Q.extended_nonnegative(0)) + True + >>> ask(Q.extended_nonnegative(I)) + False + + """ + name = 'extended_nonnegative' + handler = Dispatcher("ExtendedNonNegativeHandler") diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/sets.py b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..18261cee2d9de65df14a31a56b2cd22328328ed0 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/predicates/sets.py @@ -0,0 +1,399 @@ +from sympy.assumptions import Predicate +from sympy.multipledispatch import Dispatcher + + +class IntegerPredicate(Predicate): + """ + Integer predicate. + + Explanation + =========== + + ``Q.integer(x)`` is true iff ``x`` belongs to the set of integer + numbers. + + Examples + ======== + + >>> from sympy import Q, ask, S + >>> ask(Q.integer(5)) + True + >>> ask(Q.integer(S(1)/2)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Integer + + """ + name = 'integer' + handler = Dispatcher( + "IntegerHandler", + doc=("Handler for Q.integer.\n\n" + "Test that an expression belongs to the field of integer numbers.") + ) + + +class NonIntegerPredicate(Predicate): + """ + Non-integer extended real predicate. + """ + name = 'noninteger' + handler = Dispatcher( + "NonIntegerHandler", + doc=("Handler for Q.noninteger.\n\n" + "Test that an expression is a non-integer extended real number.") + ) + + +class RationalPredicate(Predicate): + """ + Rational number predicate. + + Explanation + =========== + + ``Q.rational(x)`` is true iff ``x`` belongs to the set of + rational numbers. + + Examples + ======== + + >>> from sympy import ask, Q, pi, S + >>> ask(Q.rational(0)) + True + >>> ask(Q.rational(S(1)/2)) + True + >>> ask(Q.rational(pi)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Rational_number + + """ + name = 'rational' + handler = Dispatcher( + "RationalHandler", + doc=("Handler for Q.rational.\n\n" + "Test that an expression belongs to the field of rational numbers.") + ) + + +class IrrationalPredicate(Predicate): + """ + Irrational number predicate. + + Explanation + =========== + + ``Q.irrational(x)`` is true iff ``x`` is any real number that + cannot be expressed as a ratio of integers. + + Examples + ======== + + >>> from sympy import ask, Q, pi, S, I + >>> ask(Q.irrational(0)) + False + >>> ask(Q.irrational(S(1)/2)) + False + >>> ask(Q.irrational(pi)) + True + >>> ask(Q.irrational(I)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Irrational_number + + """ + name = 'irrational' + handler = Dispatcher( + "IrrationalHandler", + doc=("Handler for Q.irrational.\n\n" + "Test that an expression is irrational numbers.") + ) + + +class RealPredicate(Predicate): + r""" + Real number predicate. + + Explanation + =========== + + ``Q.real(x)`` is true iff ``x`` is a real number, i.e., it is in the + interval `(-\infty, \infty)`. Note that, in particular the + infinities are not real. Use ``Q.extended_real`` if you want to + consider those as well. + + A few important facts about reals: + + - Every real number is positive, negative, or zero. Furthermore, + because these sets are pairwise disjoint, each real number is + exactly one of those three. + + - Every real number is also complex. + + - Every real number is finite. + + - Every real number is either rational or irrational. + + - Every real number is either algebraic or transcendental. + + - The facts ``Q.negative``, ``Q.zero``, ``Q.positive``, + ``Q.nonnegative``, ``Q.nonpositive``, ``Q.nonzero``, + ``Q.integer``, ``Q.rational``, and ``Q.irrational`` all imply + ``Q.real``, as do all facts that imply those facts. + + - The facts ``Q.algebraic``, and ``Q.transcendental`` do not imply + ``Q.real``; they imply ``Q.complex``. An algebraic or + transcendental number may or may not be real. + + - The "non" facts (i.e., ``Q.nonnegative``, ``Q.nonzero``, + ``Q.nonpositive`` and ``Q.noninteger``) are not equivalent to + not the fact, but rather, not the fact *and* ``Q.real``. + For example, ``Q.nonnegative`` means ``~Q.negative & Q.real``. + So for example, ``I`` is not nonnegative, nonzero, or + nonpositive. + + Examples + ======== + + >>> from sympy import Q, ask, symbols + >>> x = symbols('x') + >>> ask(Q.real(x), Q.positive(x)) + True + >>> ask(Q.real(0)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Real_number + + """ + name = 'real' + handler = Dispatcher( + "RealHandler", + doc=("Handler for Q.real.\n\n" + "Test that an expression belongs to the field of real numbers.") + ) + + +class ExtendedRealPredicate(Predicate): + r""" + Extended real predicate. + + Explanation + =========== + + ``Q.extended_real(x)`` is true iff ``x`` is a real number or + `\{-\infty, \infty\}`. + + See documentation of ``Q.real`` for more information about related + facts. + + Examples + ======== + + >>> from sympy import ask, Q, oo, I + >>> ask(Q.extended_real(1)) + True + >>> ask(Q.extended_real(I)) + False + >>> ask(Q.extended_real(oo)) + True + + """ + name = 'extended_real' + handler = Dispatcher( + "ExtendedRealHandler", + doc=("Handler for Q.extended_real.\n\n" + "Test that an expression belongs to the field of extended real\n" + "numbers, that is real numbers union {Infinity, -Infinity}.") + ) + + +class HermitianPredicate(Predicate): + """ + Hermitian predicate. + + Explanation + =========== + + ``ask(Q.hermitian(x))`` is true iff ``x`` belongs to the set of + Hermitian operators. + + References + ========== + + .. [1] https://mathworld.wolfram.com/HermitianOperator.html + + """ + # TODO: Add examples + name = 'hermitian' + handler = Dispatcher( + "HermitianHandler", + doc=("Handler for Q.hermitian.\n\n" + "Test that an expression belongs to the field of Hermitian operators.") + ) + + +class ComplexPredicate(Predicate): + """ + Complex number predicate. + + Explanation + =========== + + ``Q.complex(x)`` is true iff ``x`` belongs to the set of complex + numbers. Note that every complex number is finite. + + Examples + ======== + + >>> from sympy import Q, Symbol, ask, I, oo + >>> x = Symbol('x') + >>> ask(Q.complex(0)) + True + >>> ask(Q.complex(2 + 3*I)) + True + >>> ask(Q.complex(oo)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Complex_number + + """ + name = 'complex' + handler = Dispatcher( + "ComplexHandler", + doc=("Handler for Q.complex.\n\n" + "Test that an expression belongs to the field of complex numbers.") + ) + + +class ImaginaryPredicate(Predicate): + """ + Imaginary number predicate. + + Explanation + =========== + + ``Q.imaginary(x)`` is true iff ``x`` can be written as a real + number multiplied by the imaginary unit ``I``. Please note that ``0`` + is not considered to be an imaginary number. + + Examples + ======== + + >>> from sympy import Q, ask, I + >>> ask(Q.imaginary(3*I)) + True + >>> ask(Q.imaginary(2 + 3*I)) + False + >>> ask(Q.imaginary(0)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Imaginary_number + + """ + name = 'imaginary' + handler = Dispatcher( + "ImaginaryHandler", + doc=("Handler for Q.imaginary.\n\n" + "Test that an expression belongs to the field of imaginary numbers,\n" + "that is, numbers in the form x*I, where x is real.") + ) + + +class AntihermitianPredicate(Predicate): + """ + Antihermitian predicate. + + Explanation + =========== + + ``Q.antihermitian(x)`` is true iff ``x`` belongs to the field of + antihermitian operators, i.e., operators in the form ``x*I``, where + ``x`` is Hermitian. + + References + ========== + + .. [1] https://mathworld.wolfram.com/HermitianOperator.html + + """ + # TODO: Add examples + name = 'antihermitian' + handler = Dispatcher( + "AntiHermitianHandler", + doc=("Handler for Q.antihermitian.\n\n" + "Test that an expression belongs to the field of anti-Hermitian\n" + "operators, that is, operators in the form x*I, where x is Hermitian.") + ) + + +class AlgebraicPredicate(Predicate): + r""" + Algebraic number predicate. + + Explanation + =========== + + ``Q.algebraic(x)`` is true iff ``x`` belongs to the set of + algebraic numbers. ``x`` is algebraic if there is some polynomial + in ``p(x)\in \mathbb\{Q\}[x]`` such that ``p(x) = 0``. + + Examples + ======== + + >>> from sympy import ask, Q, sqrt, I, pi + >>> ask(Q.algebraic(sqrt(2))) + True + >>> ask(Q.algebraic(I)) + True + >>> ask(Q.algebraic(pi)) + False + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Algebraic_number + + """ + name = 'algebraic' + AlgebraicHandler = Dispatcher( + "AlgebraicHandler", + doc="""Handler for Q.algebraic key.""" + ) + + +class TranscendentalPredicate(Predicate): + """ + Transcedental number predicate. + + Explanation + =========== + + ``Q.transcendental(x)`` is true iff ``x`` belongs to the set of + transcendental numbers. A transcendental number is a real + or complex number that is not algebraic. + + """ + # TODO: Add examples + name = 'transcendental' + handler = Dispatcher( + "Transcendental", + doc="""Handler for Q.transcendental key.""" + ) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__init__.py b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04f5ed37893766feec941614691a9177f14e4027 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__init__.py @@ -0,0 +1,13 @@ +""" +A module to implement finitary relations [1] as predicate. + +References +========== + +.. [1] https://en.wikipedia.org/wiki/Finitary_relation + +""" + +__all__ = ['BinaryRelation', 'AppliedBinaryRelation'] + +from .binrel import BinaryRelation, AppliedBinaryRelation diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__pycache__/binrel.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__pycache__/binrel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a836c7f26d5653f4029893657abe4ed95c148ee Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__pycache__/binrel.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__pycache__/equality.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__pycache__/equality.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf90155bc9697d5c8df2c4980d39abccd0b801bc Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/__pycache__/equality.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/relation/equality.py b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/equality.py new file mode 100644 index 0000000000000000000000000000000000000000..d467cea2da706de2cbbc9875f93c7f8e324a9088 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/relation/equality.py @@ -0,0 +1,302 @@ +""" +Module for mathematical equality [1] and inequalities [2]. + +The purpose of this module is to provide the instances which represent the +binary predicates in order to combine the relationals into logical inference +system. Objects such as ``Q.eq``, ``Q.lt`` should remain internal to +assumptions module, and user must use the classes such as :obj:`~.Eq()`, +:obj:`~.Lt()` instead to construct the relational expressions. + +References +========== + +.. [1] https://en.wikipedia.org/wiki/Equality_(mathematics) +.. [2] https://en.wikipedia.org/wiki/Inequality_(mathematics) +""" +from sympy.assumptions import Q +from sympy.core.relational import is_eq, is_neq, is_gt, is_ge, is_lt, is_le + +from .binrel import BinaryRelation + +__all__ = ['EqualityPredicate', 'UnequalityPredicate', 'StrictGreaterThanPredicate', + 'GreaterThanPredicate', 'StrictLessThanPredicate', 'LessThanPredicate'] + + +class EqualityPredicate(BinaryRelation): + """ + Binary predicate for $=$. + + The purpose of this class is to provide the instance which represent + the equality predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Eq()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_eq` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.eq(0, 0) + Q.eq(0, 0) + >>> ask(_) + True + + See Also + ======== + + sympy.core.relational.Eq + + """ + is_reflexive = True + is_symmetric = True + + name = 'eq' + handler = None # Do not allow dispatching by this predicate + + @property + def negated(self): + return Q.ne + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_eq is None + assumptions = None + return is_eq(*args, assumptions) + + +class UnequalityPredicate(BinaryRelation): + r""" + Binary predicate for $\neq$. + + The purpose of this class is to provide the instance which represent + the inequation predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Ne()` instead to construct the inequation expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_neq` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.ne(0, 0) + Q.ne(0, 0) + >>> ask(_) + False + + See Also + ======== + + sympy.core.relational.Ne + + """ + is_reflexive = False + is_symmetric = True + + name = 'ne' + handler = None + + @property + def negated(self): + return Q.eq + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_neq is None + assumptions = None + return is_neq(*args, assumptions) + + +class StrictGreaterThanPredicate(BinaryRelation): + """ + Binary predicate for $>$. + + The purpose of this class is to provide the instance which represent + the ">" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Gt()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_gt` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.gt(0, 0) + Q.gt(0, 0) + >>> ask(_) + False + + See Also + ======== + + sympy.core.relational.Gt + + """ + is_reflexive = False + is_symmetric = False + + name = 'gt' + handler = None + + @property + def reversed(self): + return Q.lt + + @property + def negated(self): + return Q.le + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_gt is None + assumptions = None + return is_gt(*args, assumptions) + + +class GreaterThanPredicate(BinaryRelation): + """ + Binary predicate for $>=$. + + The purpose of this class is to provide the instance which represent + the ">=" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Ge()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_ge` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.ge(0, 0) + Q.ge(0, 0) + >>> ask(_) + True + + See Also + ======== + + sympy.core.relational.Ge + + """ + is_reflexive = True + is_symmetric = False + + name = 'ge' + handler = None + + @property + def reversed(self): + return Q.le + + @property + def negated(self): + return Q.lt + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_ge is None + assumptions = None + return is_ge(*args, assumptions) + + +class StrictLessThanPredicate(BinaryRelation): + """ + Binary predicate for $<$. + + The purpose of this class is to provide the instance which represent + the "<" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Lt()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_lt` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.lt(0, 0) + Q.lt(0, 0) + >>> ask(_) + False + + See Also + ======== + + sympy.core.relational.Lt + + """ + is_reflexive = False + is_symmetric = False + + name = 'lt' + handler = None + + @property + def reversed(self): + return Q.gt + + @property + def negated(self): + return Q.ge + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_lt is None + assumptions = None + return is_lt(*args, assumptions) + + +class LessThanPredicate(BinaryRelation): + """ + Binary predicate for $<=$. + + The purpose of this class is to provide the instance which represent + the "<=" predicate in order to allow the logical inference. + This class must remain internal to assumptions module and user must + use :obj:`~.Le()` instead to construct the equality expression. + + Evaluating this predicate to ``True`` or ``False`` is done by + :func:`~.core.relational.is_le` + + Examples + ======== + + >>> from sympy import ask, Q + >>> Q.le(0, 0) + Q.le(0, 0) + >>> ask(_) + True + + See Also + ======== + + sympy.core.relational.Le + + """ + is_reflexive = True + is_symmetric = False + + name = 'le' + handler = None + + @property + def reversed(self): + return Q.ge + + @property + def negated(self): + return Q.gt + + def eval(self, args, assumptions=True): + if assumptions == True: + # default assumptions for is_le is None + assumptions = None + return is_le(*args, assumptions) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/satask.py b/vila/lib/python3.10/site-packages/sympy/assumptions/satask.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc13f6d3bc3fb7f573c8d5d0564b780440c1a8c --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/satask.py @@ -0,0 +1,369 @@ +""" +Module to evaluate the proposition with assumptions using SAT algorithm. +""" + +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.kind import NumberKind, UndefinedKind +from sympy.assumptions.ask_generated import get_all_known_matrix_facts, get_all_known_number_facts +from sympy.assumptions.assume import global_assumptions, AppliedPredicate +from sympy.assumptions.sathandlers import class_fact_registry +from sympy.core import oo +from sympy.logic.inference import satisfiable +from sympy.assumptions.cnf import CNF, EncodedCNF +from sympy.matrices.kind import MatrixKind + + +def satask(proposition, assumptions=True, context=global_assumptions, + use_known_facts=True, iterations=oo): + """ + Function to evaluate the proposition with assumptions using SAT algorithm. + + This function extracts every fact relevant to the expressions composing + proposition and assumptions. For example, if a predicate containing + ``Abs(x)`` is proposed, then ``Q.zero(Abs(x)) | Q.positive(Abs(x))`` + will be found and passed to SAT solver because ``Q.nonnegative`` is + registered as a fact for ``Abs``. + + Proposition is evaluated to ``True`` or ``False`` if the truth value can be + determined. If not, ``None`` is returned. + + Parameters + ========== + + proposition : Any boolean expression. + Proposition which will be evaluated to boolean value. + + assumptions : Any boolean expression, optional. + Local assumptions to evaluate the *proposition*. + + context : AssumptionsContext, optional. + Default assumptions to evaluate the *proposition*. By default, + this is ``sympy.assumptions.global_assumptions`` variable. + + use_known_facts : bool, optional. + If ``True``, facts from ``sympy.assumptions.ask_generated`` + module are passed to SAT solver as well. + + iterations : int, optional. + Number of times that relevant facts are recursively extracted. + Default is infinite times until no new fact is found. + + Returns + ======= + + ``True``, ``False``, or ``None`` + + Examples + ======== + + >>> from sympy import Abs, Q + >>> from sympy.assumptions.satask import satask + >>> from sympy.abc import x + >>> satask(Q.zero(Abs(x)), Q.zero(x)) + True + + """ + props = CNF.from_prop(proposition) + _props = CNF.from_prop(~proposition) + + assumptions = CNF.from_prop(assumptions) + + context_cnf = CNF() + if context: + context_cnf = context_cnf.extend(context) + + sat = get_all_relevant_facts(props, assumptions, context_cnf, + use_known_facts=use_known_facts, iterations=iterations) + sat.add_from_cnf(assumptions) + if context: + sat.add_from_cnf(context_cnf) + + return check_satisfiability(props, _props, sat) + + +def check_satisfiability(prop, _prop, factbase): + sat_true = factbase.copy() + sat_false = factbase.copy() + sat_true.add_from_cnf(prop) + sat_false.add_from_cnf(_prop) + can_be_true = satisfiable(sat_true) + can_be_false = satisfiable(sat_false) + + if can_be_true and can_be_false: + return None + + if can_be_true and not can_be_false: + return True + + if not can_be_true and can_be_false: + return False + + if not can_be_true and not can_be_false: + # TODO: Run additional checks to see which combination of the + # assumptions, global_assumptions, and relevant_facts are + # inconsistent. + raise ValueError("Inconsistent assumptions") + + +def extract_predargs(proposition, assumptions=None, context=None): + """ + Extract every expression in the argument of predicates from *proposition*, + *assumptions* and *context*. + + Parameters + ========== + + proposition : sympy.assumptions.cnf.CNF + + assumptions : sympy.assumptions.cnf.CNF, optional. + + context : sympy.assumptions.cnf.CNF, optional. + CNF generated from assumptions context. + + Examples + ======== + + >>> from sympy import Q, Abs + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.satask import extract_predargs + >>> from sympy.abc import x, y + >>> props = CNF.from_prop(Q.zero(Abs(x*y))) + >>> assump = CNF.from_prop(Q.zero(x) & Q.zero(y)) + >>> extract_predargs(props, assump) + {x, y, Abs(x*y)} + + """ + req_keys = find_symbols(proposition) + keys = proposition.all_predicates() + # XXX: We need this since True/False are not Basic + lkeys = set() + if assumptions: + lkeys |= assumptions.all_predicates() + if context: + lkeys |= context.all_predicates() + + lkeys = lkeys - {S.true, S.false} + tmp_keys = None + while tmp_keys != set(): + tmp = set() + for l in lkeys: + syms = find_symbols(l) + if (syms & req_keys) != set(): + tmp |= syms + tmp_keys = tmp - req_keys + req_keys |= tmp_keys + keys |= {l for l in lkeys if find_symbols(l) & req_keys != set()} + + exprs = set() + for key in keys: + if isinstance(key, AppliedPredicate): + exprs |= set(key.arguments) + else: + exprs.add(key) + return exprs + +def find_symbols(pred): + """ + Find every :obj:`~.Symbol` in *pred*. + + Parameters + ========== + + pred : sympy.assumptions.cnf.CNF, or any Expr. + + """ + if isinstance(pred, CNF): + symbols = set() + for a in pred.all_predicates(): + symbols |= find_symbols(a) + return symbols + return pred.atoms(Symbol) + + +def get_relevant_clsfacts(exprs, relevant_facts=None): + """ + Extract relevant facts from the items in *exprs*. Facts are defined in + ``assumptions.sathandlers`` module. + + This function is recursively called by ``get_all_relevant_facts()``. + + Parameters + ========== + + exprs : set + Expressions whose relevant facts are searched. + + relevant_facts : sympy.assumptions.cnf.CNF, optional. + Pre-discovered relevant facts. + + Returns + ======= + + exprs : set + Candidates for next relevant fact searching. + + relevant_facts : sympy.assumptions.cnf.CNF + Updated relevant facts. + + Examples + ======== + + Here, we will see how facts relevant to ``Abs(x*y)`` are recursively + extracted. On the first run, set containing the expression is passed + without pre-discovered relevant facts. The result is a set containing + candidates for next run, and ``CNF()`` instance containing facts + which are relevant to ``Abs`` and its argument. + + >>> from sympy import Abs + >>> from sympy.assumptions.satask import get_relevant_clsfacts + >>> from sympy.abc import x, y + >>> exprs = {Abs(x*y)} + >>> exprs, facts = get_relevant_clsfacts(exprs) + >>> exprs + {x*y} + >>> facts.clauses #doctest: +SKIP + {frozenset({Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}), + frozenset({Literal(Q.zero(Abs(x*y)), False), Literal(Q.zero(x*y), True)}), + frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True)}), + frozenset({Literal(Q.zero(Abs(x*y)), True), Literal(Q.zero(x*y), False)}), + frozenset({Literal(Q.even(Abs(x*y)), False), + Literal(Q.odd(Abs(x*y)), False), + Literal(Q.odd(x*y), True)}), + frozenset({Literal(Q.even(Abs(x*y)), False), + Literal(Q.even(x*y), True), + Literal(Q.odd(Abs(x*y)), False)}), + frozenset({Literal(Q.positive(Abs(x*y)), False), + Literal(Q.zero(Abs(x*y)), False)})} + + We pass the first run's results to the second run, and get the expressions + for next run and updated facts. + + >>> exprs, facts = get_relevant_clsfacts(exprs, relevant_facts=facts) + >>> exprs + {x, y} + + On final run, no more candidate is returned thus we know that all + relevant facts are successfully retrieved. + + >>> exprs, facts = get_relevant_clsfacts(exprs, relevant_facts=facts) + >>> exprs + set() + + """ + if not relevant_facts: + relevant_facts = CNF() + + newexprs = set() + for expr in exprs: + for fact in class_fact_registry(expr): + newfact = CNF.to_CNF(fact) + relevant_facts = relevant_facts._and(newfact) + for key in newfact.all_predicates(): + if isinstance(key, AppliedPredicate): + newexprs |= set(key.arguments) + + return newexprs - exprs, relevant_facts + + +def get_all_relevant_facts(proposition, assumptions, context, + use_known_facts=True, iterations=oo): + """ + Extract all relevant facts from *proposition* and *assumptions*. + + This function extracts the facts by recursively calling + ``get_relevant_clsfacts()``. Extracted facts are converted to + ``EncodedCNF`` and returned. + + Parameters + ========== + + proposition : sympy.assumptions.cnf.CNF + CNF generated from proposition expression. + + assumptions : sympy.assumptions.cnf.CNF + CNF generated from assumption expression. + + context : sympy.assumptions.cnf.CNF + CNF generated from assumptions context. + + use_known_facts : bool, optional. + If ``True``, facts from ``sympy.assumptions.ask_generated`` + module are encoded as well. + + iterations : int, optional. + Number of times that relevant facts are recursively extracted. + Default is infinite times until no new fact is found. + + Returns + ======= + + sympy.assumptions.cnf.EncodedCNF + + Examples + ======== + + >>> from sympy import Q + >>> from sympy.assumptions.cnf import CNF + >>> from sympy.assumptions.satask import get_all_relevant_facts + >>> from sympy.abc import x, y + >>> props = CNF.from_prop(Q.nonzero(x*y)) + >>> assump = CNF.from_prop(Q.nonzero(x)) + >>> context = CNF.from_prop(Q.nonzero(y)) + >>> get_all_relevant_facts(props, assump, context) #doctest: +SKIP + + + """ + # The relevant facts might introduce new keys, e.g., Q.zero(x*y) will + # introduce the keys Q.zero(x) and Q.zero(y), so we need to run it until + # we stop getting new things. Hopefully this strategy won't lead to an + # infinite loop in the future. + i = 0 + relevant_facts = CNF() + all_exprs = set() + while True: + if i == 0: + exprs = extract_predargs(proposition, assumptions, context) + all_exprs |= exprs + exprs, relevant_facts = get_relevant_clsfacts(exprs, relevant_facts) + i += 1 + if i >= iterations: + break + if not exprs: + break + + if use_known_facts: + known_facts_CNF = CNF() + + if any(expr.kind == MatrixKind(NumberKind) for expr in all_exprs): + known_facts_CNF.add_clauses(get_all_known_matrix_facts()) + # check for undefinedKind since kind system isn't fully implemented + if any(((expr.kind == NumberKind) or (expr.kind == UndefinedKind)) for expr in all_exprs): + known_facts_CNF.add_clauses(get_all_known_number_facts()) + + kf_encoded = EncodedCNF() + kf_encoded.from_cnf(known_facts_CNF) + + def translate_literal(lit, delta): + if lit > 0: + return lit + delta + else: + return lit - delta + + def translate_data(data, delta): + return [{translate_literal(i, delta) for i in clause} for clause in data] + data = [] + symbols = [] + n_lit = len(kf_encoded.symbols) + for i, expr in enumerate(all_exprs): + symbols += [pred(expr) for pred in kf_encoded.symbols] + data += translate_data(kf_encoded.data, i * n_lit) + + encoding = dict(list(zip(symbols, range(1, len(symbols)+1)))) + ctx = EncodedCNF(data, encoding) + else: + ctx = EncodedCNF() + + ctx.add_from_cnf(relevant_facts) + + return ctx diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/__init__.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ff53328e73d3a58ebfe259eeff08fefa043796 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_context.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d9817abc9b7b3d95caa56be087e5ba2e3b734f6 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_context.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_matrices.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..249ef01213206993327a7c225948d866fc37eadf Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_matrices.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a2ef05d60cb20e8a329b835ca8e352e8f7aeefe Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_query.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_refine.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_refine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55b73fd8e6cf8e516afdc3c8ffc7e79168006fa6 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_refine.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec41d263f15c068c0955385d5f2a3ee47043a2d8 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_satask.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_satask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bca7673e932aa8f2088fc5e2acb6b74ef84566c1 Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_satask.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..697bb77ded728c6ccda1f04c28f29c035f74eeba Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_wrapper.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb5e53d4bee830d25c1e48fe7674ca4426515c5b Binary files /dev/null and b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/__pycache__/test_wrapper.cpython-310.pyc differ diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_matrices.py b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfa990f080eebe4d6dd5bfdd733ce1a19adf329 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_matrices.py @@ -0,0 +1,283 @@ +from sympy.assumptions.ask import (Q, ask) +from sympy.core.symbol import Symbol +from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix) +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions import (MatrixSymbol, Identity, ZeroMatrix, + OneMatrix, Trace, MatrixSlice, Determinant, BlockMatrix, BlockDiagMatrix) +from sympy.matrices.expressions.factorizations import LofLU +from sympy.testing.pytest import XFAIL + +X = MatrixSymbol('X', 2, 2) +Y = MatrixSymbol('Y', 2, 3) +Z = MatrixSymbol('Z', 2, 2) +A1x1 = MatrixSymbol('A1x1', 1, 1) +B1x1 = MatrixSymbol('B1x1', 1, 1) +C0x0 = MatrixSymbol('C0x0', 0, 0) +V1 = MatrixSymbol('V1', 2, 1) +V2 = MatrixSymbol('V2', 2, 1) + +def test_square(): + assert ask(Q.square(X)) + assert not ask(Q.square(Y)) + assert ask(Q.square(Y*Y.T)) + +def test_invertible(): + assert ask(Q.invertible(X), Q.invertible(X)) + assert ask(Q.invertible(Y)) is False + assert ask(Q.invertible(X*Y), Q.invertible(X)) is False + assert ask(Q.invertible(X*Z), Q.invertible(X)) is None + assert ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) is True + assert ask(Q.invertible(X.T)) is None + assert ask(Q.invertible(X.T), Q.invertible(X)) is True + assert ask(Q.invertible(X.I)) is True + assert ask(Q.invertible(Identity(3))) is True + assert ask(Q.invertible(ZeroMatrix(3, 3))) is False + assert ask(Q.invertible(OneMatrix(1, 1))) is True + assert ask(Q.invertible(OneMatrix(3, 3))) is False + assert ask(Q.invertible(X), Q.fullrank(X) & Q.square(X)) + +def test_singular(): + assert ask(Q.singular(X)) is None + assert ask(Q.singular(X), Q.invertible(X)) is False + assert ask(Q.singular(X), ~Q.invertible(X)) is True + +@XFAIL +def test_invertible_fullrank(): + assert ask(Q.invertible(X), Q.fullrank(X)) is True + + +def test_invertible_BlockMatrix(): + assert ask(Q.invertible(BlockMatrix([Identity(3)]))) == True + assert ask(Q.invertible(BlockMatrix([ZeroMatrix(3, 3)]))) == False + + X = Matrix([[1, 2, 3], [3, 5, 4]]) + Y = Matrix([[4, 2, 7], [2, 3, 5]]) + # non-invertible A block + assert ask(Q.invertible(BlockMatrix([ + [Matrix.ones(3, 3), Y.T], + [X, Matrix.eye(2)], + ]))) == True + # non-invertible B block + assert ask(Q.invertible(BlockMatrix([ + [Y.T, Matrix.ones(3, 3)], + [Matrix.eye(2), X], + ]))) == True + # non-invertible C block + assert ask(Q.invertible(BlockMatrix([ + [X, Matrix.eye(2)], + [Matrix.ones(3, 3), Y.T], + ]))) == True + # non-invertible D block + assert ask(Q.invertible(BlockMatrix([ + [Matrix.eye(2), X], + [Y.T, Matrix.ones(3, 3)], + ]))) == True + + +def test_invertible_BlockDiagMatrix(): + assert ask(Q.invertible(BlockDiagMatrix(Identity(3), Identity(5)))) == True + assert ask(Q.invertible(BlockDiagMatrix(ZeroMatrix(3, 3), Identity(5)))) == False + assert ask(Q.invertible(BlockDiagMatrix(Identity(3), OneMatrix(5, 5)))) == False + + +def test_symmetric(): + assert ask(Q.symmetric(X), Q.symmetric(X)) + assert ask(Q.symmetric(X*Z), Q.symmetric(X)) is None + assert ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) is True + assert ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) is True + assert ask(Q.symmetric(Y)) is False + assert ask(Q.symmetric(Y*Y.T)) is True + assert ask(Q.symmetric(Y.T*X*Y)) is None + assert ask(Q.symmetric(Y.T*X*Y), Q.symmetric(X)) is True + assert ask(Q.symmetric(X**10), Q.symmetric(X)) is True + assert ask(Q.symmetric(A1x1)) is True + assert ask(Q.symmetric(A1x1 + B1x1)) is True + assert ask(Q.symmetric(A1x1 * B1x1)) is True + assert ask(Q.symmetric(V1.T*V1)) is True + assert ask(Q.symmetric(V1.T*(V1 + V2))) is True + assert ask(Q.symmetric(V1.T*(V1 + V2) + A1x1)) is True + assert ask(Q.symmetric(MatrixSlice(Y, (0, 1), (1, 2)))) is True + assert ask(Q.symmetric(Identity(3))) is True + assert ask(Q.symmetric(ZeroMatrix(3, 3))) is True + assert ask(Q.symmetric(OneMatrix(3, 3))) is True + +def _test_orthogonal_unitary(predicate): + assert ask(predicate(X), predicate(X)) + assert ask(predicate(X.T), predicate(X)) is True + assert ask(predicate(X.I), predicate(X)) is True + assert ask(predicate(X**2), predicate(X)) + assert ask(predicate(Y)) is False + assert ask(predicate(X)) is None + assert ask(predicate(X), ~Q.invertible(X)) is False + assert ask(predicate(X*Z*X), predicate(X) & predicate(Z)) is True + assert ask(predicate(Identity(3))) is True + assert ask(predicate(ZeroMatrix(3, 3))) is False + assert ask(Q.invertible(X), predicate(X)) + assert not ask(predicate(X + Z), predicate(X) & predicate(Z)) + +def test_orthogonal(): + _test_orthogonal_unitary(Q.orthogonal) + +def test_unitary(): + _test_orthogonal_unitary(Q.unitary) + assert ask(Q.unitary(X), Q.orthogonal(X)) + +def test_fullrank(): + assert ask(Q.fullrank(X), Q.fullrank(X)) + assert ask(Q.fullrank(X**2), Q.fullrank(X)) + assert ask(Q.fullrank(X.T), Q.fullrank(X)) is True + assert ask(Q.fullrank(X)) is None + assert ask(Q.fullrank(Y)) is None + assert ask(Q.fullrank(X*Z), Q.fullrank(X) & Q.fullrank(Z)) is True + assert ask(Q.fullrank(Identity(3))) is True + assert ask(Q.fullrank(ZeroMatrix(3, 3))) is False + assert ask(Q.fullrank(OneMatrix(1, 1))) is True + assert ask(Q.fullrank(OneMatrix(3, 3))) is False + assert ask(Q.invertible(X), ~Q.fullrank(X)) == False + + +def test_positive_definite(): + assert ask(Q.positive_definite(X), Q.positive_definite(X)) + assert ask(Q.positive_definite(X.T), Q.positive_definite(X)) is True + assert ask(Q.positive_definite(X.I), Q.positive_definite(X)) is True + assert ask(Q.positive_definite(Y)) is False + assert ask(Q.positive_definite(X)) is None + assert ask(Q.positive_definite(X**3), Q.positive_definite(X)) + assert ask(Q.positive_definite(X*Z*X), + Q.positive_definite(X) & Q.positive_definite(Z)) is True + assert ask(Q.positive_definite(X), Q.orthogonal(X)) + assert ask(Q.positive_definite(Y.T*X*Y), + Q.positive_definite(X) & Q.fullrank(Y)) is True + assert not ask(Q.positive_definite(Y.T*X*Y), Q.positive_definite(X)) + assert ask(Q.positive_definite(Identity(3))) is True + assert ask(Q.positive_definite(ZeroMatrix(3, 3))) is False + assert ask(Q.positive_definite(OneMatrix(1, 1))) is True + assert ask(Q.positive_definite(OneMatrix(3, 3))) is False + assert ask(Q.positive_definite(X + Z), Q.positive_definite(X) & + Q.positive_definite(Z)) is True + assert not ask(Q.positive_definite(-X), Q.positive_definite(X)) + assert ask(Q.positive(X[1, 1]), Q.positive_definite(X)) + +def test_triangular(): + assert ask(Q.upper_triangular(X + Z.T + Identity(2)), Q.upper_triangular(X) & + Q.lower_triangular(Z)) is True + assert ask(Q.upper_triangular(X*Z.T), Q.upper_triangular(X) & + Q.lower_triangular(Z)) is True + assert ask(Q.lower_triangular(Identity(3))) is True + assert ask(Q.lower_triangular(ZeroMatrix(3, 3))) is True + assert ask(Q.upper_triangular(ZeroMatrix(3, 3))) is True + assert ask(Q.lower_triangular(OneMatrix(1, 1))) is True + assert ask(Q.upper_triangular(OneMatrix(1, 1))) is True + assert ask(Q.lower_triangular(OneMatrix(3, 3))) is False + assert ask(Q.upper_triangular(OneMatrix(3, 3))) is False + assert ask(Q.triangular(X), Q.unit_triangular(X)) + assert ask(Q.upper_triangular(X**3), Q.upper_triangular(X)) + assert ask(Q.lower_triangular(X**3), Q.lower_triangular(X)) + + +def test_diagonal(): + assert ask(Q.diagonal(X + Z.T + Identity(2)), Q.diagonal(X) & + Q.diagonal(Z)) is True + assert ask(Q.diagonal(ZeroMatrix(3, 3))) + assert ask(Q.diagonal(OneMatrix(1, 1))) is True + assert ask(Q.diagonal(OneMatrix(3, 3))) is False + assert ask(Q.lower_triangular(X) & Q.upper_triangular(X), Q.diagonal(X)) + assert ask(Q.diagonal(X), Q.lower_triangular(X) & Q.upper_triangular(X)) + assert ask(Q.symmetric(X), Q.diagonal(X)) + assert ask(Q.triangular(X), Q.diagonal(X)) + assert ask(Q.diagonal(C0x0)) + assert ask(Q.diagonal(A1x1)) + assert ask(Q.diagonal(A1x1 + B1x1)) + assert ask(Q.diagonal(A1x1*B1x1)) + assert ask(Q.diagonal(V1.T*V2)) + assert ask(Q.diagonal(V1.T*(X + Z)*V1)) + assert ask(Q.diagonal(MatrixSlice(Y, (0, 1), (1, 2)))) is True + assert ask(Q.diagonal(V1.T*(V1 + V2))) is True + assert ask(Q.diagonal(X**3), Q.diagonal(X)) + assert ask(Q.diagonal(Identity(3))) + assert ask(Q.diagonal(DiagMatrix(V1))) + assert ask(Q.diagonal(DiagonalMatrix(X))) + + +def test_non_atoms(): + assert ask(Q.real(Trace(X)), Q.positive(Trace(X))) + +@XFAIL +def test_non_trivial_implies(): + X = MatrixSymbol('X', 3, 3) + Y = MatrixSymbol('Y', 3, 3) + assert ask(Q.lower_triangular(X+Y), Q.lower_triangular(X) & + Q.lower_triangular(Y)) is True + assert ask(Q.triangular(X), Q.lower_triangular(X)) is True + assert ask(Q.triangular(X+Y), Q.lower_triangular(X) & + Q.lower_triangular(Y)) is True + +def test_MatrixSlice(): + X = MatrixSymbol('X', 4, 4) + B = MatrixSlice(X, (1, 3), (1, 3)) + C = MatrixSlice(X, (0, 3), (1, 3)) + assert ask(Q.symmetric(B), Q.symmetric(X)) + assert ask(Q.invertible(B), Q.invertible(X)) + assert ask(Q.diagonal(B), Q.diagonal(X)) + assert ask(Q.orthogonal(B), Q.orthogonal(X)) + assert ask(Q.upper_triangular(B), Q.upper_triangular(X)) + + assert not ask(Q.symmetric(C), Q.symmetric(X)) + assert not ask(Q.invertible(C), Q.invertible(X)) + assert not ask(Q.diagonal(C), Q.diagonal(X)) + assert not ask(Q.orthogonal(C), Q.orthogonal(X)) + assert not ask(Q.upper_triangular(C), Q.upper_triangular(X)) + +def test_det_trace_positive(): + X = MatrixSymbol('X', 4, 4) + assert ask(Q.positive(Trace(X)), Q.positive_definite(X)) + assert ask(Q.positive(Determinant(X)), Q.positive_definite(X)) + +def test_field_assumptions(): + X = MatrixSymbol('X', 4, 4) + Y = MatrixSymbol('Y', 4, 4) + assert ask(Q.real_elements(X), Q.real_elements(X)) + assert not ask(Q.integer_elements(X), Q.real_elements(X)) + assert ask(Q.complex_elements(X), Q.real_elements(X)) + assert ask(Q.complex_elements(X**2), Q.real_elements(X)) + assert ask(Q.real_elements(X**2), Q.integer_elements(X)) + assert ask(Q.real_elements(X+Y), Q.real_elements(X)) is None + assert ask(Q.real_elements(X+Y), Q.real_elements(X) & Q.real_elements(Y)) + from sympy.matrices.expressions.hadamard import HadamardProduct + assert ask(Q.real_elements(HadamardProduct(X, Y)), + Q.real_elements(X) & Q.real_elements(Y)) + assert ask(Q.complex_elements(X+Y), Q.real_elements(X) & Q.complex_elements(Y)) + + assert ask(Q.real_elements(X.T), Q.real_elements(X)) + assert ask(Q.real_elements(X.I), Q.real_elements(X) & Q.invertible(X)) + assert ask(Q.real_elements(Trace(X)), Q.real_elements(X)) + assert ask(Q.integer_elements(Determinant(X)), Q.integer_elements(X)) + assert not ask(Q.integer_elements(X.I), Q.integer_elements(X)) + alpha = Symbol('alpha') + assert ask(Q.real_elements(alpha*X), Q.real_elements(X) & Q.real(alpha)) + assert ask(Q.real_elements(LofLU(X)), Q.real_elements(X)) + e = Symbol('e', integer=True, negative=True) + assert ask(Q.real_elements(X**e), Q.real_elements(X) & Q.invertible(X)) + assert ask(Q.real_elements(X**e), Q.real_elements(X)) is None + +def test_matrix_element_sets(): + X = MatrixSymbol('X', 4, 4) + assert ask(Q.real(X[1, 2]), Q.real_elements(X)) + assert ask(Q.integer(X[1, 2]), Q.integer_elements(X)) + assert ask(Q.complex(X[1, 2]), Q.complex_elements(X)) + assert ask(Q.integer_elements(Identity(3))) + assert ask(Q.integer_elements(ZeroMatrix(3, 3))) + assert ask(Q.integer_elements(OneMatrix(3, 3))) + from sympy.matrices.expressions.fourier import DFT + assert ask(Q.complex_elements(DFT(3))) + + +def test_matrix_element_sets_slices_blocks(): + X = MatrixSymbol('X', 4, 4) + assert ask(Q.integer_elements(X[:, 3]), Q.integer_elements(X)) + assert ask(Q.integer_elements(BlockMatrix([[X], [X]])), + Q.integer_elements(X)) + +def test_matrix_element_sets_determinant_trace(): + assert ask(Q.integer(Determinant(X)), Q.integer_elements(X)) + assert ask(Q.integer(Trace(X)), Q.integer_elements(X)) diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_refine.py b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..81533a88b232cd5c3cfb9be17d09dad404d679dc --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_refine.py @@ -0,0 +1,227 @@ +from sympy.assumptions.ask import Q +from sympy.assumptions.refine import refine +from sympy.core.expr import Expr +from sympy.core.numbers import (I, Rational, nan, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (atan, atan2) +from sympy.abc import w, x, y, z +from sympy.core.relational import Eq, Ne +from sympy.functions.elementary.piecewise import Piecewise +from sympy.matrices.expressions.matexpr import MatrixSymbol + + +def test_Abs(): + assert refine(Abs(x), Q.positive(x)) == x + assert refine(1 + Abs(x), Q.positive(x)) == 1 + x + assert refine(Abs(x), Q.negative(x)) == -x + assert refine(1 + Abs(x), Q.negative(x)) == 1 - x + + assert refine(Abs(x**2)) != x**2 + assert refine(Abs(x**2), Q.real(x)) == x**2 + + +def test_pow1(): + assert refine((-1)**x, Q.even(x)) == 1 + assert refine((-1)**x, Q.odd(x)) == -1 + assert refine((-2)**x, Q.even(x)) == 2**x + + # nested powers + assert refine(sqrt(x**2)) != Abs(x) + assert refine(sqrt(x**2), Q.complex(x)) != Abs(x) + assert refine(sqrt(x**2), Q.real(x)) == Abs(x) + assert refine(sqrt(x**2), Q.positive(x)) == x + assert refine((x**3)**Rational(1, 3)) != x + + assert refine((x**3)**Rational(1, 3), Q.real(x)) != x + assert refine((x**3)**Rational(1, 3), Q.positive(x)) == x + + assert refine(sqrt(1/x), Q.real(x)) != 1/sqrt(x) + assert refine(sqrt(1/x), Q.positive(x)) == 1/sqrt(x) + + # powers of (-1) + assert refine((-1)**(x + y), Q.even(x)) == (-1)**y + assert refine((-1)**(x + y + z), Q.odd(x) & Q.odd(z)) == (-1)**y + assert refine((-1)**(x + y + 1), Q.odd(x)) == (-1)**y + assert refine((-1)**(x + y + 2), Q.odd(x)) == (-1)**(y + 1) + assert refine((-1)**(x + 3)) == (-1)**(x + 1) + + # continuation + assert refine((-1)**((-1)**x/2 - S.Half), Q.integer(x)) == (-1)**x + assert refine((-1)**((-1)**x/2 + S.Half), Q.integer(x)) == (-1)**(x + 1) + assert refine((-1)**((-1)**x/2 + 5*S.Half), Q.integer(x)) == (-1)**(x + 1) + + +def test_pow2(): + assert refine((-1)**((-1)**x/2 - 7*S.Half), Q.integer(x)) == (-1)**(x + 1) + assert refine((-1)**((-1)**x/2 - 9*S.Half), Q.integer(x)) == (-1)**x + + # powers of Abs + assert refine(Abs(x)**2, Q.real(x)) == x**2 + assert refine(Abs(x)**3, Q.real(x)) == Abs(x)**3 + assert refine(Abs(x)**2) == Abs(x)**2 + + +def test_exp(): + x = Symbol('x', integer=True) + assert refine(exp(pi*I*2*x)) == 1 + assert refine(exp(pi*I*2*(x + S.Half))) == -1 + assert refine(exp(pi*I*2*(x + Rational(1, 4)))) == I + assert refine(exp(pi*I*2*(x + Rational(3, 4)))) == -I + + +def test_Piecewise(): + assert refine(Piecewise((1, x < 0), (3, True)), (x < 0)) == 1 + assert refine(Piecewise((1, x < 0), (3, True)), ~(x < 0)) == 3 + assert refine(Piecewise((1, x < 0), (3, True)), (y < 0)) == \ + Piecewise((1, x < 0), (3, True)) + assert refine(Piecewise((1, x > 0), (3, True)), (x > 0)) == 1 + assert refine(Piecewise((1, x > 0), (3, True)), ~(x > 0)) == 3 + assert refine(Piecewise((1, x > 0), (3, True)), (y > 0)) == \ + Piecewise((1, x > 0), (3, True)) + assert refine(Piecewise((1, x <= 0), (3, True)), (x <= 0)) == 1 + assert refine(Piecewise((1, x <= 0), (3, True)), ~(x <= 0)) == 3 + assert refine(Piecewise((1, x <= 0), (3, True)), (y <= 0)) == \ + Piecewise((1, x <= 0), (3, True)) + assert refine(Piecewise((1, x >= 0), (3, True)), (x >= 0)) == 1 + assert refine(Piecewise((1, x >= 0), (3, True)), ~(x >= 0)) == 3 + assert refine(Piecewise((1, x >= 0), (3, True)), (y >= 0)) == \ + Piecewise((1, x >= 0), (3, True)) + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(x, 0)))\ + == 1 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(0, x)))\ + == 1 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(x, 0)))\ + == 3 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(0, x)))\ + == 3 + assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(y, 0)))\ + == Piecewise((1, Eq(x, 0)), (3, True)) + assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(x, 0)))\ + == 1 + assert refine(Piecewise((1, Ne(x, 0)), (3, True)), ~(Ne(x, 0)))\ + == 3 + assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(y, 0)))\ + == Piecewise((1, Ne(x, 0)), (3, True)) + + +def test_atan2(): + assert refine(atan2(y, x), Q.real(y) & Q.positive(x)) == atan(y/x) + assert refine(atan2(y, x), Q.negative(y) & Q.positive(x)) == atan(y/x) + assert refine(atan2(y, x), Q.negative(y) & Q.negative(x)) == atan(y/x) - pi + assert refine(atan2(y, x), Q.positive(y) & Q.negative(x)) == atan(y/x) + pi + assert refine(atan2(y, x), Q.zero(y) & Q.negative(x)) == pi + assert refine(atan2(y, x), Q.positive(y) & Q.zero(x)) == pi/2 + assert refine(atan2(y, x), Q.negative(y) & Q.zero(x)) == -pi/2 + assert refine(atan2(y, x), Q.zero(y) & Q.zero(x)) is nan + + +def test_re(): + assert refine(re(x), Q.real(x)) == x + assert refine(re(x), Q.imaginary(x)) is S.Zero + assert refine(re(x+y), Q.real(x) & Q.real(y)) == x + y + assert refine(re(x+y), Q.real(x) & Q.imaginary(y)) == x + assert refine(re(x*y), Q.real(x) & Q.real(y)) == x * y + assert refine(re(x*y), Q.real(x) & Q.imaginary(y)) == 0 + assert refine(re(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) == x * y * z + + +def test_im(): + assert refine(im(x), Q.imaginary(x)) == -I*x + assert refine(im(x), Q.real(x)) is S.Zero + assert refine(im(x+y), Q.imaginary(x) & Q.imaginary(y)) == -I*x - I*y + assert refine(im(x+y), Q.real(x) & Q.imaginary(y)) == -I*y + assert refine(im(x*y), Q.imaginary(x) & Q.real(y)) == -I*x*y + assert refine(im(x*y), Q.imaginary(x) & Q.imaginary(y)) == 0 + assert refine(im(1/x), Q.imaginary(x)) == -I/x + assert refine(im(x*y*z), Q.imaginary(x) & Q.imaginary(y) + & Q.imaginary(z)) == -I*x*y*z + + +def test_complex(): + assert refine(re(1/(x + I*y)), Q.real(x) & Q.real(y)) == \ + x/(x**2 + y**2) + assert refine(im(1/(x + I*y)), Q.real(x) & Q.real(y)) == \ + -y/(x**2 + y**2) + assert refine(re((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y) + & Q.real(z)) == w*y - x*z + assert refine(im((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y) + & Q.real(z)) == w*z + x*y + + +def test_sign(): + x = Symbol('x', real = True) + assert refine(sign(x), Q.positive(x)) == 1 + assert refine(sign(x), Q.negative(x)) == -1 + assert refine(sign(x), Q.zero(x)) == 0 + assert refine(sign(x), True) == sign(x) + assert refine(sign(Abs(x)), Q.nonzero(x)) == 1 + + x = Symbol('x', imaginary=True) + assert refine(sign(x), Q.positive(im(x))) == S.ImaginaryUnit + assert refine(sign(x), Q.negative(im(x))) == -S.ImaginaryUnit + assert refine(sign(x), True) == sign(x) + + x = Symbol('x', complex=True) + assert refine(sign(x), Q.zero(x)) == 0 + +def test_arg(): + x = Symbol('x', complex = True) + assert refine(arg(x), Q.positive(x)) == 0 + assert refine(arg(x), Q.negative(x)) == pi + +def test_func_args(): + class MyClass(Expr): + # A class with nontrivial .func + + def __init__(self, *args): + self.my_member = "" + + @property + def func(self): + def my_func(*args): + obj = MyClass(*args) + obj.my_member = self.my_member + return obj + return my_func + + x = MyClass() + x.my_member = "A very important value" + assert x.my_member == refine(x).my_member + +def test_issue_refine_9384(): + assert refine(Piecewise((1, x < 0), (0, True)), Q.positive(x)) == 0 + assert refine(Piecewise((1, x < 0), (0, True)), Q.negative(x)) == 1 + assert refine(Piecewise((1, x > 0), (0, True)), Q.positive(x)) == 1 + assert refine(Piecewise((1, x > 0), (0, True)), Q.negative(x)) == 0 + + +def test_eval_refine(): + class MockExpr(Expr): + def _eval_refine(self, assumptions): + return True + + mock_obj = MockExpr() + assert refine(mock_obj) + +def test_refine_issue_12724(): + expr1 = refine(Abs(x * y), Q.positive(x)) + expr2 = refine(Abs(x * y * z), Q.positive(x)) + assert expr1 == x * Abs(y) + assert expr2 == x * Abs(y * z) + y1 = Symbol('y1', real = True) + expr3 = refine(Abs(x * y1**2 * z), Q.positive(x)) + assert expr3 == x * y1**2 * Abs(z) + + +def test_matrixelement(): + x = MatrixSymbol('x', 3, 3) + i = Symbol('i', positive = True) + j = Symbol('j', positive = True) + assert refine(x[0, 1], Q.symmetric(x)) == x[0, 1] + assert refine(x[1, 0], Q.symmetric(x)) == x[0, 1] + assert refine(x[i, j], Q.symmetric(x)) == x[j, i] + assert refine(x[j, i], Q.symmetric(x)) == x[j, i] diff --git a/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_wrapper.py b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..af9afd5d51fb1341e0b08149dc842b78a39c329b --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/assumptions/tests/test_wrapper.py @@ -0,0 +1,39 @@ +from sympy.assumptions.ask import Q +from sympy.assumptions.wrapper import (AssumptionsWrapper, is_infinite, + is_extended_real) +from sympy.core.symbol import Symbol +from sympy.core.assumptions import _assume_defined + + +def test_all_predicates(): + for fact in _assume_defined: + method_name = f'_eval_is_{fact}' + assert hasattr(AssumptionsWrapper, method_name) + + +def test_AssumptionsWrapper(): + x = Symbol('x', positive=True) + y = Symbol('y') + assert AssumptionsWrapper(x).is_positive + assert AssumptionsWrapper(y).is_positive is None + assert AssumptionsWrapper(y, Q.positive(y)).is_positive + + +def test_is_infinite(): + x = Symbol('x', infinite=True) + y = Symbol('y', infinite=False) + z = Symbol('z') + assert is_infinite(x) + assert not is_infinite(y) + assert is_infinite(z) is None + assert is_infinite(z, Q.infinite(z)) + + +def test_is_extended_real(): + x = Symbol('x', extended_real=True) + y = Symbol('y', extended_real=False) + z = Symbol('z') + assert is_extended_real(x) + assert not is_extended_real(y) + assert is_extended_real(z) is None + assert is_extended_real(z, Q.extended_real(z)) diff --git a/vila/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91b528843d04648555d3b7d6239c7dc3e7477c4f --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aaff90199de1c4ef0eb51991db9c8d0050a9145c9dd5490100dd338af8e6668d +size 152903 diff --git a/vila/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9770773d7c7bed91b36421a7a1cb01d45721ccf --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c9f738170ef803fa11092e6dc8bcd5071314d7eab755c3c46a2e766e4dcb149 +size 114991 diff --git a/vila/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2082f39f52a3a837b03ed4e4091b619bf693857a --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a39a8fc3329384e4df1f0fae9369ab3c6e400a88150848656f5e104aaea7f60d +size 101036 diff --git a/vila/lib/python3.10/site-packages/sympy/core/__pycache__/numbers.cpython-310.pyc b/vila/lib/python3.10/site-packages/sympy/core/__pycache__/numbers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e6192ea955ce1673946d78f63ce88140e2c5743 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/core/__pycache__/numbers.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc82e0d9f254019f1cc8ec1253a8f9e90ebb049a3ba0ea2b801990d7e3617610 +size 118089 diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/cartan_type.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/cartan_type.py new file mode 100644 index 0000000000000000000000000000000000000000..16bb152469238ea912a30c2d0f8210d6f729bdb1 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/cartan_type.py @@ -0,0 +1,73 @@ +from sympy.core import Atom, Basic + + +class CartanType_generator(): + """ + Constructor for actually creating things + """ + def __call__(self, *args): + c = args[0] + if isinstance(c, list): + letter, n = c[0], int(c[1]) + elif isinstance(c, str): + letter, n = c[0], int(c[1:]) + else: + raise TypeError("Argument must be a string (e.g. 'A3') or a list (e.g. ['A', 3])") + + if n < 0: + raise ValueError("Lie algebra rank cannot be negative") + if letter == "A": + from . import type_a + return type_a.TypeA(n) + if letter == "B": + from . import type_b + return type_b.TypeB(n) + + if letter == "C": + from . import type_c + return type_c.TypeC(n) + + if letter == "D": + from . import type_d + return type_d.TypeD(n) + + if letter == "E": + if n >= 6 and n <= 8: + from . import type_e + return type_e.TypeE(n) + + if letter == "F": + if n == 4: + from . import type_f + return type_f.TypeF(n) + + if letter == "G": + if n == 2: + from . import type_g + return type_g.TypeG(n) + +CartanType = CartanType_generator() + + +class Standard_Cartan(Atom): + """ + Concrete base class for Cartan types such as A4, etc + """ + + def __new__(cls, series, n): + obj = Basic.__new__(cls) + obj.n = n + obj.series = series + return obj + + def rank(self): + """ + Returns the rank of the Lie algebra + """ + return self.n + + def series(self): + """ + Returns the type of the Lie algebra + """ + return self.series diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/dynkin_diagram.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/dynkin_diagram.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9e2dac4d54490b803eeaf9637cb9b66b01f058 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/dynkin_diagram.py @@ -0,0 +1,24 @@ +from .cartan_type import CartanType + + +def DynkinDiagram(t): + """Display the Dynkin diagram of a given Lie algebra + + Works by generating the CartanType for the input, t, and then returning the + Dynkin diagram method from the individual classes. + + Examples + ======== + + >>> from sympy.liealgebras.dynkin_diagram import DynkinDiagram + >>> print(DynkinDiagram("A3")) + 0---0---0 + 1 2 3 + + >>> print(DynkinDiagram("B4")) + 0---0---0=>=0 + 1 2 3 4 + + """ + + return CartanType(t).dynkin_diagram() diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/root_system.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/root_system.py new file mode 100644 index 0000000000000000000000000000000000000000..60c516b07c7693a38bb8814f61917bd552cdfd70 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/root_system.py @@ -0,0 +1,199 @@ +from .cartan_type import CartanType +from sympy.core.basic import Atom + +class RootSystem(Atom): + """Represent the root system of a simple Lie algebra + + Every simple Lie algebra has a unique root system. To find the root + system, we first consider the Cartan subalgebra of g, which is the maximal + abelian subalgebra, and consider the adjoint action of g on this + subalgebra. There is a root system associated with this action. Now, a + root system over a vector space V is a set of finite vectors Phi (called + roots), which satisfy: + + 1. The roots span V + 2. The only scalar multiples of x in Phi are x and -x + 3. For every x in Phi, the set Phi is closed under reflection + through the hyperplane perpendicular to x. + 4. If x and y are roots in Phi, then the projection of y onto + the line through x is a half-integral multiple of x. + + Now, there is a subset of Phi, which we will call Delta, such that: + 1. Delta is a basis of V + 2. Each root x in Phi can be written x = sum k_y y for y in Delta + + The elements of Delta are called the simple roots. + Therefore, we see that the simple roots span the root space of a given + simple Lie algebra. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Root_system + .. [2] Lie Algebras and Representation Theory - Humphreys + + """ + + def __new__(cls, cartantype): + """Create a new RootSystem object + + This method assigns an attribute called cartan_type to each instance of + a RootSystem object. When an instance of RootSystem is called, it + needs an argument, which should be an instance of a simple Lie algebra. + We then take the CartanType of this argument and set it as the + cartan_type attribute of the RootSystem instance. + + """ + obj = Atom.__new__(cls) + obj.cartan_type = CartanType(cartantype) + return obj + + def simple_roots(self): + """Generate the simple roots of the Lie algebra + + The rank of the Lie algebra determines the number of simple roots that + it has. This method obtains the rank of the Lie algebra, and then uses + the simple_root method from the Lie algebra classes to generate all the + simple roots. + + Examples + ======== + + >>> from sympy.liealgebras.root_system import RootSystem + >>> c = RootSystem("A3") + >>> roots = c.simple_roots() + >>> roots + {1: [1, -1, 0, 0], 2: [0, 1, -1, 0], 3: [0, 0, 1, -1]} + + """ + n = self.cartan_type.rank() + roots = {} + for i in range(1, n+1): + root = self.cartan_type.simple_root(i) + roots[i] = root + return roots + + + def all_roots(self): + """Generate all the roots of a given root system + + The result is a dictionary where the keys are integer numbers. It + generates the roots by getting the dictionary of all positive roots + from the bases classes, and then taking each root, and multiplying it + by -1 and adding it to the dictionary. In this way all the negative + roots are generated. + + """ + alpha = self.cartan_type.positive_roots() + keys = list(alpha.keys()) + k = max(keys) + for val in keys: + k += 1 + root = alpha[val] + newroot = [-x for x in root] + alpha[k] = newroot + return alpha + + def root_space(self): + """Return the span of the simple roots + + The root space is the vector space spanned by the simple roots, i.e. it + is a vector space with a distinguished basis, the simple roots. This + method returns a string that represents the root space as the span of + the simple roots, alpha[1],...., alpha[n]. + + Examples + ======== + + >>> from sympy.liealgebras.root_system import RootSystem + >>> c = RootSystem("A3") + >>> c.root_space() + 'alpha[1] + alpha[2] + alpha[3]' + + """ + n = self.cartan_type.rank() + rs = " + ".join("alpha["+str(i) +"]" for i in range(1, n+1)) + return rs + + def add_simple_roots(self, root1, root2): + """Add two simple roots together + + The function takes as input two integers, root1 and root2. It then + uses these integers as keys in the dictionary of simple roots, and gets + the corresponding simple roots, and then adds them together. + + Examples + ======== + + >>> from sympy.liealgebras.root_system import RootSystem + >>> c = RootSystem("A3") + >>> newroot = c.add_simple_roots(1, 2) + >>> newroot + [1, 0, -1, 0] + + """ + + alpha = self.simple_roots() + if root1 > len(alpha) or root2 > len(alpha): + raise ValueError("You've used a root that doesn't exist!") + a1 = alpha[root1] + a2 = alpha[root2] + newroot = [_a1 + _a2 for _a1, _a2 in zip(a1, a2)] + return newroot + + def add_as_roots(self, root1, root2): + """Add two roots together if and only if their sum is also a root + + It takes as input two vectors which should be roots. It then computes + their sum and checks if it is in the list of all possible roots. If it + is, it returns the sum. Otherwise it returns a string saying that the + sum is not a root. + + Examples + ======== + + >>> from sympy.liealgebras.root_system import RootSystem + >>> c = RootSystem("A3") + >>> c.add_as_roots([1, 0, -1, 0], [0, 0, 1, -1]) + [1, 0, 0, -1] + >>> c.add_as_roots([1, -1, 0, 0], [0, 0, -1, 1]) + 'The sum of these two roots is not a root' + + """ + alpha = self.all_roots() + newroot = [r1 + r2 for r1, r2 in zip(root1, root2)] + if newroot in alpha.values(): + return newroot + else: + return "The sum of these two roots is not a root" + + + def cartan_matrix(self): + """Cartan matrix of Lie algebra associated with this root system + + Examples + ======== + + >>> from sympy.liealgebras.root_system import RootSystem + >>> c = RootSystem("A3") + >>> c.cartan_matrix() + Matrix([ + [ 2, -1, 0], + [-1, 2, -1], + [ 0, -1, 2]]) + """ + return self.cartan_type.cartan_matrix() + + def dynkin_diagram(self): + """Dynkin diagram of the Lie algebra associated with this root system + + Examples + ======== + + >>> from sympy.liealgebras.root_system import RootSystem + >>> c = RootSystem("A3") + >>> print(c.dynkin_diagram()) + 0---0---0 + 1 2 3 + """ + return self.cartan_type.dynkin_diagram() diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/type_c.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_c.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf4c227fb0cd0d7f3a69e2e4348c67593131dfa --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_c.py @@ -0,0 +1,171 @@ +from .cartan_type import Standard_Cartan +from sympy.core.backend import eye + +class TypeC(Standard_Cartan): + + def __new__(cls, n): + if n < 3: + raise ValueError("n cannot be less than 3") + return Standard_Cartan.__new__(cls, "C", n) + + + def dimension(self): + """Dimension of the vector space V underlying the Lie algebra + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("C3") + >>> c.dimension() + 3 + """ + n = self.n + return n + + def basic_root(self, i, j): + """Generate roots with 1 in ith position and a -1 in jth position + """ + n = self.n + root = [0]*n + root[i] = 1 + root[j] = -1 + return root + + def simple_root(self, i): + """The ith simple root for the C series + + Every lie algebra has a unique root system. + Given a root system Q, there is a subset of the + roots such that an element of Q is called a + simple root if it cannot be written as the sum + of two elements in Q. If we let D denote the + set of simple roots, then it is clear that every + element of Q can be written as a linear combination + of elements of D with all coefficients non-negative. + + In C_n, the first n-1 simple roots are the same as + the roots in A_(n-1) (a 1 in the ith position, a -1 + in the (i+1)th position, and zeroes elsewhere). The + nth simple root is the root in which there is a 2 in + the nth position and zeroes elsewhere. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("C3") + >>> c.simple_root(2) + [0, 1, -1] + + """ + + n = self.n + if i < n: + return self.basic_root(i-1,i) + else: + root = [0]*self.n + root[n-1] = 2 + return root + + + def positive_roots(self): + """Generates all the positive roots of A_n + + This is half of all of the roots of C_n; by multiplying all the + positive roots by -1 we get the negative roots. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("A3") + >>> c.positive_roots() + {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0], + 5: [0, 1, 0, -1], 6: [0, 0, 1, -1]} + + """ + + n = self.n + posroots = {} + k = 0 + for i in range(0, n-1): + for j in range(i+1, n): + k += 1 + posroots[k] = self.basic_root(i, j) + k += 1 + root = self.basic_root(i, j) + root[j] = 1 + posroots[k] = root + + for i in range(0, n): + k += 1 + root = [0]*n + root[i] = 2 + posroots[k] = root + + return posroots + + def roots(self): + """ + Returns the total number of roots for C_n" + """ + + n = self.n + return 2*(n**2) + + def cartan_matrix(self): + """The Cartan matrix for C_n + + The Cartan matrix matrix for a Lie algebra is + generated by assigning an ordering to the simple + roots, (alpha[1], ...., alpha[l]). Then the ijth + entry of the Cartan matrix is (). + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType('C4') + >>> c.cartan_matrix() + Matrix([ + [ 2, -1, 0, 0], + [-1, 2, -1, 0], + [ 0, -1, 2, -1], + [ 0, 0, -2, 2]]) + + """ + + n = self.n + m = 2 * eye(n) + i = 1 + while i < n-1: + m[i, i+1] = -1 + m[i, i-1] = -1 + i += 1 + m[0,1] = -1 + m[n-1, n-2] = -2 + return m + + + def basis(self): + """ + Returns the number of independent generators of C_n + """ + + n = self.n + return n*(2*n + 1) + + def lie_algebra(self): + """ + Returns the Lie algebra associated with C_n" + """ + + n = self.n + return "sp(" + str(2*n) + ")" + + def dynkin_diagram(self): + n = self.n + diag = "---".join("0" for i in range(1, n)) + "=<=0\n" + diag += " ".join(str(i) for i in range(1, n+1)) + return diag diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/type_d.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_d.py new file mode 100644 index 0000000000000000000000000000000000000000..3c46bd79837fce236ffd6922add0eb4743230aa4 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_d.py @@ -0,0 +1,175 @@ +from .cartan_type import Standard_Cartan +from sympy.core.backend import eye + +class TypeD(Standard_Cartan): + + def __new__(cls, n): + if n < 3: + raise ValueError("n cannot be less than 3") + return Standard_Cartan.__new__(cls, "D", n) + + + def dimension(self): + """Dmension of the vector space V underlying the Lie algebra + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("D4") + >>> c.dimension() + 4 + """ + + return self.n + + def basic_root(self, i, j): + """ + This is a method just to generate roots + with a 1 iin the ith position and a -1 + in the jth position. + + """ + + n = self.n + root = [0]*n + root[i] = 1 + root[j] = -1 + return root + + def simple_root(self, i): + """ + Every lie algebra has a unique root system. + Given a root system Q, there is a subset of the + roots such that an element of Q is called a + simple root if it cannot be written as the sum + of two elements in Q. If we let D denote the + set of simple roots, then it is clear that every + element of Q can be written as a linear combination + of elements of D with all coefficients non-negative. + + In D_n, the first n-1 simple roots are the same as + the roots in A_(n-1) (a 1 in the ith position, a -1 + in the (i+1)th position, and zeroes elsewhere). + The nth simple root is the root in which there 1s in + the nth and (n-1)th positions, and zeroes elsewhere. + + This method returns the ith simple root for the D series. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("D4") + >>> c.simple_root(2) + [0, 1, -1, 0] + + """ + + n = self.n + if i < n: + return self.basic_root(i-1, i) + else: + root = [0]*n + root[n-2] = 1 + root[n-1] = 1 + return root + + + def positive_roots(self): + """ + This method generates all the positive roots of + A_n. This is half of all of the roots of D_n + by multiplying all the positive roots by -1 we + get the negative roots. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("A3") + >>> c.positive_roots() + {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0], + 5: [0, 1, 0, -1], 6: [0, 0, 1, -1]} + """ + + n = self.n + posroots = {} + k = 0 + for i in range(0, n-1): + for j in range(i+1, n): + k += 1 + posroots[k] = self.basic_root(i, j) + k += 1 + root = self.basic_root(i, j) + root[j] = 1 + posroots[k] = root + return posroots + + def roots(self): + """ + Returns the total number of roots for D_n" + """ + + n = self.n + return 2*n*(n-1) + + def cartan_matrix(self): + """ + Returns the Cartan matrix for D_n. + The Cartan matrix matrix for a Lie algebra is + generated by assigning an ordering to the simple + roots, (alpha[1], ...., alpha[l]). Then the ijth + entry of the Cartan matrix is (). + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType('D4') + >>> c.cartan_matrix() + Matrix([ + [ 2, -1, 0, 0], + [-1, 2, -1, -1], + [ 0, -1, 2, 0], + [ 0, -1, 0, 2]]) + + """ + + n = self.n + m = 2*eye(n) + i = 1 + while i < n-2: + m[i,i+1] = -1 + m[i,i-1] = -1 + i += 1 + m[n-2, n-3] = -1 + m[n-3, n-1] = -1 + m[n-1, n-3] = -1 + m[0, 1] = -1 + return m + + def basis(self): + """ + Returns the number of independent generators of D_n + """ + n = self.n + return n*(n-1)/2 + + def lie_algebra(self): + """ + Returns the Lie algebra associated with D_n" + """ + + n = self.n + return "so(" + str(2*n) + ")" + + def dynkin_diagram(self): + n = self.n + diag = " "*4*(n-3) + str(n-1) + "\n" + diag += " "*4*(n-3) + "0\n" + diag += " "*4*(n-3) +"|\n" + diag += " "*4*(n-3) + "|\n" + diag += "---".join("0" for i in range(1,n)) + "\n" + diag += " ".join(str(i) for i in range(1, n-1)) + " "+str(n) + return diag diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/type_f.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_f.py new file mode 100644 index 0000000000000000000000000000000000000000..778fcd6d14950c36b63e187b18aeb17c5beb99dd --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_f.py @@ -0,0 +1,162 @@ +from .cartan_type import Standard_Cartan +from sympy.core.backend import Matrix, Rational + + +class TypeF(Standard_Cartan): + + def __new__(cls, n): + if n != 4: + raise ValueError("n should be 4") + return Standard_Cartan.__new__(cls, "F", 4) + + def dimension(self): + """Dimension of the vector space V underlying the Lie algebra + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("F4") + >>> c.dimension() + 4 + """ + + return 4 + + + def basic_root(self, i, j): + """Generate roots with 1 in ith position and -1 in jth position + + """ + + n = self.n + root = [0]*n + root[i] = 1 + root[j] = -1 + return root + + def simple_root(self, i): + """The ith simple root of F_4 + + Every lie algebra has a unique root system. + Given a root system Q, there is a subset of the + roots such that an element of Q is called a + simple root if it cannot be written as the sum + of two elements in Q. If we let D denote the + set of simple roots, then it is clear that every + element of Q can be written as a linear combination + of elements of D with all coefficients non-negative. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("F4") + >>> c.simple_root(3) + [0, 0, 0, 1] + + """ + + if i < 3: + return self.basic_root(i-1, i) + if i == 3: + root = [0]*4 + root[3] = 1 + return root + if i == 4: + root = [Rational(-1, 2)]*4 + return root + + def positive_roots(self): + """Generate all the positive roots of A_n + + This is half of all of the roots of F_4; by multiplying all the + positive roots by -1 we get the negative roots. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("A3") + >>> c.positive_roots() + {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0], + 5: [0, 1, 0, -1], 6: [0, 0, 1, -1]} + + """ + + n = self.n + posroots = {} + k = 0 + for i in range(0, n-1): + for j in range(i+1, n): + k += 1 + posroots[k] = self.basic_root(i, j) + k += 1 + root = self.basic_root(i, j) + root[j] = 1 + posroots[k] = root + + for i in range(0, n): + k += 1 + root = [0]*n + root[i] = 1 + posroots[k] = root + + k += 1 + root = [Rational(1, 2)]*n + posroots[k] = root + for i in range(1, 4): + k += 1 + root = [Rational(1, 2)]*n + root[i] = Rational(-1, 2) + posroots[k] = root + + posroots[k+1] = [Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2)] + posroots[k+2] = [Rational(1, 2), Rational(-1, 2), Rational(1, 2), Rational(-1, 2)] + posroots[k+3] = [Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2)] + posroots[k+4] = [Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(-1, 2)] + + return posroots + + + def roots(self): + """ + Returns the total number of roots for F_4 + """ + return 48 + + def cartan_matrix(self): + """The Cartan matrix for F_4 + + The Cartan matrix matrix for a Lie algebra is + generated by assigning an ordering to the simple + roots, (alpha[1], ...., alpha[l]). Then the ijth + entry of the Cartan matrix is (). + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType('A4') + >>> c.cartan_matrix() + Matrix([ + [ 2, -1, 0, 0], + [-1, 2, -1, 0], + [ 0, -1, 2, -1], + [ 0, 0, -1, 2]]) + """ + + m = Matrix( 4, 4, [2, -1, 0, 0, -1, 2, -2, 0, 0, + -1, 2, -1, 0, 0, -1, 2]) + return m + + def basis(self): + """ + Returns the number of independent generators of F_4 + """ + return 52 + + def dynkin_diagram(self): + diag = "0---0=>=0---0\n" + diag += " ".join(str(i) for i in range(1, 5)) + return diag diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/type_g.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_g.py new file mode 100644 index 0000000000000000000000000000000000000000..014409cf5ed966b53c596b14e0073e89ceee05b6 --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/type_g.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- + +from .cartan_type import Standard_Cartan +from sympy.core.backend import Matrix + +class TypeG(Standard_Cartan): + + def __new__(cls, n): + if n != 2: + raise ValueError("n should be 2") + return Standard_Cartan.__new__(cls, "G", 2) + + + def dimension(self): + """Dimension of the vector space V underlying the Lie algebra + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("G2") + >>> c.dimension() + 3 + """ + return 3 + + def simple_root(self, i): + """The ith simple root of G_2 + + Every lie algebra has a unique root system. + Given a root system Q, there is a subset of the + roots such that an element of Q is called a + simple root if it cannot be written as the sum + of two elements in Q. If we let D denote the + set of simple roots, then it is clear that every + element of Q can be written as a linear combination + of elements of D with all coefficients non-negative. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("G2") + >>> c.simple_root(1) + [0, 1, -1] + + """ + if i == 1: + return [0, 1, -1] + else: + return [1, -2, 1] + + def positive_roots(self): + """Generate all the positive roots of A_n + + This is half of all of the roots of A_n; by multiplying all the + positive roots by -1 we get the negative roots. + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("A3") + >>> c.positive_roots() + {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0], + 5: [0, 1, 0, -1], 6: [0, 0, 1, -1]} + + """ + + roots = {1: [0, 1, -1], 2: [1, -2, 1], 3: [1, -1, 0], 4: [1, 0, 1], + 5: [1, 1, -2], 6: [2, -1, -1]} + return roots + + def roots(self): + """ + Returns the total number of roots of G_2" + """ + return 12 + + def cartan_matrix(self): + """The Cartan matrix for G_2 + + The Cartan matrix matrix for a Lie algebra is + generated by assigning an ordering to the simple + roots, (alpha[1], ...., alpha[l]). Then the ijth + entry of the Cartan matrix is (). + + Examples + ======== + + >>> from sympy.liealgebras.cartan_type import CartanType + >>> c = CartanType("G2") + >>> c.cartan_matrix() + Matrix([ + [ 2, -1], + [-3, 2]]) + + """ + + m = Matrix( 2, 2, [2, -1, -3, 2]) + return m + + def basis(self): + """ + Returns the number of independent generators of G_2 + """ + return 14 + + def dynkin_diagram(self): + diag = "0≡<≡0\n1 2" + return diag diff --git a/vila/lib/python3.10/site-packages/sympy/liealgebras/weyl_group.py b/vila/lib/python3.10/site-packages/sympy/liealgebras/weyl_group.py new file mode 100644 index 0000000000000000000000000000000000000000..15ff70b6f1fc4649268a38ee13e1f717a1c9f5fa --- /dev/null +++ b/vila/lib/python3.10/site-packages/sympy/liealgebras/weyl_group.py @@ -0,0 +1,403 @@ +# -*- coding: utf-8 -*- + +from .cartan_type import CartanType +from mpmath import fac +from sympy.core.backend import Matrix, eye, Rational, igcd +from sympy.core.basic import Atom + +class WeylGroup(Atom): + + """ + For each semisimple Lie group, we have a Weyl group. It is a subgroup of + the isometry group of the root system. Specifically, it's the subgroup + that is generated by reflections through the hyperplanes orthogonal to + the roots. Therefore, Weyl groups are reflection groups, and so a Weyl + group is a finite Coxeter group. + + """ + + def __new__(cls, cartantype): + obj = Atom.__new__(cls) + obj.cartan_type = CartanType(cartantype) + return obj + + def generators(self): + """ + This method creates the generating reflections of the Weyl group for + a given Lie algebra. For a Lie algebra of rank n, there are n + different generating reflections. This function returns them as + a list. + + Examples + ======== + + >>> from sympy.liealgebras.weyl_group import WeylGroup + >>> c = WeylGroup("F4") + >>> c.generators() + ['r1', 'r2', 'r3', 'r4'] + """ + n = self.cartan_type.rank() + generators = [] + for i in range(1, n+1): + reflection = "r"+str(i) + generators.append(reflection) + return generators + + def group_order(self): + """ + This method returns the order of the Weyl group. + For types A, B, C, D, and E the order depends on + the rank of the Lie algebra. For types F and G, + the order is fixed. + + Examples + ======== + + >>> from sympy.liealgebras.weyl_group import WeylGroup + >>> c = WeylGroup("D4") + >>> c.group_order() + 192.0 + """ + n = self.cartan_type.rank() + if self.cartan_type.series == "A": + return fac(n+1) + + if self.cartan_type.series in ("B", "C"): + return fac(n)*(2**n) + + if self.cartan_type.series == "D": + return fac(n)*(2**(n-1)) + + if self.cartan_type.series == "E": + if n == 6: + return 51840 + if n == 7: + return 2903040 + if n == 8: + return 696729600 + if self.cartan_type.series == "F": + return 1152 + + if self.cartan_type.series == "G": + return 12 + + def group_name(self): + """ + This method returns some general information about the Weyl group for + a given Lie algebra. It returns the name of the group and the elements + it acts on, if relevant. + """ + n = self.cartan_type.rank() + if self.cartan_type.series == "A": + return "S"+str(n+1) + ": the symmetric group acting on " + str(n+1) + " elements." + + if self.cartan_type.series in ("B", "C"): + return "The hyperoctahedral group acting on " + str(2*n) + " elements." + + if self.cartan_type.series == "D": + return "The symmetry group of the " + str(n) + "-dimensional demihypercube." + + if self.cartan_type.series == "E": + if n == 6: + return "The symmetry group of the 6-polytope." + + if n == 7: + return "The symmetry group of the 7-polytope." + + if n == 8: + return "The symmetry group of the 8-polytope." + + if self.cartan_type.series == "F": + return "The symmetry group of the 24-cell, or icositetrachoron." + + if self.cartan_type.series == "G": + return "D6, the dihedral group of order 12, and symmetry group of the hexagon." + + def element_order(self, weylelt): + """ + This method returns the order of a given Weyl group element, which should + be specified by the user in the form of products of the generating + reflections, i.e. of the form r1*r2 etc. + + For types A-F, this method current works by taking the matrix form of + the specified element, and then finding what power of the matrix is the + identity. It then returns this power. + + Examples + ======== + + >>> from sympy.liealgebras.weyl_group import WeylGroup + >>> b = WeylGroup("B4") + >>> b.element_order('r1*r4*r2') + 4 + """ + n = self.cartan_type.rank() + if self.cartan_type.series == "A": + a = self.matrix_form(weylelt) + order = 1 + while a != eye(n+1): + a *= self.matrix_form(weylelt) + order += 1 + return order + + if self.cartan_type.series == "D": + a = self.matrix_form(weylelt) + order = 1 + while a != eye(n): + a *= self.matrix_form(weylelt) + order += 1 + return order + + if self.cartan_type.series == "E": + a = self.matrix_form(weylelt) + order = 1 + while a != eye(8): + a *= self.matrix_form(weylelt) + order += 1 + return order + + if self.cartan_type.series == "G": + elts = list(weylelt) + reflections = elts[1::3] + m = self.delete_doubles(reflections) + while self.delete_doubles(m) != m: + m = self.delete_doubles(m) + reflections = m + if len(reflections) % 2 == 1: + return 2 + + elif len(reflections) == 0: + return 1 + + else: + if len(reflections) == 1: + return 2 + else: + m = len(reflections) // 2 + lcm = (6 * m)/ igcd(m, 6) + order = lcm / m + return order + + + if self.cartan_type.series == 'F': + a = self.matrix_form(weylelt) + order = 1 + while a != eye(4): + a *= self.matrix_form(weylelt) + order += 1 + return order + + + if self.cartan_type.series in ("B", "C"): + a = self.matrix_form(weylelt) + order = 1 + while a != eye(n): + a *= self.matrix_form(weylelt) + order += 1 + return order + + def delete_doubles(self, reflections): + """ + This is a helper method for determining the order of an element in the + Weyl group of G2. It takes a Weyl element and if repeated simple reflections + in it, it deletes them. + """ + counter = 0 + copy = list(reflections) + for elt in copy: + if counter < len(copy)-1: + if copy[counter + 1] == elt: + del copy[counter] + del copy[counter] + counter += 1 + + + return copy + + + def matrix_form(self, weylelt): + """ + This method takes input from the user in the form of products of the + generating reflections, and returns the matrix corresponding to the + element of the Weyl group. Since each element of the Weyl group is + a reflection of some type, there is a corresponding matrix representation. + This method uses the standard representation for all the generating + reflections. + + Examples + ======== + + >>> from sympy.liealgebras.weyl_group import WeylGroup + >>> f = WeylGroup("F4") + >>> f.matrix_form('r2*r3') + Matrix([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, -1], + [0, 0, 1, 0]]) + + """ + elts = list(weylelt) + reflections = elts[1::3] + n = self.cartan_type.rank() + if self.cartan_type.series == 'A': + matrixform = eye(n+1) + for elt in reflections: + a = int(elt) + mat = eye(n+1) + mat[a-1, a-1] = 0 + mat[a-1, a] = 1 + mat[a, a-1] = 1 + mat[a, a] = 0 + matrixform *= mat + return matrixform + + if self.cartan_type.series == 'D': + matrixform = eye(n) + for elt in reflections: + a = int(elt) + mat = eye(n) + if a < n: + mat[a-1, a-1] = 0 + mat[a-1, a] = 1 + mat[a, a-1] = 1 + mat[a, a] = 0 + matrixform *= mat + else: + mat[n-2, n-1] = -1 + mat[n-2, n-2] = 0 + mat[n-1, n-2] = -1 + mat[n-1, n-1] = 0 + matrixform *= mat + return matrixform + + if self.cartan_type.series == 'G': + matrixform = eye(3) + for elt in reflections: + a = int(elt) + if a == 1: + gen1 = Matrix([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) + matrixform *= gen1 + else: + gen2 = Matrix([[Rational(2, 3), Rational(2, 3), Rational(-1, 3)], + [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], + [Rational(-1, 3), Rational(2, 3), Rational(2, 3)]]) + matrixform *= gen2 + return matrixform + + if self.cartan_type.series == 'F': + matrixform = eye(4) + for elt in reflections: + a = int(elt) + if a == 1: + mat = Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) + matrixform *= mat + elif a == 2: + mat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) + matrixform *= mat + elif a == 3: + mat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]) + matrixform *= mat + else: + + mat = Matrix([[Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2)], + [Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2)], + [Rational(1, 2), Rational(-1, 2), Rational(1, 2), Rational(-1, 2)], + [Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2)]]) + matrixform *= mat + return matrixform + + if self.cartan_type.series == 'E': + matrixform = eye(8) + for elt in reflections: + a = int(elt) + if a == 1: + mat = Matrix([[Rational(3, 4), Rational(1, 4), Rational(1, 4), Rational(1, 4), + Rational(1, 4), Rational(1, 4), Rational(1, 4), Rational(-1, 4)], + [Rational(1, 4), Rational(3, 4), Rational(-1, 4), Rational(-1, 4), + Rational(-1, 4), Rational(-1, 4), Rational(1, 4), Rational(-1, 4)], + [Rational(1, 4), Rational(-1, 4), Rational(3, 4), Rational(-1, 4), + Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4)], + [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4), + Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4)], + [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), + Rational(3, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4)], + [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), + Rational(-1, 4), Rational(3, 4), Rational(-1, 4), Rational(1, 4)], + [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), + Rational(-1, 4), Rational(-1, 4), Rational(-3, 4), Rational(1, 4)], + [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), + Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4)]]) + matrixform *= mat + elif a == 2: + mat = eye(8) + mat[0, 0] = 0 + mat[0, 1] = -1 + mat[1, 0] = -1 + mat[1, 1] = 0 + matrixform *= mat + else: + mat = eye(8) + mat[a-3, a-3] = 0 + mat[a-3, a-2] = 1 + mat[a-2, a-3] = 1 + mat[a-2, a-2] = 0 + matrixform *= mat + return matrixform + + + if self.cartan_type.series in ("B", "C"): + matrixform = eye(n) + for elt in reflections: + a = int(elt) + mat = eye(n) + if a == 1: + mat[0, 0] = -1 + matrixform *= mat + else: + mat[a - 2, a - 2] = 0 + mat[a-2, a-1] = 1 + mat[a - 1, a - 2] = 1 + mat[a -1, a - 1] = 0 + matrixform *= mat + return matrixform + + + + def coxeter_diagram(self): + """ + This method returns the Coxeter diagram corresponding to a Weyl group. + The Coxeter diagram can be obtained from a Lie algebra's Dynkin diagram + by deleting all arrows; the Coxeter diagram is the undirected graph. + The vertices of the Coxeter diagram represent the generating reflections + of the Weyl group, $s_i$. An edge is drawn between $s_i$ and $s_j$ if the order + $m(i, j)$ of $s_is_j$ is greater than two. If there is one edge, the order + $m(i, j)$ is 3. If there are two edges, the order $m(i, j)$ is 4, and if there + are three edges, the order $m(i, j)$ is 6. + + Examples + ======== + + >>> from sympy.liealgebras.weyl_group import WeylGroup + >>> c = WeylGroup("B3") + >>> print(c.coxeter_diagram()) + 0---0===0 + 1 2 3 + """ + n = self.cartan_type.rank() + if self.cartan_type.series in ("A", "D", "E"): + return self.cartan_type.dynkin_diagram() + + if self.cartan_type.series in ("B", "C"): + diag = "---".join("0" for i in range(1, n)) + "===0\n" + diag += " ".join(str(i) for i in range(1, n+1)) + return diag + + if self.cartan_type.series == "F": + diag = "0---0===0---0\n" + diag += " ".join(str(i) for i in range(1, 5)) + return diag + + if self.cartan_type.series == "G": + diag = "0≡≡≡0\n1 2" + return diag