Python sympy.sympify() Examples

The following are 30 code examples of sympy.sympify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sympy , or try the search function .
Example #1
Source File: test_sympy_conv.py    From symengine.py with MIT License 6 votes vote down vote up
def test_constants():
    assert sympify(sympy.E) == E
    assert sympy.E == E._sympy_()

    assert sympify(sympy.pi) == pi
    assert sympy.pi == pi._sympy_()

    assert sympify(sympy.GoldenRatio) == GoldenRatio
    assert sympy.GoldenRatio == GoldenRatio._sympy_()

    assert sympify(sympy.Catalan) == Catalan
    assert sympy.Catalan == Catalan._sympy_()

    assert sympify(sympy.EulerGamma) == EulerGamma
    assert sympy.EulerGamma == EulerGamma._sympy_()

    assert sympify(sympy.oo) == oo
    assert sympy.oo == oo._sympy_()

    assert sympify(sympy.zoo) == zoo
    assert sympy.zoo == zoo._sympy_()

    assert sympify(sympy.nan) == nan
    assert sympy.nan == nan._sympy_() 
Example #2
Source File: evaluator.py    From Jarvis with MIT License 6 votes vote down vote up
def calc(jarvis, s, calculator=sympy.sympify, formatter=None, do_evalf=True):
    s = format_expression(s)
    try:
        result = calculator(s)
    except sympy.SympifyError:
        jarvis.say("Error: Something is wrong with your expression", Fore.RED)
        return
    except NotImplementedError:
        jarvis.say("Sorry, cannot solve", Fore.RED)
        return

    if formatter is not None:
        result = formatter(result)

    if do_evalf:
        result = result.evalf()

    jarvis.say(str(result), Fore.BLUE) 
Example #3
Source File: test_sympy_conv.py    From symengine.py with MIT License 6 votes vote down vote up
def test_tuples_lists():
    x = sympy.Symbol("x")
    y = sympy.Symbol("y")
    z = sympy.Symbol("z")
    L = [x, y, z, x*y, z**y]
    t = (x, y, z, x*y, z**y)
    x = Symbol("x")
    y = Symbol("y")
    z = Symbol("z")
    l2 = [x, y, z, x*y, z**y]
    t2 = (x, y, z, x*y, z**y)
    assert sympify(L) == l2
    assert sympify(t) == t2
    assert sympify(L) != t2
    assert sympify(t) != l2

    assert L == l2
    assert t == t2
    assert L != t2
    assert t != l2 
Example #4
Source File: _parser_test.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def test_expressions(expr: str):
    qasm = """OPENQASM 2.0;
     qreg q[1];
     U({}, 2 * pi, pi / 2.0) q[0];
""".format(expr)

    parser = QasmParser()

    q0 = cirq.NamedQubit('q_0')

    expected_circuit = Circuit()
    expected_circuit.append(
        QasmUGate(float(sympy.sympify(expr)) / np.pi, 2.0, 1 / 2.0)(q0))

    parsed_qasm = parser.parse(qasm)

    assert parsed_qasm.supportedFormat
    assert not parsed_qasm.qelib1Include

    ct.assert_allclose_up_to_global_phase(cirq.unitary(parsed_qasm.circuit),
                                          cirq.unitary(expected_circuit),
                                          atol=1e-10)
    assert parsed_qasm.qregs == {'q': 1} 
Example #5
Source File: unit_registry.py    From unyt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _correct_old_unit_registry(data, sympify=False):
    lut = {}
    for k, v in data.items():
        unsan_v = list(v)
        if sympify:
            unsan_v[1] = cached_sympify(v[1])
        if len(unsan_v) == 4:
            # old unit registry so we need to add SI-prefixability to the registry
            # entry and correct the base_value to be in MKS units
            if k in default_unit_symbol_lut:
                unsan_v.append(default_unit_symbol_lut[k][4])
            else:
                unsan_v.append(False)
            dims = unsan_v[1]
            for dim_factor in dims.as_ordered_factors():
                dim, power = dim_factor.as_base_exp()
                if dim == unyt_dims.mass:
                    unsan_v[0] /= 1000 ** float(power)
                if dim == unyt_dims.length:
                    unsan_v[0] /= 100 ** float(power)
        lut[k] = tuple(unsan_v)
    for k in default_unit_symbol_lut:
        if k not in lut:
            lut[k] = default_unit_symbol_lut[k]
    return lut 
