Пример #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'))
Пример #2
0
def test_sympyify_iterables():
    ans = [Rational(3, 10), Rational(1, 5)]
    assert sympify(['.3', '.2'], rational=True) == ans
    assert sympify({'.3', '.2'}, rational=True) == set(ans)
    assert sympify(('.3', '.2'), rational=True) == Tuple(*ans)
    assert sympify({x: 0, y: 1}) == {x: 0, y: 1}
    assert sympify(['1', '2', ['3', '4']]) == [Integer(1), Integer(2), [Integer(3), Integer(4)]]
Пример #3
0
def test_sympyissue_6540_6552():
    assert sympify('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2],
                                            (Rational(2, 5), )]
    assert sympify('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2],
                                            (Rational(1, 2), )]
    assert sympify('[[[2*(1)]]]') == [[[2]]]
    assert sympify('Matrix([2*(1)])') == Matrix([2])
Пример #4
0
def test_sympyify_iterables():
    ans = [Rational(3, 10), Rational(1, 5)]
    assert sympify(['.3', '.2'], rational=True) == ans
    assert sympify({'.3', '.2'}, rational=True) == set(ans)
    assert sympify(('.3', '.2'), rational=True) == Tuple(*ans)
    assert sympify({x: 0, y: 1}) == {x: 0, y: 1}
    assert sympify(['1', '2', ['3', '4']]) == [Integer(1), Integer(2), [Integer(3), Integer(4)]]
