Esempio n. 1
0
def test_sympify3():
    assert sympify("x**3") == x**3
    assert sympify("x^3") == x**3
    assert sympify("1/2") == Rational(1, 2)

    pytest.raises(SympifyError, lambda: _sympify('x**3'))
    pytest.raises(SympifyError, lambda: _sympify('1/2'))
Esempio n. 2
0
def test_sympify3():
    assert sympify("x**3") == x**3
    assert sympify("x^3") == x**3
    assert sympify("x^3", convert_xor=False) == Xor(x, 3)
    assert sympify("1/2") == Rational(1, 2)

    pytest.raises(SympifyError, lambda: _sympify('x**3'))
    pytest.raises(SympifyError, lambda: _sympify('1/2'))
Esempio n. 3
0
    def __setitem__(self, index, value):
        """Allows to set items to MutableDenseNDimArray.

        Examples
        ========

        >>> from diofant.tensor.array import MutableSparseNDimArray
        >>> a = MutableSparseNDimArray.zeros(2, 2)
        >>> a[0, 0] = 1
        >>> a[1, 1] = 1
        >>> a
        [[1, 0], [0, 1]]


        """
        index = self._parse_index(index)
        if not isinstance(value, MutableNDimArray):
            value = _sympify(value)

        if isinstance(value, NDimArray):
            return NotImplementedError

        if value == 0 and index in self._sparse_array:
            self._sparse_array.pop(index)
        else:
            self._sparse_array[index] = value
Esempio n. 4
0
 def _contains(self, other):
     if (((self.start - other) / self.step).is_integer
             or ((self.stop - other) / self.step).is_integer):
         return _sympify(other >= self.inf and other <= self.sup)
     elif (((self.start - other) / self.step).is_integer is False
           and ((self.stop - other) / self.step).is_integer is False):
         return S.false
Esempio n. 5
0
 def __new__(cls, mat):
     mat = _sympify(mat)
     if not mat.is_Matrix:
         raise TypeError("mat should be a matrix")
     if not mat.is_square:
         raise ShapeError("Inverse of non-square matrix %s" % mat)
     return Basic.__new__(cls, mat)
Esempio n. 6
0
def test_sympify4():
    class A:
        def _diofant_(self):
            return Symbol("x")

    a = A()

    assert _sympify(a)**3 == x**3
    assert sympify(a)**3 == x**3
    assert a == x
Esempio n. 7
0
 def __new__(cls, lhs, rhs=0, **assumptions):
     from diofant.matrices.expressions.matexpr import (
         MatrixElement, MatrixSymbol)
     from diofant.tensor.indexed import Indexed
     lhs = _sympify(lhs)
     rhs = _sympify(rhs)
     # Tuple of things that can be on the lhs of an assignment
     assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed)
     if not isinstance(lhs, assignable):
         raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
     # Indexed types implement shape, but don't define it until later. This
     # causes issues in assignment validation. For now, matrices are defined
     # as anything with a shape that is not an Indexed
     lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
     rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
     # If lhs and rhs have same structure, then this assignment is ok
     if lhs_is_mat:
         if not rhs_is_mat:
             raise ValueError("Cannot assign a scalar to a matrix.")
         elif lhs.shape != rhs.shape:
             raise ValueError("Dimensions of lhs and rhs don't align.")
     elif rhs_is_mat and not lhs_is_mat:
         raise ValueError("Cannot assign a matrix to a scalar.")
     return Relational.__new__(cls, lhs, rhs, **assumptions)
Esempio n. 8
0
def test__sympify():
    x = Symbol('x')
    f = Function('f')

    # positive _sympify
    assert _sympify(x) is x
    assert _sympify(f) is f
    assert _sympify(1) == Integer(1)
    assert _sympify(0.5) == Float("0.5")
    assert _sympify(1 + 1j) == 1.0 + I*1.0

    class A:
        def _diofant_(self):
            return Integer(5)

    a = A()
    assert _sympify(a) == Integer(5)

    # negative _sympify
    pytest.raises(SympifyError, lambda: _sympify('1'))
    pytest.raises(SympifyError, lambda: _sympify([1, 2, 3]))
Esempio n. 9
0
    def __setitem__(self, index, value):
        """Allows to set items to MutableDenseNDimArray.

        Examples
        ========

        >>> from diofant.tensor.array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray.zeros(2,  2)
        >>> a[0,0] = 1
        >>> a[1,1] = 1
        >>> a
        [[1, 0], [0, 1]]

        """
        index = self._parse_index(index)
        self._setter_iterable_check(value)
        value = _sympify(value)

        self._array[index] = value
Esempio n. 10
0
    def __new__(cls, *args, **kwargs):

        shape, flat_list = cls._handle_ndarray_creation_inputs(*args, **kwargs)
        self = object.__new__(cls)
        self._shape = shape
        self._rank = len(shape)
        self._loop_size = functools.reduce(lambda x, y: x * y,
                                           shape) if shape else 0

        # Sparse array:
        if isinstance(flat_list, (dict, Dict)):
            self._sparse_array = dict(flat_list)
            return self

        self._sparse_array = {}

        for i, el in enumerate(flatten(flat_list)):
            if el != 0:
                self._sparse_array[i] = _sympify(el)

        return self