Example #6
Source File: test_sympy_conv.py    From symengine.py with MIT License 6 votes vote down vote up
def test_conv11():
    x = sympy.Symbol("x")
    y = sympy.Symbol("y")
    x1 = Symbol("x")
    y1 = Symbol("y")
    f = sympy.Function("f")
    f1 = Function("f")

    e1 = diff(f(2*x, y), x)
    e2 = diff(f1(2*x1, y1), x1)
    e3 = diff(f1(2*x1, y1), y1)

    assert sympify(e1) == e2
    assert sympify(e1) != e3

    assert e2._sympy_() == e1
    assert e3._sympy_() != e1 
Example #7
Source File: test_sympy_conv.py    From symengine.py with MIT License 6 votes vote down vote up
def test_conv10b():
    A = sympy.Matrix([[sympy.Symbol("x"), sympy.Symbol("y")],
                     [sympy.Symbol("z"), sympy.Symbol("t")]])
    assert sympify(A) == DenseMatrix(2, 2, [Symbol("x"), Symbol("y"),
                                            Symbol("z"), Symbol("t")])

    B = sympy.Matrix([[1, 2], [3, 4]])
    assert sympify(B) == DenseMatrix(2, 2, [Integer(1), Integer(2), Integer(3),
                                            Integer(4)])

    C = sympy.Matrix([[7, sympy.Symbol("y")],
                     [sympy.Function("g")(sympy.Symbol("z")), 3 + 2*sympy.I]])
    assert sympify(C) == DenseMatrix(2, 2, [Integer(7), Symbol("y"),
                                            function_symbol("g",
                                                            Symbol("z")),
                                            3 + 2*I]) 
Example #8
Source File: tsn.py    From tsalib with Apache License 2.0 6 votes vote down vote up
def _sexpr_to_ts (e, dummy_idx=0, strict=False, num_to_sym=False):
    '''
    A single string expression (sexpr) to Tensor Shape expressions (ts)
    Converts shorthand dummy/empty placeholders to dummy TSs
    '''
    if isinstance(e, DimExpr):  
        t = e
    else: 
        assert isinstance(e, str)
        if e.isdigit() and num_to_sym: e = '_' #convert to dummy var
        if e == '' or e =='_':  
            t = dummy_dvar(dummy_idx)
            dummy_idx += 1
        elif e == '^':
            #TODO: better way to handle '^' ?
            t = DimExpr(Symbol(e))
        else: 
            #TODO: strict: check if all dim vars in e are previously declared?
            t = DimExpr(sympify(e))

    return t, dummy_idx 
Example #9
Source File: mathml.py    From Computable with MIT License 6 votes vote down vote up
def print_mathml(expr, **settings):
    """
    Prints a pretty representation of the MathML code for expr

    Examples
    ========

    >>> ##
    >>> from sympy.printing.mathml import print_mathml
    >>> from sympy.abc import x
    >>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE
    <apply>
        <plus/>
        <ci>x</ci>
        <cn>1</cn>
    </apply>

    """
    s = MathMLPrinter(settings)
    xml = s._print(sympify(expr))
    s.apply_patch()
    pretty_xml = xml.toprettyxml()
    s.restore_patch()

    print(pretty_xml) 
Example #10
Source File: qexpr.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _qsympify_sequence(seq):
    """Convert elements of a sequence to standard form.

    This is like sympify, but it performs special logic for arguments passed
    to QExpr. The following conversions are done:

    * (list, tuple, Tuple) => _qsympify_sequence each element and convert
      sequence to a Tuple.
    * basestring => Symbol
    * Matrix => Matrix
    * other => sympify

    Strings are passed to Symbol, not sympify to make sure that variables like
    'pi' are kept as Symbols, not the SymPy built-in number subclasses.

    Examples
    ========

    >>> from sympsi.qexpr import _qsympify_sequence
    >>> _qsympify_sequence((1,2,[3,4,[1,]]))
    (1, 2, (3, 4, (1,)))

    """

    return tuple(__qsympify_sequence_helper(seq)) 
