예제 #1
0
def test_implicit_multiplication():
    cases = {
        '5x': '5*x',
        'xyz': 'x*y*z',
        '3sin(x)': '3*sin(x)',
        '(x+1)(x+2)': '(x+1)*(x+2)',
        '(5 x**2)sin(x)': '(5*x**2)*sin(x)',
        '2 sin(x) cos(x)': '2*sin(x)*cos(x)',
        'pi x': 'pi*x',
        'x pi': 'x*pi',
        'E x': 'E*x',
        'EulerGamma y': 'EulerGamma*y',
        'E pi': 'E*pi',
        'pi (x + 2)': 'pi*(x+2)',
        '(x + 2) pi': '(x+2)*pi',
        'pi sin(x)': 'pi*sin(x)'}
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (split_symbols,
                                          implicit_multiplication)
    for k, v in cases.items():
        implicit = parse_expr(k, transformations=transformations2)
        normal = parse_expr(v, transformations=transformations)
        assert implicit == normal

    application = ['sin x', 'cos 2*x', 'sin cos x']
    for case in application:
        pytest.raises(SyntaxError,
                      lambda: parse_expr(case, transformations=transformations2))
    pytest.raises(TypeError,
                  lambda: parse_expr('sin**2(x)', transformations=transformations2))
def test_implicit_multiplication():
    cases = {
        '5x': '5*x',
        'abc': 'a*b*c',
        '3sin(x)': '3*sin(x)',
        '(x+1)(x+2)': '(x+1)*(x+2)',
        '(5 x**2)sin(x)': '(5*x**2)*sin(x)',
        '2 sin(x) cos(x)': '2*sin(x)*cos(x)',
        'pi x': 'pi*x',
        'x pi': 'x*pi',
        'E x': 'E*x',
        'EulerGamma y': 'EulerGamma*y',
        'E pi': 'E*pi',
        'pi (x + 2)': 'pi*(x+2)',
        '(x + 2) pi': '(x+2)*pi',
        'pi sin(x)': 'pi*sin(x)',
    }
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (split_symbols,
                                          implicit_multiplication)
    for case in cases:
        implicit = parse_expr(case, transformations=transformations2)
        normal = parse_expr(cases[case], transformations=transformations)
        assert(implicit == normal)

    application = ['sin x', 'cos 2*x', 'sin cos x']
    for case in application:
        pytest.raises(SyntaxError,
                      lambda: parse_expr(case, transformations=transformations2))
    pytest.raises(TypeError,
                  lambda: parse_expr('sin**2(x)', transformations=transformations2))
예제 #3
0
def test_local_dict_symbol_to_fcn():
    x = Symbol('x')
    d = {'foo': Function('bar')}
    assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
    # XXX: bit odd, but would be error if parser left the Symbol
    d = {'foo': Symbol('baz')}
    assert parse_expr('foo(x)', local_dict=d) == Function('baz')(x)
예제 #4
0
def test_builtins():
    cases = [('abs(x)', 'Abs(x)'), ('max(x, y)', 'Max(x, y)'),
             ('min(x, y)', 'Min(x, y)'), ('pow(x, y)', 'Pow(x, y)')]
    for built_in_func_call, sympy_func_call in cases:
        assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call)
    assert parse_expr('pow(38, -1)') == Rational(1, 38)
    # issue sympy/sympy#22322
    assert parse_expr('abs(-42)', evaluate=False) == Abs(-42, evaluate=False)
예제 #5
0
def test_split_symbols():
    transformations = standard_transformations + \
        (split_symbols, implicit_multiplication)
    x = Symbol('x')
    y = Symbol('y')
    xy = Symbol('xy')

    assert parse_expr("xy") == xy
    assert parse_expr("xy", transformations=transformations) == x*y
예제 #6
0
def test_functional_exponent():
    t = standard_transformations + (convert_xor, function_exponentiation)
    x = Symbol('x')
    y = Symbol('y')
    a = Symbol('a')
    yfcn = Function('y')
    assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
    assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
    assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
    assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
    assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
예제 #7
0
def test_split_symbols_function():
    transformations = standard_transformations + \
        (split_symbols, implicit_multiplication)
    x = Symbol('x')
    y = Symbol('y')
    a = Symbol('a')
    f = Function('f')

    assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x + 1)
    assert parse_expr("af(x+1)", transformations=transformations,
                      local_dict={'f': f}) == a*f(x + 1)