Пример #5
0
def test_sympyissue_6046():
    assert str(sympify("Q & C", locals=_clash1)) == 'And(C, Q)'
    assert str(sympify('pi(x)', locals=_clash2)) == 'pi(x)'
    assert str(sympify('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
    locals = {}
    exec("from diofant.abc import S, O", locals)
    assert str(sympify('O&S', locals)) == 'And(O, S)'
Пример #6
0
def test_sympyissue_6046():
    assert str(sympify("Q & C", locals=_clash1)) == 'And(C, Q)'
    assert str(sympify('pi(x)', locals=_clash2)) == 'pi(x)'
    assert str(sympify('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
    locals = {}
    exec("from diofant.abc import S, O", locals)
    assert str(sympify('O&S', locals)) == 'And(O, S)'
Пример #7
0
 def __getitem__(self, key):
     if not isinstance(key, tuple) and isinstance(key, slice):
         from diofant.matrices.expressions.slice import MatrixSlice
         return MatrixSlice(self, key, (0, None, 1))
     if isinstance(key, tuple) and len(key) == 2:
         i, j = key
         if isinstance(i, slice) or isinstance(j, slice):
             from diofant.matrices.expressions.slice import MatrixSlice
             return MatrixSlice(self, i, j)
         i, j = sympify(i), sympify(j)
         if self.valid_index(i, j) is not False:
             return self._entry(i, j)
         else:
             raise IndexError("Invalid indices (%s, %s)" % (i, j))
     elif isinstance(key, (int, Integer)):
         # row-wise decomposition of matrix
         rows, cols = self.shape
         if not (isinstance(rows, Integer) and isinstance(cols, Integer)):
             raise IndexError("Single index only supported for "
                              "non-symbolic matrix shapes.")
         key = sympify(key)
         i = key // cols
         j = key % cols
         if self.valid_index(i, j) is not False:
             return self._entry(i, j)
         else:
             raise IndexError("Invalid index %s" % key)
     elif isinstance(key, (Symbol, Expr)):
         raise IndexError("Single index only supported for "
                          "non-symbolic indices.")
     raise IndexError("Invalid index, wanted %s[i,j]" % self)
Пример #8
0
def test_sympyissue_10773():
    with evaluate(False):
        ans = Mul(Integer(-10), Pow(Integer(5), Integer(-1)))
    assert sympify('-10/5', evaluate=False) == ans

    with evaluate(False):
        ans = Mul(Integer(-10), Pow(Integer(-5), Integer(-1)))
    assert sympify('-10/-5', evaluate=False) == ans
Пример #9
0
def test_sympyissue_10773():
    with evaluate(False):
        ans = Mul(Integer(-10), Pow(Integer(5), Integer(-1)))
    assert sympify('-10/5', evaluate=False) == ans

    with evaluate(False):
        ans = Mul(Integer(-10), Pow(Integer(-5), Integer(-1)))
    assert sympify('-10/-5', evaluate=False) == ans
Пример #10
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'))
Пример #11
0
def test_sympify_gmpy():
    if HAS_GMPY:
        import gmpy2 as gmpy

        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Пример #12
0
def test_sympyissue_4988_builtins():
    C = Symbol('C')
    vars = {}
    vars['C'] = C
    exp1 = sympify('C')
    assert exp1 == C  # Make sure it did not get mixed up with diofant.C

    exp2 = sympify('C', vars)
    assert exp2 == C  # Make sure it did not get mixed up with diofant.C
Пример #13
0
def test_sympyissue_4988_builtins():
    C = Symbol('C')
    vars = {}
    vars['C'] = C
    exp1 = sympify('C')
    assert exp1 == C  # Make sure it did not get mixed up with diofant.C

    exp2 = sympify('C', vars)
    assert exp2 == C  # Make sure it did not get mixed up with diofant.C
Пример #14
0
def test_sympify_gmpy():
    if HAS_GMPY:
        import gmpy2 as gmpy

        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Пример #15
0
def test_lambda_raises():
    pytest.raises(NotImplementedError,
                  lambda: sympify("lambda *args: args"))  # args argument error
    pytest.raises(
        NotImplementedError,
        lambda: sympify("lambda **kwargs: kwargs"))  # kwargs argument error
    pytest.raises(SympifyError,
                  lambda: sympify("lambda x = 1: x"))  # Keyword argument error
    with pytest.raises(SympifyError):
        sympify('lambda: 1', strict=True)
Пример #16
0
def test_sympify4():
    class A:
        def _diofant_(self):
            return Symbol("x")

    a = A()

    assert sympify(a, strict=True)**3 == x**3
    assert sympify(a)**3 == x**3
    assert a == x
Пример #17
0
def test_sympify5():
    class A:
        def __str__(self):
            raise TypeError

    with pytest.raises(SympifyError) as err:
        sympify(A())
    assert re.match(r"^Sympify of expression '<diofant.core\.tests\.test_sympify"
                    r"\.test_sympify5\.<locals>\.A object at 0x[0-9a-f]+>' failed,"
                    " because of exception being raised:\nTypeError: $", str(err.value))
Пример #18
0
def test_sympify5():
    class A:
        def __str__(self):
            raise TypeError

    with pytest.raises(SympifyError) as err:
        sympify(A())
    assert re.match(r"^Sympify of expression '<diofant\.tests\.core\.test_sympify"
                    r"\.test_sympify5\.<locals>\.A object at 0x[0-9a-f]+>' failed,"
                    " because of exception being raised:\nTypeError: $", str(err.value))
Пример #19
0
def test_sympify4():
    class A:
        def _diofant_(self):
            return Symbol("x")

    a = A()

    assert sympify(a, strict=True)**3 == x**3
    assert sympify(a)**3 == x**3
    assert a == x
Пример #20
0
def wronskian(functions, var, method='bareis'):
    """
    Compute Wronskian for [] of functions

    ::

                         | f1       f2        ...   fn      |
                         | f1'      f2'       ...   fn'     |
                         |  .        .        .      .      |
        W(f1, ..., fn) = |  .        .         .     .      |
                         |  .        .          .    .      |
                         |  (n)      (n)            (n)     |
                         | D   (f1) D   (f2)  ...  D   (fn) |

    see: http://en.wikipedia.org/wiki/Wronskian

    See Also
    ========

    diofant.matrices.matrices.MatrixBase.jacobian
    diofant.matrices.dense.hessian
    """
    from .dense import Matrix

    for index in range(0, len(functions)):
        functions[index] = sympify(functions[index])
    n = len(functions)
    if n == 0:
        return 1
    W = Matrix(n, n, lambda i, j: functions[i].diff(var, j))
    return W.det(method)
Пример #21
0
    def _rebuild_expr(self, expr, mapping):
        domain = self.domain

        def _rebuild(expr):
            generator = mapping.get(expr)

            if generator is not None:
                return generator
            elif expr.is_Add:
                return reduce(add, list(map(_rebuild, expr.args)))
            elif expr.is_Mul:
                return reduce(mul, list(map(_rebuild, expr.args)))
            elif expr.is_Pow:
                c, a = expr.exp.as_coeff_Mul(rational=True)
                if c.is_Integer and c != 1:
                    return _rebuild(expr.base**a)**int(c)

            try:
                return domain.convert(expr)
            except CoercionFailed:
                if not domain.has_Field and domain.has_assoc_Field:
                    return domain.get_field().convert(expr)
                else:
                    raise

        return _rebuild(sympify(expr))
Пример #22
0
def to_dnf(expr, simplify=False):
    """
    Convert a propositional logical sentence s to disjunctive normal form.
    That is, of the form ((A & ~B & ...) | (B & C & ...) | ...)
    If simplify is True, the expr is evaluated to its simplest DNF form.

    Examples
    ========

    >>> from diofant.logic.boolalg import to_dnf
    >>> from diofant.abc import A, B, C
    >>> to_dnf(B & (A | C))
    Or(And(A, B), And(B, C))
    >>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True)
    Or(A, C)

    """
    expr = sympify(expr)
    if not isinstance(expr, BooleanFunction):
        return expr

    if simplify:
        return simplify_logic(expr, 'dnf', True)

    # Don't convert unless we have to
    if is_dnf(expr):
        return expr

    expr = eliminate_implications(expr)
    return distribute_or_over_and(expr)
Пример #23
0
def to_cnf(expr, simplify=False):
    """
    Convert a propositional logical sentence s to conjunctive normal form.
    That is, of the form ((A | ~B | ...) & (B | C | ...) & ...)
    If simplify is True, the expr is evaluated to its simplest CNF form.

    Examples
    ========

    >>> from diofant.logic.boolalg import to_cnf
    >>> from diofant.abc import A, B, D
    >>> to_cnf(~(A | B) | D)
    And(Or(D, Not(A)), Or(D, Not(B)))
    >>> to_cnf((A | B) & (A | ~A), True)
    Or(A, B)

    """
    expr = sympify(expr)
    if not isinstance(expr, BooleanFunction):
        return expr

    if simplify:
        return simplify_logic(expr, 'cnf', True)

    # Don't convert unless we have to
    if is_cnf(expr):
        return expr

    expr = eliminate_implications(expr)
    return distribute_and_over_or(expr)
Пример #24
0
 def __new__(cls, *args, **kwargs):
     from diofant.geometry.point import Point
     args = [
         Tuple(*a)
         if is_sequence(a) and not isinstance(a, Point) else sympify(a)
         for a in args
     ]
     return Basic.__new__(cls, *args)
Пример #25
0
def test_sympify_Fraction():
    try:
        import fractions
    except ImportError:
        pass
    else:
        value = sympify(fractions.Fraction(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Пример #26
0
    def doprint(self, expr, assign_to=None):
        """
        Print the expression as code.

        Parameters
        ----------
        expr : Expression
            The expression to be printed.

        assign_to : Symbol, MatrixSymbol, or string (optional)
            If provided, the printed code will set the expression to a
            variable with name ``assign_to``.
        """
        from diofant.matrices.expressions.matexpr import MatrixSymbol

        if isinstance(assign_to, str):
            if expr.is_Matrix:
                assign_to = MatrixSymbol(assign_to, *expr.shape)
            else:
                assign_to = Symbol(assign_to)
        elif not isinstance(assign_to, (Basic, type(None))):
            raise TypeError("{0} cannot assign to object of type {1}".format(
                type(self).__name__, type(assign_to)))

        if assign_to:
            expr = Assignment(assign_to, expr)
        else:
            # _sympify is not enough b/c it errors on iterables
            expr = sympify(expr)

        # keep a set of expressions that are not strictly translatable to Code
        # and number constants that must be declared and initialized
        self._not_supported = set()
        self._number_symbols = set()

        lines = self._print(expr).splitlines()

        # format the output
        if self._settings["human"]:
            frontlines = []
            if len(self._not_supported) > 0:
                frontlines.append(self._get_comment(
                    "Not supported in {0}:".format(self.language)))
                for expr in sorted(self._not_supported, key=str):
                    frontlines.append(self._get_comment(type(expr).__name__))
            for name, value in sorted(self._number_symbols, key=str):
                frontlines.append(self._declare_number_const(name, value))
            lines = frontlines + lines
            lines = self._format_code(lines)
            result = "\n".join(lines)
        else:
            lines = self._format_code(lines)
            result = (self._number_symbols, self._not_supported,
                    "\n".join(lines))
        del self._not_supported
        del self._number_symbols
        return result
Пример #27
0
def test_sympify2():
    class A:
        def _diofant_(self):
            return Symbol("x")**3

    a = A()

    assert _sympify(a) == x**3
    assert sympify(a) == x**3
    assert a == x**3
Пример #28
0
def series(expr, x=None, x0=0, n=6, dir="+"):
    """Series expansion of ``expr`` in ``x`` around point ``x0``.

    See Also
    ========

    diofant.core.expr.Expr.series
    """
    expr = sympify(expr)
    return expr.series(x, x0, n, dir)
Пример #29
0
def POSform(variables, minterms, dontcares=None):
    """
    The POSform function uses simplified_pairs and a redundant-group
    eliminating algorithm to convert the list of all input combinations
    that generate '1' (the minterms) into the smallest Product of Sums form.

    The variables must be given as the first argument.

    Return a logical And function (i.e., the "product of sums" or "POS"
    form) that gives the desired outcome. If there are inputs that can
    be ignored, pass them as a list, too.

    The result will be one of the (perhaps many) functions that satisfy
    the conditions.

    Examples
    ========

    >>> from diofant.logic import POSform
    >>> from diofant import symbols
    >>> w, x, y, z = symbols('w x y z')
    >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1],
    ...             [1, 0, 1, 1], [1, 1, 1, 1]]
    >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
    >>> POSform([w, x, y, z], minterms, dontcares)
    And(Or(Not(w), y), z)

    References
    ==========

    .. [1] en.wikipedia.org/wiki/Quine-McCluskey_algorithm

    """
    variables = [sympify(v) for v in variables]
    if minterms == []:
        return false

    minterms = [list(i) for i in minterms]
    dontcares = [list(i) for i in (dontcares or [])]
    for d in dontcares:
        if d in minterms:
            raise ValueError('%s in minterms is also in dontcares' % d)

    maxterms = []
    for t in product([0, 1], repeat=len(variables)):
        t = list(t)
        if (t not in minterms) and (t not in dontcares):
            maxterms.append(t)
    old = None
    new = maxterms + dontcares
    while new != old:
        old = new
        new = _simplified_pairs(old)
    essential = _rem_redundancy(new, maxterms)
    return And(*[_convert_to_varsPOS(x, variables) for x in essential])
Пример #30
0
def _force_mutable(x):
    """Return a matrix as a Matrix, otherwise return x."""
    if getattr(x, 'is_Matrix', False):
        return x.as_mutable()
    elif isinstance(x, Basic):
        return x
    elif hasattr(x, '__array__'):
        a = x.__array__()
        if len(a.shape) == 0:
            return sympify(a)
        return Matrix(x)
    return x
Пример #31
0
def simplify_logic(expr, form=None, deep=True):
    """
    This function simplifies a boolean function to its simplified version
    in SOP or POS form. The return type is an Or or And object in Diofant.

    Parameters
    ==========

    expr : string or boolean expression
    form : string ('cnf' or 'dnf') or None (default).
        If 'cnf' or 'dnf', the simplest expression in the corresponding
        normal form is returned; if None, the answer is returned
        according to the form with fewest args (in CNF by default).
    deep : boolean (default True)
        indicates whether to recursively simplify any
        non-boolean functions contained within the input.

    Examples
    ========

    >>> from diofant.logic import simplify_logic
    >>> from diofant.abc import x, y, z
    >>> from diofant import sympify
    >>> b = (~x & ~y & ~z) | ( ~x & ~y & z)
    >>> simplify_logic(b)
    And(Not(x), Not(y))

    >>> sympify(b)
    Or(And(Not(x), Not(y), Not(z)), And(Not(x), Not(y), z))
    >>> simplify_logic(_)
    And(Not(x), Not(y))
    """

    if form == 'cnf' or form == 'dnf' or form is None:
        expr = sympify(expr)
        if not isinstance(expr, BooleanFunction):
            return expr
        variables = _find_predicates(expr)
        truthtable = []
        for t in product([0, 1], repeat=len(variables)):
            t = list(t)
            if expr.xreplace(dict(zip(variables, t))):
                truthtable.append(t)
        if deep:
            from diofant.simplify.simplify import simplify
            variables = [simplify(v) for v in variables]
        if form == 'dnf' or \
           (form is None and len(truthtable) >= (2 ** (len(variables) - 1))):
            return SOPform(variables, truthtable)
        elif form == 'cnf' or form is None:
            return POSform(variables, truthtable)
    else:
        raise ValueError("form can be cnf or dnf only")
Пример #32
0
def test_evaluate_false():
    cases = {
        '2 + 3': Add(2, 3, evaluate=False),
        '2**2 / 3': Mul(Pow(2, 2, evaluate=False), Pow(3, -1, evaluate=False), evaluate=False),
        '2 + 3 * 5': Add(2, Mul(3, 5, evaluate=False), evaluate=False),
        '2 - 3 * 5': Add(2, -Mul(3, 5, evaluate=False), evaluate=False),
        '1 / 3': Mul(1, Pow(3, -1, evaluate=False), evaluate=False),
        'True | False': Or(True, False, evaluate=False),
        '1 + 2 + 3 + 5*3 + integrate(x)': Add(1, 2, 3, Mul(5, 3, evaluate=False), x**2/2, evaluate=False),
        '2 * 4 * 6 + 8': Add(Mul(2, 4, 6, evaluate=False), 8, evaluate=False),
    }
    for case, result in cases.items():
        assert sympify(case, evaluate=False) == result
Пример #33
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', strict=True))
    pytest.raises(SympifyError, lambda: sympify('1/2', strict=True))
Пример #34
0
def SOPform(variables, minterms, dontcares=None):
    """
    The SOPform function uses simplified_pairs and a redundant group-
    eliminating algorithm to convert the list of all input combos that
    generate '1' (the minterms) into the smallest Sum of Products form.

    The variables must be given as the first argument.

    Return a logical Or function (i.e., the "sum of products" or "SOP"
    form) that gives the desired outcome. If there are inputs that can
    be ignored, pass them as a list, too.

    The result will be one of the (perhaps many) functions that satisfy
    the conditions.

    Examples
    ========

    >>> from diofant.logic import SOPform
    >>> from diofant import symbols
    >>> w, x, y, z = symbols('w x y z')
    >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1],
    ...             [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
    >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
    >>> SOPform([w, x, y, z], minterms, dontcares)
    Or(And(Not(w), z), And(y, z))

    References
    ==========

    .. [1] en.wikipedia.org/wiki/Quine-McCluskey_algorithm

    """
    variables = [sympify(v) for v in variables]
    if minterms == []:
        return false

    minterms = [list(i) for i in minterms]
    dontcares = [list(i) for i in (dontcares or [])]
    for d in dontcares:
        if d in minterms:
            raise ValueError('%s in minterms is also in dontcares' % d)

    old = None
    new = minterms + dontcares
    while new != old:
        old = new
        new = _simplified_pairs(old)
    essential = _rem_redundancy(new, minterms)
    return Or(*[_convert_to_varsSOP(x, variables) for x in essential])
Пример #35
0
def test_sympify_text():
    assert sympify('some') == Symbol('some')
    assert sympify('core') == Symbol('core')

    assert sympify('True') is True
    assert sympify('False') is False

    assert sympify('Poly') == Poly
    assert sympify('sin') == sin
Пример #36
0
def test_sympify_text():
    assert sympify('some') == Symbol('some')
    assert sympify('core') == Symbol('core')

    assert sympify('True') is True
    assert sympify('False') is False

    assert sympify('Poly') == Poly
    assert sympify('sin') == sin
Пример #37
0
def line_integrate(field, curve, vars):
    """line_integrate(field, Curve, variables)

    Compute the line integral.

    Examples
    ========

    >>> from diofant import Curve, line_integrate, E, ln
    >>> from diofant.abc import x, y, t
    >>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
    >>> line_integrate(x + y, C, [x, y])
    3*sqrt(2)

    See Also
    ========

    diofant.integrals.integrals.integrate
    diofant.integrals.integrals.Integral
    """
    from diofant.geometry import Curve
    F = sympify(field)
    if not F:
        raise ValueError(
            "Expecting function specifying field as first argument.")
    if not isinstance(curve, Curve):
        raise ValueError("Expecting Curve entity as second argument.")
    if not is_sequence(vars):
        raise ValueError("Expecting ordered iterable for variables.")
    if len(curve.functions) != len(vars):
        raise ValueError("Field variable size does not match curve dimension.")

    if curve.parameter in vars:
        raise ValueError("Curve parameter clashes with field parameters.")

    # Calculate derivatives for line parameter functions
    # F(r) -> F(r(t)) and finally F(r(t)*r'(t))
    Ft = F
    dldt = 0
    for i, var in enumerate(vars):
        _f = curve.functions[i]
        _dn = diff(_f, curve.parameter)
        # ...arc length
        dldt = dldt + (_dn * _dn)
        Ft = Ft.subs(var, _f)
    Ft = Ft * sqrt(dldt)

    integral = Integral(Ft, curve.limits).doit(deep=False)
    return integral
Пример #38
0
def _is_form(expr, function1, function2):
    """
    Test whether or not an expression is of the required form.

    """
    expr = sympify(expr)

    # Special case of an Atom
    if expr.is_Atom:
        return True

    # Special case of a single expression of function2
    if expr.func is function2:
        for lit in expr.args:
            if lit.func is Not:
                if not lit.args[0].is_Atom:
                    return False
            else:
                if not lit.is_Atom:
                    return False
        return True

    # Special case of a single negation
    if expr.func is Not:
        if not expr.args[0].is_Atom:
            return False

    if expr.func is not function1:
        return False

    for cls in expr.args:
        if cls.is_Atom:
            continue
        if cls.func is Not:
            if not cls.args[0].is_Atom:
                return False
        elif cls.func is not function2:
            return False
        for lit in cls.args:
            if lit.func is Not:
                if not lit.args[0].is_Atom:
                    return False
            else:
                if not lit.is_Atom:
                    return False

    return True
Пример #39
0
def is_nnf(expr, simplified=True):
    """
    Checks if expr is in Negation Normal Form.
    A logical expression is in Negation Normal Form (NNF) if it
    contains only And, Or and Not, and Not is applied only to literals.
    If simpified is True, checks if result contains no redundant clauses.

    Examples
    ========

    >>> from diofant.abc import A, B, C
    >>> from diofant.logic.boolalg import Not, is_nnf
    >>> is_nnf(A & B | ~C)
    True
    >>> is_nnf((A | ~A) & (B | C))
    False
    >>> is_nnf((A | ~A) & (B | C), False)
    True
    >>> is_nnf(Not(A & B) | C)
    False
    >>> is_nnf((A >> B) & (B >> A))
    False
    """

    expr = sympify(expr)
    if is_literal(expr):
        return True

    stack = [expr]

    while stack:
        expr = stack.pop()
        if expr.func in (And, Or):
            if simplified:
                args = expr.args
                for arg in args:
                    if Not(arg) in args:
                        return False
            stack.extend(expr.args)

        elif not is_literal(expr):
            return False

    return True
Пример #40
0
def test_sympify_strict():
    x = Symbol('x')
    f = Function('f')

    # positive sympify
    assert sympify(x, strict=True) is x
    assert sympify(f, strict=True) is f
    assert sympify(1, strict=True) == Integer(1)
    assert sympify(0.5, strict=True) == Float("0.5")
    assert sympify(1 + 1j, strict=True) == 1.0 + I*1.0

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

    a = A()
    assert sympify(a, strict=True) == Integer(5)

    # negative sympify
    pytest.raises(SympifyError, lambda: sympify('1', strict=True))
    pytest.raises(SympifyError, lambda: sympify([1, 2, 3], strict=True))
Пример #41
0
def test_sympify_strict():
    x = Symbol('x')
    f = Function('f')

    # positive sympify
    assert sympify(x, strict=True) is x
    assert sympify(f, strict=True) is f
    assert sympify(1, strict=True) == Integer(1)
    assert sympify(0.5, strict=True) == Float("0.5")
    assert sympify(1 + 1j, strict=True) == 1.0 + I*1.0

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

    a = A()
    assert sympify(a, strict=True) == Integer(5)

    # negative sympify
    pytest.raises(SympifyError, lambda: sympify('1', strict=True))
    pytest.raises(SympifyError, lambda: sympify([1, 2, 3], strict=True))
Пример #42
0
def test_sympify_mpmath():
    value = sympify(mpmath.mpf(1.0))
    assert value == Float(1.0) and type(value) is Float

    mpmath.mp.dps = 12
    assert sympify(
        mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) is true
    assert sympify(
        mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) is false

    mpmath.mp.dps = 6
    assert sympify(
        mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) is true
    assert sympify(
        mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) is false

    assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I
Пример #43
0
def test_lambda_raises():
    pytest.raises(NotImplementedError, lambda: sympify("lambda *args: args"))  # args argument error
    pytest.raises(NotImplementedError, lambda: sympify("lambda **kwargs: kwargs"))  # kwargs argument error
    pytest.raises(SympifyError, lambda: sympify("lambda x = 1: x"))    # Keyword argument error
    with pytest.raises(SympifyError):
        sympify('lambda: 1', strict=True)
Пример #44
0
def test_sympyissue_3538():
    v = sympify("exp(x)")
    assert v == exp(x)
    assert isinstance(v, Pow)
    assert str(type(v)) == str(type(exp(x)))
Пример #45
0
def test_sympyissue_3982():
    a = [3, 2.0]
    assert sympify(a) == [Integer(3), Float(2.0)]
    assert sympify(tuple(a)) == Tuple(Integer(3), Float(2.0))
    assert sympify(set(a)) == {Integer(3), Float(2.0)}
Пример #46
0
def test_S_sympify():
    assert Rational(1, 2) == sympify(1)/2
    assert sqrt(-2) == sqrt(2)*I
Пример #47
0
def test_lambda():
    x = Symbol('x')
    assert sympify('lambda: 1') == Lambda((), 1)
    assert sympify('lambda x: x') == Lambda(x, x)
    assert sympify('lambda x: 2*x') == Lambda(x, 2*x)
    assert sympify('lambda x, y: 2*x+y') == Lambda([x, y], 2*x + y)
Пример #48
0
def test_sympyissue_4798_None():
    assert sympify(None) is None
Пример #49
0
def test_sympify_Fraction():
    value = sympify(fractions.Fraction(101, 127))
    assert value == Rational(101, 127) and type(value) is Rational
Пример #50
0
def test_sympyissue_8821_highprec_from_str():
    s = str(pi.evalf(128))
    p = sympify(s)
    assert Abs(sin(p)) < 1e-127
Пример #51
0
def test_Range():
    assert sympify(range(10)) == Range(10)
    assert sympify(range(10), strict=True) == Range(10)
Пример #52
0
def test_int_float():
    class F1_1:
        def __float__(self):
            return 1.1

    class F1_1b:
        """
        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:
        """
        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:
        def __int__(self):
            return 5

    class I5b:
        """
        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:
        """
        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, strict=True) == 5
    assert isinstance(sympify(i5, strict=True), Integer)
    assert sympify(i5b, strict=True) == 5
    assert isinstance(sympify(i5b, strict=True), Float)
    assert sympify(i5c, strict=True) == 5
    assert isinstance(sympify(i5c, strict=True), Integer)
    assert abs(sympify(f1_1, strict=True) - 1.1) < 1e-5
    assert abs(sympify(f1_1b, strict=True) - 1.1) < 1e-5
    assert abs(sympify(f1_1c, strict=True) - 1.1) < 1e-5
Пример #53
0
def test_sympyissue_6540_6552():
    assert sympify('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)]
    assert sympify('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (Rational(1, 2),)]
    assert sympify('[[[2*(1)]]]') == [[[2]]]
    assert sympify('Matrix([2*(1)])') == Matrix([2])
Пример #54
0
def test_geometry():
    p = sympify(Point(0, 1))
    assert p == Point(0, 1) and isinstance(p, Point)
    L = sympify(Line(p, (1, 0)))
    assert L == Line((0, 1), (1, 0)) and isinstance(L, Line)
Пример #55
0
def test_sympify1():
    assert sympify(None) is None
    with pytest.raises(SympifyError) as ex:
        sympify(None, strict=True)
    assert str(ex).find("unprintable SympifyError object") >= 0
    assert sympify("x") == Symbol("x")
    assert sympify("   x") == Symbol("x")
    assert sympify("   x   ") == Symbol("x")
    # issue sympy/sympy#4877
    n1 = Rational(1, 2)
    assert sympify('--.5') == n1
    assert sympify('-1/2') == -n1
    assert sympify('-+--.5') == -n1
    # options to make reals into rationals
    assert sympify('2/2.6', rational=True) == Rational(10, 13)
    assert sympify('2.6/2', rational=True) == Rational(13, 10)
    assert sympify('2.6e2/17', rational=True) == Rational(260, 17)
    assert sympify('2.6e+2/17', rational=True) == Rational(260, 17)
    assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000)
    assert sympify('2.1+3/4', rational=True) == \
        Rational(21, 10) + Rational(3, 4)
    assert sympify('2.234456', rational=True) == Rational(279307, 125000)
    assert sympify('2.234456e23', rational=True) == 223445600000000000000000
    assert sympify('2.234456e-23', rational=True) == \
        Rational(279307, 12500000000000000000000000000)
    assert sympify('-2.234456e-23', rational=True) == \
        Rational(-279307, 12500000000000000000000000000)
    assert sympify('12345678901/17', rational=True) == \
        Rational(12345678901, 17)
    assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x
    # make sure longs in fractions work
    assert sympify('222222222222/11111111111') == \
        Rational(222222222222, 11111111111)
    # ... or from high precision reals
    assert sympify('.1234567890123456', rational=True) == \
        Rational(19290123283179, 156250000000000)
Пример #56
0
def test_sympyissue_4788():
    assert repr(sympify(1.0 + 0J)) == repr(Float(1.0)) == repr(Float(1.0))
Пример #57
0
def test_sympyissue_3595():
    assert sympify("a_") == Symbol("a_")
    assert sympify("_a") == Symbol("_a")
Пример #58
0
def test_sympyissue_3218():
    assert sympify("x+\ny") == x + y
Пример #59
0
def test_sympify_raises():
    pytest.raises(SympifyError, lambda: sympify("fx)"))
Пример #60
0
def test_sympyissue_4133():
    a = sympify('Integer(4)')

    assert a == Integer(4)
    assert a.is_Integer