Example #11
Source File: hilbert.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def eval(cls, args):
        new_args = args[0], sympify(args[1])
        exp = new_args[1]
        #simplify hs**1 -> hs
        if exp == 1:
            return args[0]
        #simplify hs**0 -> 1
        if exp == 0:
            return sympify(1)
        #check (and allow) for hs**(x+42+y...) case
        if len(exp.atoms()) == 1:
            if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
                raise ValueError('Hilbert spaces can only be raised to \
                positive integers or Symbols: %r' % exp)
        else:
            for power in exp.atoms():
                if not (power.is_Integer or power.is_Symbol):
                    raise ValueError('Tensor powers can only contain integers \
                    or Symbols: %r' % power)
        return new_args 
Example #12
Source File: distributedmodules.py    From Computable with MIT License 6 votes vote down vote up
def sdm_from_vector(vec, O, K, **opts):
    """
    Create an sdm from an iterable of expressions.

    Coefficients are created in the ground field ``K``, and terms are ordered
    according to monomial order ``O``. Named arguments are passed on to the
    polys conversion code and can be used to specify for example generators.

    Examples
    ========

    >>> from sympy.polys.distributedmodules import sdm_from_vector
    >>> from sympy.abc import x, y, z
    >>> from sympy.polys import QQ, lex
    >>> sdm_from_vector([x**2+y**2, 2*z], lex, QQ)
    [((1, 0, 0, 1), 2), ((0, 2, 0, 0), 1), ((0, 0, 2, 0), 1)]
    """
    dics, gens = parallel_dict_from_expr(sympify(vec), **opts)
    dic = {}
    for i, d in enumerate(dics):
        for k, v in d.items():
            dic[(i,) + k] = K.convert(v)
    return sdm_from_dict(dic, O) 
Example #13
Source File: test_sympy_conv.py    From symengine.py with MIT License 6 votes vote down vote up
def test_conv7b():
    x = sympy.Symbol("x")
    y = sympy.Symbol("y")
    assert sympify(sympy.sin(x/3)) == sin(Symbol("x") / 3)
    assert sympify(sympy.sin(x/3)) != cos(Symbol("x") / 3)
    assert sympify(sympy.cos(x/3)) == cos(Symbol("x") / 3)
    assert sympify(sympy.tan(x/3)) == tan(Symbol("x") / 3)
    assert sympify(sympy.cot(x/3)) == cot(Symbol("x") / 3)
    assert sympify(sympy.csc(x/3)) == csc(Symbol("x") / 3)
    assert sympify(sympy.sec(x/3)) == sec(Symbol("x") / 3)
    assert sympify(sympy.asin(x/3)) == asin(Symbol("x") / 3)
    assert sympify(sympy.acos(x/3)) == acos(Symbol("x") / 3)
    assert sympify(sympy.atan(x/3)) == atan(Symbol("x") / 3)
    assert sympify(sympy.acot(x/3)) == acot(Symbol("x") / 3)
    assert sympify(sympy.acsc(x/3)) == acsc(Symbol("x") / 3)
    assert sympify(sympy.asec(x/3)) == asec(Symbol("x") / 3) 