예제 #8
0
def test_diofant_parser():
    x = Symbol('x')
    inputs = {
        '2*x':
        2 * x,
        '3.00':
        Float(3),
        '22/7':
        Rational(22, 7),
        '2+3j':
        2 + 3 * I,
        'exp(x)':
        exp(x),
        '-(2)':
        -Integer(2),
        '[-1, -2, 3]': [Integer(-1), Integer(-2),
                        Integer(3)],
        'Symbol("x").free_symbols':
        x.free_symbols,
        'Float(Integer(3).evalf(3))':
        3.00,
        'factorint(12, visual=True)':
        Mul(Pow(2, 2, evaluate=False),
            Pow(3, 1, evaluate=False),
            evaluate=False),
        'Limit(sin(x), x, 0, dir=1)':
        Limit(sin(x), x, 0, dir=1),
    }
    for text, result in inputs.items():
        assert parse_expr(text) == result
예제 #9
0
def test_rationalize():
    inputs = {
        '0.123': Rational(123, 1000)
    }
    transformations = standard_transformations + (rationalize,)
    for text, result in inputs.items():
        assert parse_expr(text, transformations=transformations) == result
예제 #10
0
def test_local_dict():
    local_dict = {
        'my_function': lambda x: x + 2
    }
    inputs = {
        'my_function(2)': Integer(4)
    }
    for text, result in inputs.items():
        assert parse_expr(text, local_dict=local_dict) == result
예제 #11
0
def test_global_dict():
    global_dict = {
        'Symbol': Symbol
    }
    inputs = {
        'Q & S': And(Symbol('Q'), Symbol('S'))
    }
    for text, result in inputs.items():
        assert parse_expr(text, global_dict=global_dict) == result
예제 #12
0
def test_function_exponentiation():
    cases = {
        'sin**2(x)': 'sin(x)**2',
        'exp^y(z)': 'exp(z)^y',
        'sin**2(E^(x))': 'sin(E^(x))**2'}
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (function_exponentiation,)
    for k, v in cases.items():
        implicit = parse_expr(k, transformations=transformations2)
        normal = parse_expr(v, transformations=transformations)
        assert implicit == normal

    other_implicit = ['x y', 'x sin x', '2x', 'sin x',
                      'cos 2*x', 'sin cos x']
    for case in other_implicit:
        pytest.raises(SyntaxError,
                      lambda: parse_expr(case, transformations=transformations2))

    assert parse_expr('x**2', local_dict={'x': diofant.Symbol('x')},
                      transformations=transformations2) == parse_expr('x**2')
def test_function_exponentiation():
    cases = {
        'sin**2(x)': 'sin(x)**2',
        'exp^y(z)': 'exp(z)^y',
        'sin**2(E^(x))': 'sin(E^(x))**2'
    }
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (function_exponentiation,)
    for case in cases:
        implicit = parse_expr(case, transformations=transformations2)
        normal = parse_expr(cases[case], transformations=transformations)
        assert(implicit == normal)

    other_implicit = ['x y', 'x sin x', '2x', 'sin x',
                      'cos 2*x', 'sin cos x']
    for case in other_implicit:
        pytest.raises(SyntaxError,
                      lambda: parse_expr(case, transformations=transformations2))

    assert parse_expr('x**2', local_dict={ 'x': diofant.Symbol('x') },
                      transformations=transformations2) == parse_expr('x**2')
예제 #14
0
def test_implicit_application():
    cases = {
        'factorial': 'factorial',
        'sin x': 'sin(x)',
        'tan y**3': 'tan(y**3)',
        'cos 2*x': 'cos(2*x)',
        '(cot)': 'cot',
        'sin cos tan x': 'sin(cos(tan(x)))'}
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (implicit_application,)
    for k, v in cases.items():
        implicit = parse_expr(k, transformations=transformations2)
        normal = parse_expr(v, transformations=transformations)
        assert implicit == normal

    multiplication = ['x y', 'x sin x', '2x']
    for case in multiplication:
        pytest.raises(SyntaxError,
                      lambda: parse_expr(case, transformations=transformations2))
    pytest.raises(TypeError,
                  lambda: parse_expr('sin**2(x)', transformations=transformations2))