Esempio n. 11
0
    def __new__(cls, *args, **options):
        from diofant.core.relational import Relational
        args = [_sympify(arg) for arg in args]

        argset = set(args)
        for x in args:
            if isinstance(x, Number) or x in [True, False]:  # Includes 0, 1
                argset.discard(x)
                argset.add(True if x else False)
        rel = []
        for r in argset:
            if isinstance(r, Relational):
                rel.append((r, r.canonical, (~r).canonical))
        remove = []
        for i, (r, c, nc) in enumerate(rel):
            for j in range(i + 1, len(rel)):
                rj, cj = rel[j][:2]
                if cj == nc:
                    return false
                elif cj == c:
                    remove.append((r, rj))
                    break
        for a, b in remove:
            argset.remove(a)
            argset.remove(b)
            argset.add(True)
        if len(argset) <= 1:
            return true
        if True in argset:
            argset.discard(True)
            return And(*argset)
        if False in argset:
            argset.discard(False)
            return And(*[~arg for arg in argset])
        _args = frozenset(argset)
        obj = super(Equivalent, cls).__new__(cls, _args)
        obj._argset = _args
        return obj
Esempio n. 12
0
    def __new__(cls, *args, **kwargs):

        shape, flat_list = cls._handle_ndarray_creation_inputs(*args, **kwargs)
        shape = Tuple(*map(_sympify, shape))
        loop_size = functools.reduce(lambda x, y: x * y, shape) if shape else 0

        # Sparse array:
        if isinstance(flat_list, (dict, Dict)):
            sparse_array = Dict(flat_list)
        else:
            sparse_array = {}
            for i, el in enumerate(flatten(flat_list)):
                if el != 0:
                    sparse_array[i] = _sympify(el)

        sparse_array = Dict(sparse_array)

        self = Expr.__new__(cls, sparse_array, shape, **kwargs)
        self._shape = shape
        self._rank = len(shape)
        self._loop_size = loop_size
        self._sparse_array = sparse_array

        return self
Esempio n. 13
0
def test_sympify_poly():
    p = Poly(x**2 + x + 1, x)

    assert _sympify(p) is p
    assert sympify(p) is p
Esempio n. 14
0
def test_Range():
    assert sympify(range(10)) == Range(10)
    assert _sympify(range(10)) == Range(10)
Esempio n. 15
0
 def __new__(cls, base, exp):
     base = _sympify(base)
     if not base.is_Matrix:
         raise TypeError("Function parameter should be a matrix")
     exp = _sympify(exp)
     return super(MatPow, cls).__new__(cls, base, exp)
Esempio n. 16
0
def test_lambda_raises():
    pytest.raises(SympifyError, lambda: sympify("lambda *args: args"))  # args argument error
    pytest.raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]"))  # kwargs argument error
    pytest.raises(SympifyError, lambda: sympify("lambda x = 1: x"))    # Keyword argument error
    with pytest.raises(SympifyError):
        _sympify('lambda: 1')
Esempio n. 17
0
def test_int_float():
    class F1_1(object):
        def __float__(self):
            return 1.1

    class F1_1b(object):
        """
        This class is still a float, even though it also implements __int__().
        """
        def __float__(self):
            return 1.1

        def __int__(self):
            return 1

    class F1_1c(object):
        """
        This class is still a float, because it implements _diofant_()
        """
        def __float__(self):
            return 1.1

        def __int__(self):
            return 1

        def _diofant_(self):
            return Float(1.1)

    class I5(object):
        def __int__(self):
            return 5

    class I5b(object):
        """
        This class implements both __int__() and __float__(), so it will be
        treated as Float in Diofant. One could change this behavior, by using
        float(a) == int(a), but deciding that integer-valued floats represent
        exact numbers is arbitrary and often not correct, so we do not do it.
        If, in the future, we decide to do it anyway, the tests for I5b need to
        be changed.
        """
        def __float__(self):
            return 5.0

        def __int__(self):
            return 5

    class I5c(object):
        """
        This class implements both __int__() and __float__(), but also
        a _diofant_() method, so it will be Integer.
        """
        def __float__(self):
            return 5.0

        def __int__(self):
            return 5

        def _diofant_(self):
            return Integer(5)

    i5 = I5()
    i5b = I5b()
    i5c = I5c()
    f1_1 = F1_1()
    f1_1b = F1_1b()
    f1_1c = F1_1c()
    assert sympify(i5) == 5
    assert isinstance(sympify(i5), Integer)
    assert sympify(i5b) == 5
    assert isinstance(sympify(i5b), Float)
    assert sympify(i5c) == 5
    assert isinstance(sympify(i5c), Integer)
    assert abs(sympify(f1_1) - 1.1) < 1e-5
    assert abs(sympify(f1_1b) - 1.1) < 1e-5
    assert abs(sympify(f1_1c) - 1.1) < 1e-5

    assert _sympify(i5) == 5
    assert isinstance(_sympify(i5), Integer)
    assert _sympify(i5b) == 5
    assert isinstance(_sympify(i5b), Float)
    assert _sympify(i5c) == 5
    assert isinstance(_sympify(i5c), Integer)
    assert abs(_sympify(f1_1) - 1.1) < 1e-5
    assert abs(_sympify(f1_1b) - 1.1) < 1e-5
    assert abs(_sympify(f1_1c) - 1.1) < 1e-5