Example #14
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_loggamma():
    x = Symbol("x")
    e1 = sympy.loggamma(sympy.Symbol("x"))
    e2 = loggamma(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #15
Source File: sympy_diff.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def pdf(x, mu, sigma):
    """Return the probability density function as an expression in x"""
    #x = sy.sympify(x)
    return 1/(sigma*sy.sqrt(2*sy.pi)) * sy.exp(-(x-mu)**2 / (2*sigma**2)) 
Example #16
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_beta():
    x = Symbol("x")
    y = Symbol("y")
    e1 = sympy.beta(sympy.Symbol("y"), sympy.Symbol("x"))
    e2 = beta(y, x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #17
Source File: unit_registry.py    From unyt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cached_sympify(u):
    """
    Successive loads of unit systems produce the same calls to sympify
    in UnitRegistry.from_json. Even within a single load, this is a
    net improvement because there will often be a few cache hits
    """
    return sympify(u, locals=vars(unyt_dims)) 
Example #18
Source File: basis.py    From RBF with MIT License 5 votes vote down vote up
def __init__(self, expr, supp, **kwargs):
    RBF.__init__(self, expr, **kwargs)
    ## SANITIZE `SUPP`
    # make sure `supp` is a scalar or a sympy expression of `eps`
    supp = sympy.sympify(supp)
    other_symbols = supp.free_symbols.difference({_EPS})
    if len(other_symbols) != 0:
      raise ValueError(
        '`supp` cannot contain any symbols other than `eps`')
  
    self._supp = supp 
Example #19
Source File: unit_registry.py    From unyt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_json(cls, json_text):
        """
        Returns a UnitRegistry object from a json-serialized unit registry

        Parameters
        ----------

        json_text : str
           A string containing a json represention of a UnitRegistry
        """
        data = json.loads(json_text)
        lut = _correct_old_unit_registry(data, sympify=True)
        return cls(lut=lut, add_default_symbols=False) 
Example #20
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_sign():
    x = Symbol("x")
    e1 = sympy.sign(sympy.Symbol("x"))
    e2 = sign(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #21
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_lowergamma():
    x = Symbol("x")
    y = Symbol("y")
    e1 = sympy.lowergamma(sympy.Symbol("x"), sympy.Symbol("y"))
    e2 = lowergamma(x, y)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #22
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_erfc():
    x = Symbol("x")
    e1 = sympy.erfc(sympy.Symbol("x"))
    e2 = erfc(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #23
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_erf():
    x = Symbol("x")
    e1 = sympy.erf(sympy.Symbol("x"))
    e2 = erf(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #24
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_levi_civita():
    x = Symbol("x")
    y = Symbol("y")
    z = Symbol("z")
    e1 = sympy.LeviCivita(sympy.Symbol("x"), sympy.Symbol("y"), sympy.Symbol("z"))
    e2 = LeviCivita(x, y, z)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #25
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_kronecker_delta():
    x = Symbol("x")
    y = Symbol("y")
    e1 = sympy.KroneckerDelta(sympy.Symbol("x"), sympy.Symbol("y"))
    e2 = KroneckerDelta(x, y)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #26
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_zeta():
    x = Symbol("x")
    y = Symbol("y")
    e1 = sympy.zeta(sympy.Symbol("x"))
    e2 = zeta(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1
    e1 = sympy.zeta(sympy.Symbol("x"), sympy.Symbol("y"))
    e2 = zeta(x, y)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #27
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_lambertw():
    x = Symbol("x")
    e1 = sympy.LambertW(sympy.Symbol("x"))
    e2 = LambertW(x)
    assert sympify(e1) == e2
    assert e2._sympy_() == e1 
Example #28
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_log():
    x = Symbol("x")
    x1 = sympy.Symbol("x")

    assert log(x) == log(x1)
    assert log(x)._sympy_() == sympy.log(x1)
    assert sympify(sympy.log(x1)) == log(x)

    y = Symbol("y")
    y1 = sympy.Symbol("y")

    assert log(x, y) == log(x, y1)
    assert log(x1, y) == log(x1, y1)
    assert log(x, y)._sympy_() == sympy.log(x1, y1)
    assert sympify(sympy.log(x1, y1)) == log(x, y) 
Example #29
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_mpc():
    if have_mpc:
        a = ComplexMPC('1', '2', 100)
        b = sympy.Float(1, 29) + sympy.Float(2, 29) * sympy.I
        assert sympify(b) == a
        assert b == a._sympy_() 
Example #30
Source File: test_sympy_conv.py    From symengine.py with MIT License 5 votes vote down vote up
def test_mpfr():
    if have_mpfr:
        a = RealMPFR('100', 100)
        b = sympy.Float('100', 29)
        assert sympify(b) == a
        assert b == a._sympy_()