def test_all_implicit_steps():
    cases = {
        '2x': '2*x',  # implicit multiplication
        'x y': 'x*y',
        'xy': 'x*y',
        'sin x': 'sin(x)',  # add parentheses
        '2sin x': '2*sin(x)',
        'x y z': 'x*y*z',
        'sin(2 * 3x)': 'sin(2 * 3 * x)',
        'sin(x) (1 + cos(x))': 'sin(x) * (1 + cos(x))',
        '(x + 2) sin(x)': '(x + 2) * sin(x)',
        '(x + 2) sin x': '(x + 2) * sin(x)',
        'sin(sin x)': 'sin(sin(x))',
        'factorial': 'factorial',  # don't apply a bare function
        'x sin x': 'x * sin(x)',  # both application and multiplication
        'xy sin x': 'x * y * sin(x)',
        '(x+2)(x+3)': '(x + 2) * (x+3)',
        'x**2 + 2xy + y**2': 'x**2 + 2 * x * y + y**2',  # split the xy
        'pi': 'pi',  # don't mess with constants
        'None': 'None',
        'ln sin x': 'ln(sin(x))',  # multiple implicit function applications
        'factorial': 'factorial',  # don't add parentheses
        'sin x**2': 'sin(x**2)',  # implicit application to an exponential
        'alpha': 'Symbol("alpha")',  # don't split Greek letters/subscripts
        'x_2': 'Symbol("x_2")',
        'sin^2 x**2': 'sin(x**2)**2',  # function raised to a power
        'sin**3(x)': 'sin(x)**3',
        '(factorial)': 'factorial',
        'tan 3x': 'tan(3*x)',
        'sin^2(3*E^(x))': 'sin(3*E**(x))**2',
        'sin**2(E^(3x))': 'sin(E**(3*x))**2',
        'sin^2 (3x*E^(x))': 'sin(3*x*E^x)**2',
        'pi sin x': 'pi*sin(x)',
    }
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (implicit_multiplication_application,)
    for case in cases:
        implicit = parse_expr(case, transformations=transformations2)
        normal = parse_expr(cases[case], transformations=transformations)
        assert(implicit == normal)
def test_implicit_application():
    cases = {
        'factorial': 'factorial',
        'sin x': 'sin(x)',
        'tan y**3': 'tan(y**3)',
        'cos 2*x': 'cos(2*x)',
        '(cot)': 'cot',
        'sin cos tan x': 'sin(cos(tan(x)))'
    }
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (implicit_application,)
    for case in cases:
        implicit = parse_expr(case, transformations=transformations2)
        normal = parse_expr(cases[case], transformations=transformations)
        assert(implicit == normal)

    multiplication = ['x y', 'x sin x', '2x']
    for case in multiplication:
        pytest.raises(SyntaxError,
                      lambda: parse_expr(case, transformations=transformations2))
    pytest.raises(TypeError,
                  lambda: parse_expr('sin**2(x)', transformations=transformations2))
예제 #17
0
def test_all_implicit_steps():
    cases = {
        '2x': '2*x',  # implicit multiplication
        'x y': 'x*y',
        'xy': 'x*y',
        'sin x': 'sin(x)',  # add parentheses
        '2sin x': '2*sin(x)',
        'x y z': 'x*y*z',
        'sin(2 * 3x)': 'sin(2 * 3 * x)',
        'sin(x) (1 + cos(x))': 'sin(x) * (1 + cos(x))',
        '(x + 2) sin(x)': '(x + 2) * sin(x)',
        '(x + 2) sin x': '(x + 2) * sin(x)',
        'sin(sin x)': 'sin(sin(x))',
        'factorial': 'factorial',  # don't apply a bare function
        'x sin x': 'x * sin(x)',  # both application and multiplication
        'xy sin x': 'x * y * sin(x)',
        '(x+2)(x+3)': '(x + 2) * (x+3)',
        'x**2 + 2xy + y**2': 'x**2 + 2 * x * y + y**2',  # split the xy
        'pi': 'pi',  # don't mess with constants
        'None': 'None',
        'ln sin x': 'ln(sin(x))',  # multiple implicit function applications
        'sin x**2': 'sin(x**2)',  # implicit application to an exponential
        'alpha': 'Symbol("alpha")',  # don't split Greek letters/subscripts
        'x_2': 'Symbol("x_2")',
        'sin^2 x**2': 'sin(x**2)**2',  # function raised to a power
        'sin**3(x)': 'sin(x)**3',
        '(factorial)': 'factorial',
        'tan 3x': 'tan(3*x)',
        'sin^2(3*E^(x))': 'sin(3*E**(x))**2',
        'sin**2(E^(3x))': 'sin(E**(3*x))**2',
        'sin^2 (3x*E^(x))': 'sin(3*x*E^x)**2',
        'pi sin x': 'pi*sin(x)'}
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (implicit_multiplication_application,)
    for k, v in cases.items():
        implicit = parse_expr(k, transformations=transformations2)
        normal = parse_expr(v, transformations=transformations)
        assert implicit == normal
예제 #18
0
def test_diofant_parser():
    x = Symbol('x')
    inputs = {
        '2*x': 2 * x,
        '3.00': Float(3),
        '22/7': Rational(22, 7),
        '2+3j': 2 + 3*I,
        'exp(x)': exp(x),
        '-(2)': -Integer(2),
        '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
        'Symbol("x").free_symbols': x.free_symbols,
        "Float(Integer(3).evalf(3))": 3.00,
        'factorint(12, visual=True)': Mul(
            Pow(2, 2, evaluate=False),
            Pow(3, 1, evaluate=False),
            evaluate=False),
        'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),

    }
    for text, result in inputs.items():
        assert parse_expr(text) == result
예제 #19
0
def sympify(a,
            locals=None,
            convert_xor=True,
            strict=False,
            rational=False,
            evaluate=None):
    """Converts an arbitrary expression to a type that can be used inside Diofant.

    For example, it will convert Python ints into instance of diofant.Rational,
    floats into instances of diofant.Float, etc. It is also able to coerce symbolic
    expressions which inherit from Basic. This can be useful in cooperation
    with SAGE.

    It currently accepts as arguments:
       - any object defined in diofant
       - standard numeric python types: int, long, float, Decimal
       - strings (like "0.09" or "2e-19")
       - booleans, including ``None`` (will leave ``None`` unchanged)
       - lists, sets or tuples containing any of the above

    If the argument is already a type that Diofant understands, it will do
    nothing but return that value. This can be used at the beginning of a
    function to ensure you are working with the correct type.

    >>> from diofant import sympify

    >>> sympify(2).is_integer
    True
    >>> sympify(2).is_extended_real
    True

    >>> sympify(2.0).is_extended_real
    True
    >>> sympify("2.0").is_extended_real
    True
    >>> sympify("2e-45").is_extended_real
    True

    If the expression could not be converted, a SympifyError is raised.

    >>> sympify("x***2")
    Traceback (most recent call last):
    ...
    SympifyError: SympifyError: "could not parse u'x***2'"

    *Locals*

    The sympification happens with access to everything that is loaded
    by ``from diofant import *``; anything used in a string that is not
    defined by that import will be converted to a symbol. In the following,
    the ``bitcount`` function is treated as a symbol and the ``O`` is
    interpreted as the Order object (used with series) and it raises
    an error when used improperly:

    >>> s = 'bitcount(42)'
    >>> sympify(s)
    bitcount(42)
    >>> sympify("O(x)")
    O(x)
    >>> sympify("O + 1")
    Traceback (most recent call last):
    ...
    TypeError: unbound method...

    In order to have ``bitcount`` be recognized it can be imported into a
    namespace dictionary and passed as locals:

    >>> ns = {}
    >>> exec('from diofant.core.evalf import bitcount', ns)
    >>> sympify(s, locals=ns)
    6

    In order to have the ``O`` interpreted as a Symbol, identify it as such
    in the namespace dictionary. This can be done in a variety of ways; all
    three of the following are possibilities:

    >>> from diofant import Symbol
    >>> ns["O"] = Symbol("O")  # method 1
    >>> exec('from diofant.abc import O', ns)  # method 2
    >>> ns.update(dict(O=Symbol("O")))  # method 3
    >>> sympify("O + 1", locals=ns)
    O + 1

    If you want *all* single-letter and Greek-letter variables to be symbols
    then you can use the clashing-symbols dictionaries that have been defined
    there as private variables: _clash1 (single-letter variables), _clash2
    (the multi-letter Greek names) or _clash (both single and multi-letter
    names that are defined in abc).

    >>> from diofant.abc import _clash1
    >>> _clash1
    {'E': E, 'I': I, 'N': N, 'O': O, 'S': S}
    >>> sympify('E & O', _clash1)
    And(E, O)

    *Strict*

    If the option ``strict`` is set to ``True``, only the types for which an
    explicit conversion has been defined are converted. In the other
    cases, a SympifyError is raised.

    >>> print(sympify(None))
    None
    >>> sympify(None, strict=True)
    Traceback (most recent call last):
    ...
    SympifyError: SympifyError: None

    *Evaluation*

    If the option ``evaluate`` is set to ``False``, then arithmetic and
    operators will be converted into their Diofant equivalents and the
    ``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will
    be denested first. This is done via an AST transformation that replaces
    operators with their Diofant equivalents, so if an operand redefines any
    of those operations, the redefined operators will not be used.

    >>> sympify('2**2 / 3 + 5')
    19/3
    >>> sympify('2**2 / 3 + 5', evaluate=False)
    2**2/3 + 5

    Sometimes autosimplification during sympification results in expressions
    that are very different in structure than what was entered.  Below you
    can see how an expression reduces to -1 by autosimplification, but does
    not do so when ``evaluate`` option is used.

    >>> from diofant.abc import x
    >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
    -1
    >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
    >>> sympify(s)
    -1
    >>> sympify(s, evaluate=False)
    -2*((x - 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1

    *Extending*

    To extend ``sympify`` to convert custom objects (not derived from ``Basic``),
    just define a ``_diofant_`` method to your class. You can do that even to
    classes that you do not own by subclassing or adding the method at runtime.

    >>> from diofant import Matrix
    >>> class MyList1(object):
    ...     def __iter__(self):
    ...         yield 1
    ...         yield 2
    ...         raise StopIteration
    ...     def __getitem__(self, i): return list(self)[i]
    ...     def _diofant_(self): return Matrix(self)
    >>> sympify(MyList1())
    Matrix([
    [1],
    [2]])

    If you do not have control over the class definition you could also use the
    ``converter`` global dictionary. The key is the class and the value is a
    function that takes a single argument and returns the desired Diofant
    object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.

    >>> class MyList2(object):   # XXX Do not do this if you control the class!
    ...     def __iter__(self):  #     Use _diofant_!
    ...         yield 1
    ...         yield 2
    ...         raise StopIteration
    ...     def __getitem__(self, i): return list(self)[i]
    >>> from diofant.core.sympify import converter
    >>> converter[MyList2] = lambda x: Matrix(x)
    >>> sympify(MyList2())
    Matrix([
    [1],
    [2]])
    """
    from .basic import Basic

    if evaluate is None:
        evaluate = global_evaluate[0]
    try:
        if issubclass(a, Basic):
            return a
    except TypeError:  # Type of a is unhashable
        pass
    cls = a.__class__
    if issubclass(cls, Basic):
        return a
    if issubclass(cls, type(None)):
        if strict:
            raise SympifyError(a)
        else:
            return a

    try:
        return converter[cls](a)
    except KeyError:
        for superclass in getmro(cls):
            try:
                return converter[superclass](a)
            except KeyError:
                continue

    if isinstance(a, CantSympify):
        raise SympifyError(a)

    try:
        return a._diofant_()
    except AttributeError:
        pass

    if not isinstance(a, str):
        for coerce in (float, int):
            try:
                return sympify(coerce(a))
            except (TypeError, ValueError, AttributeError, SympifyError):
                continue

    if strict:
        raise SympifyError(a)

    if iterable(a):
        return type(a)([
            sympify(x,
                    locals=locals,
                    convert_xor=convert_xor,
                    rational=rational) for x in a
        ])
    if isinstance(a, dict):
        return type(a)([
            sympify(x,
                    locals=locals,
                    convert_xor=convert_xor,
                    rational=rational) for x in a.items()
        ])

    # At this point we were given an arbitrary expression
    # which does not inherit from Basic and doesn't implement
    # _diofant_ (which is a canonical and robust way to convert
    # anything to Diofant expression).
    #
    # As a last chance, we try to take "a"'s normal form via str()
    # and try to parse it. If it fails, then we have no luck and
    # return an exception
    try:
        a = str(a)
    except Exception as exc:
        raise SympifyError(a, exc)

    from diofant.parsing.sympy_parser import (parse_expr, TokenError,
                                              standard_transformations)
    from diofant.parsing.sympy_parser import convert_xor as t_convert_xor
    from diofant.parsing.sympy_parser import rationalize as t_rationalize

    transformations = standard_transformations

    if rational:
        transformations += (t_rationalize, )
    if convert_xor:
        transformations += (t_convert_xor, )

    try:
        a = a.replace('\n', '')
        expr = parse_expr(a,
                          local_dict=locals,
                          transformations=transformations,
                          evaluate=evaluate)
    except (TokenError, SyntaxError) as exc:
        raise SympifyError('could not parse %r' % a, exc)

    return expr
def test_symbol_splitting():
    # By default Greek letter names should not be split (lambda is a keyword
    # so skip it)
    transformations = standard_transformations + (split_symbols,)
    greek_letters = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
                     'eta', 'theta', 'iota', 'kappa', 'mu', 'nu', 'xi',
                     'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
                     'phi', 'chi', 'psi', 'omega')

    for letter in greek_letters:
        assert(parse_expr(letter, transformations=transformations) ==
               parse_expr(letter))

    # Make sure symbol splitting resolves names
    transformations += (implicit_multiplication,)
    local_dict = { 'e': diofant.E }
    cases = {
        'xe': 'E*x',
        'Iy': 'I*y',
        'ee': 'E*E',
    }
    for case, expected in cases.items():
        assert(parse_expr(case, local_dict=local_dict,
                          transformations=transformations) ==
               parse_expr(expected))

    # Make sure custom splitting works
    def can_split(symbol):
        if symbol not in ('unsplittable', 'names'):
            return _token_splittable(symbol)
        return False
    transformations = standard_transformations
    transformations += (split_symbols_custom(can_split),
                        implicit_multiplication)

    assert(parse_expr('unsplittable', transformations=transformations) ==
           parse_expr('unsplittable'))
    assert(parse_expr('names', transformations=transformations) ==
           parse_expr('names'))
    assert(parse_expr('xy', transformations=transformations) ==
           parse_expr('x*y'))
    for letter in greek_letters:
        assert(parse_expr(letter, transformations=transformations) ==
               parse_expr(letter))
예제 #21
0
def test_sympyissue_7663():
    e = '2*(x+1)'
    assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False)
예제 #22
0
def test_sympyissue_2515():
    pytest.raises(TokenError, lambda: parse_expr('(()'))
    pytest.raises(TokenError, lambda: parse_expr('"""'))
예제 #23
0
def test_issue_7663():
    x = Symbol('x')
    e = '2*(x+1)'
    assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False)
예제 #24
0
def test_symbol_splitting():
    # By default Greek letter names should not be split (lambda is a keyword
    # so skip it)
    transformations = standard_transformations + (split_symbols, )
    greek_letters = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
                     'eta', 'theta', 'iota', 'kappa', 'mu', 'nu', 'xi',
                     'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi',
                     'chi', 'psi', 'omega')

    for letter in greek_letters:
        assert (parse_expr(
            letter, transformations=transformations) == parse_expr(letter))

    # Make sure symbol splitting resolves names
    transformations += (implicit_multiplication, )
    local_dict = {'e': diofant.E}
    cases = {
        'xe': 'E*x',
        'Iy': 'I*y',
        'ee': 'E*E',
    }
    for case, expected in cases.items():
        assert (parse_expr(
            case, local_dict=local_dict,
            transformations=transformations) == parse_expr(expected))

    # Make sure custom splitting works
    def can_split(symbol):
        if symbol not in ('unsplittable', 'names'):
            return _token_splittable(symbol)
        return False

    transformations = standard_transformations
    transformations += (split_symbols_custom(can_split),
                        implicit_multiplication)

    assert (parse_expr(
        'unsplittable',
        transformations=transformations) == parse_expr('unsplittable'))
    assert (parse_expr('names',
                       transformations=transformations) == parse_expr('names'))
    assert (parse_expr('xy',
                       transformations=transformations) == parse_expr('x*y'))
    for letter in greek_letters:
        assert (parse_expr(
            letter, transformations=transformations) == parse_expr(letter))
예제 #25
0
def test_sympyissue_22020():
    x = parse_expr('log((2*V/3-V)/C)/-(R+r)*C')
    y = parse_expr('log((2*V/3-V)/C)/-(R+r)*2')

    assert x.equals(y) is False
예제 #26
0
def test_match_parentheses_implicit_multiplication():
    transformations = standard_transformations + (implicit_multiplication,)
    pytest.raises(TokenError, lambda: parse_expr('(1,2),(3,4]', transformations=transformations))