Python sympy 模块,sympify() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sympy.sympify()

项目:ReGraph    作者:eugeniashurko    | 项目源码 | 文件源码
def to_atset(value):
    """Convert an attribute value to AtSet object."""
    if isinstance(value, str):
        symset = safe_sympify(value)
        # check that there are no symbols
        return AtSet(convert(AtSymSet(symset)), AtEmptySet())
    elif isinstance(value, list) or isinstance(value, set):
        str_vals = []
        num_vals = []
        for val in value:
            if test_number(val):
                num_vals.append(val)
            else:
                str_vals.append(val)
        res = AtSet(convert(AtFinSet(set(sympify(num_vals)))),
                    convert(AtPosStringSet(set(str_vals))))
        return res
    elif isinstance(value, dict):
        return AtSet.from_json(value)
    elif isinstance(value, AtSet):
        return value
    else:
        raise ReGraphError("value {} should be a list, set, string or dict "
                           "representation of AtSet".format(value))
项目:jitcdde    作者:neurophysik    | 项目源码 | 文件源码
def tangent_vector_f(f, helpers, n, n_lyap, delays, zero_padding=0, simplify=True):
    if f:
        def f_lyap():
            yield from f()

            for i in range(n_lyap):
                jacs = [_jac(f, helpers, delay, n) for delay in delays]

                for _ in range(n):
                    expression = 0
                    for delay,jac in zip(delays,jacs):
                        for k,entry in enumerate(next(jac)):
                            expression += entry * y(k+(i+1)*n,t-delay)

                    if simplify:
                        expression = expression.simplify(ratio=1.0)
                    yield expression

            for _ in range(zero_padding):
                yield symengine.sympify(0)

    else:
        return []

    return f_lyap
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(
        self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
            **kwargs):
        super(ParametricSurfaceSeries, self).__init__()
        self.expr_x = sympify(expr_x)
        self.expr_y = sympify(expr_y)
        self.expr_z = sympify(expr_z)
        self.var_u = sympify(var_start_end_u[0])
        self.start_u = float(var_start_end_u[1])
        self.end_u = float(var_start_end_u[2])
        self.var_v = sympify(var_start_end_v[0])
        self.start_v = float(var_start_end_v[1])
        self.end_v = float(var_start_end_v[2])
        self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
        self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
        self.surface_color = kwargs.get('surface_color', None)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(self, expr, var_start_end_x, var_start_end_y,
            has_equality, use_interval_math, depth, nb_of_points):
        super(ImplicitSeries, self).__init__()
        self.expr = sympify(expr)
        self.var_x = sympify(var_start_end_x[0])
        self.start_x = float(var_start_end_x[1])
        self.end_x = float(var_start_end_x[2])
        self.var_y = sympify(var_start_end_y[0])
        self.start_y = float(var_start_end_y[1])
        self.end_y = float(var_start_end_y[2])
        self.get_points = self.get_raster
        self.has_equality = has_equality  # If the expression has equality, i.e.
                                         #Eq, Greaterthan, LessThan.
        self.nb_of_points = nb_of_points
        self.use_interval_math = use_interval_math
        self.depth = 4 + depth
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def set_potential_energy(self, scalar):
        """Used to set the potential energy of the Particle.

        Parameters
        ==========

        scalar : Sympifyable
            The potential energy (a scalar) of the Particle.

        Examples
        ========

        >>> from sympy.physics.mechanics import Particle, Point
        >>> from sympy import symbols
        >>> m, g, h = symbols('m g h')
        >>> O = Point('O')
        >>> P = Particle('P', O, m)
        >>> P.set_potential_energy(m * g * h)

        """

        self._pe = sympify(scalar)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __mul__(self, other):
        """Multiplies the Dyadic by a sympifyable expression.

        Parameters
        ==========

        other : Sympafiable
            The scalar to multiply this Dyadic with

        Examples
        ========

        >>> from sympy.physics.vector import ReferenceFrame, outer
        >>> N = ReferenceFrame('N')
        >>> d = outer(N.x, N.x)
        >>> 5 * d
        5*(N.x|N.x)

        """

        newlist = [v for v in self.args]
        for i, v in enumerate(newlist):
            newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1],
                          newlist[i][2])
        return Dyadic(newlist)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_function_series1():
    """Create our new "sin" function."""

    class my_function(Function):

        def fdiff(self, argindex=1):
            return cos(self.args[0])

        @classmethod
        def eval(cls, arg):
            arg = sympify(arg)
            if arg == 0:
                return sympify(0)

    #Test that the taylor series is correct
    assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
    assert limit(my_function(x)/x, x, 0) == 1
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_function_series2():
    """Create our new "cos" function."""

    class my_function2(Function):

        def fdiff(self, argindex=1):
            return -sin(self.args[0])

        @classmethod
        def eval(cls, arg):
            arg = sympify(arg)
            if arg == 0:
                return sympify(1)

    #Test that the taylor series is correct
    assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_function_series3():
    """
    Test our easy "tanh" function.

    This test tests two things:
      * that the Function interface works as expected and it's easy to use
      * that the general algorithm for the series expansion works even when the
        derivative is defined recursively in terms of the original function,
        since tanh(x).diff(x) == 1-tanh(x)**2
    """

    class mytanh(Function):

        def fdiff(self, argindex=1):
            return 1 - mytanh(self.args[0])**2

        @classmethod
        def eval(cls, arg):
            arg = sympify(arg)
            if arg == 0:
                return sympify(0)

    e = tanh(x)
    f = mytanh(x)
    assert tanh(x).series(x, 0, 6) == mytanh(x).series(x, 0, 6)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def parse_maxima(str, globals=None, name_dict={}):
    str = str.strip()
    str = str.rstrip('; ')

    for k, v in sub_dict.items():
        str = v.sub(k, str)

    assign_var = None
    var_match = var_name.search(str)
    if var_match:
        assign_var = var_match.group(1)
        str = str[var_match.end():].strip()

    dct = MaximaHelpers.__dict__.copy()
    dct.update(name_dict)
    obj = sympify(str, locals=dct)

    if assign_var and globals:
        globals[assign_var] = obj

    return obj
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_mathematica():
    d = {'Sin[x]^2': 'sin(x)**2',
        '2(x-1)': '2*(x-1)',
        '3y+8': '3*y+8',
        'Arcsin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
        'x+y': 'x+y',
        '355/113': '355/113',
        '2.718281828': '2.718281828',
        'Sin[12]': 'sin(12)',
        'Exp[Log[4]]': 'exp(log(4))',
        '(x+1)(x+3)': '(x+1)*(x+3)',
        'Cos[Arccos[3.6]]': 'cos(acos(3.6))',
        'Cos[x]==Sin[y]': 'cos(x)==sin(y)',
        '2*Sin[x+y]': '2*sin(x+y)',
        'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
        'Sin[Cos[x]]': 'sin(cos(x))',
        '2*Sqrt[x+y]': '2*sqrt(x+y)'}   # Test case from the issue 4259
    for e in d:
        assert mathematica(e) == sympify(d[e])
项目:bce    作者:bce-toolkit    | 项目源码 | 文件源码
def print_mexp(expr, protected_header_enabled=False, protected_header_prefix="X", **settings):
    """Print an expression to a MathML object.

    :type protected_header_enabled: bool
    :type protected_header_prefix: str
    :param expr: The expression.
    :param protected_header_enabled: Whether the protected headers are enabled.
    :param protected_header_prefix: The prefix of the protected headers.
    :param settings: The settings.
    :rtype : bce.dom.mathml.all.Base
    :return: The printed MathML object.
    """

    # noinspection PyProtectedMember
    return _MathMLPrinter(
        settings,
        protected_header_enabled=protected_header_enabled,
        protected_header_prefix=protected_header_prefix
    ).doprint(_sympy.sympify(expr))
项目:pyccel    作者:ratnania    | 项目源码 | 文件源码
def leading_term(expr, *args):
    """
    Returns the leading term in a sympy Polynomial.

    expr: sympy.Expr
        any sympy expression

    args: list
        list of input symbols for univariate/multivariate polynomials
    """
    expr = sympify(str(expr))
    P = Poly(expr, *args)
    return LT(P)
# ...

# ...
项目:pyccel    作者:ratnania    | 项目源码 | 文件源码
def __new__(cls, lhs, rhs, strict=False, status=None, like=None):
        cls._strict = strict
        if strict:
            lhs = sympify(lhs)
            rhs = sympify(rhs)
            # Tuple of things that can be on the lhs of an assignment
            assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Idx)
            #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 Basic.__new__(cls, lhs, rhs, status, like)
项目:pyccel    作者:ratnania    | 项目源码 | 文件源码
def __new__(cls, base, *args, **kw_args):
        from sympy.utilities.misc import filldedent
        from sympy.tensor.array.ndim_array import NDimArray
        from sympy.matrices.matrices import MatrixBase

        if not args:
            raise IndexException("Indexed needs at least one index.")
        if isinstance(base, (string_types, Symbol)):
            base = IndexedBase(base)
        elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase):
            raise TypeError(filldedent("""
                Indexed expects string, Symbol, or IndexedBase as base."""))
        args = list(map(sympify, args))
        if isinstance(base, (NDimArray, collections.Iterable, Tuple, MatrixBase)) and all([i.is_number for i in args]):
            if len(args) == 1:
                return base[args[0]]
            else:
                return base[args]

        return Expr.__new__(cls, base, *args, **kw_args)
项目:Chemistry-ChemEng    作者:AndyWilliams682    | 项目源码 | 文件源码
def dof_unknowns(control_volume_dimensions):
    unknown_list = []

    for path in control_volume_dimensions:
        for equation_key, equation_value in path.items():
            for variable in sp.sympify(equation_value).atoms(sp.Symbol):
                if variable not in unknown_list:
                    unknown_list.append(variable)

    unknowns = len(unknown_list)

    return unknowns


# This function uses the dof_unknowns, along with the setup matrix from the first function
# to determine how many degrees of freedom exist in a given control volume
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def __init__(
        self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
            **kwargs):
        super(ParametricSurfaceSeries, self).__init__()
        self.expr_x = sympify(expr_x)
        self.expr_y = sympify(expr_y)
        self.expr_z = sympify(expr_z)
        self.var_u = sympify(var_start_end_u[0])
        self.start_u = float(var_start_end_u[1])
        self.end_u = float(var_start_end_u[2])
        self.var_v = sympify(var_start_end_v[0])
        self.start_v = float(var_start_end_v[1])
        self.end_v = float(var_start_end_v[2])
        self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
        self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
        self.surface_color = kwargs.get('surface_color', None)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def __init__(self, expr, var_start_end_x, var_start_end_y,
            has_equality, use_interval_math, depth, nb_of_points,
            line_color):
        super(ImplicitSeries, self).__init__()
        self.expr = sympify(expr)
        self.var_x = sympify(var_start_end_x[0])
        self.start_x = float(var_start_end_x[1])
        self.end_x = float(var_start_end_x[2])
        self.var_y = sympify(var_start_end_y[0])
        self.start_y = float(var_start_end_y[1])
        self.end_y = float(var_start_end_y[2])
        self.get_points = self.get_raster
        self.has_equality = has_equality  # If the expression has equality, i.e.
                                         #Eq, Greaterthan, LessThan.
        self.nb_of_points = nb_of_points
        self.use_interval_math = use_interval_math
        self.depth = 4 + depth
        self.line_color = line_color
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def __new__(cls, name, symbol=None):

        if isinstance(name, string_types):
            name = Symbol(name)
        else:
            name = sympify(name)

        if not isinstance(name, Expr):
            raise TypeError("Dimension name needs to be a valid math expression")

        if isinstance(symbol, string_types):
            symbol = Symbol(symbol)
        elif symbol is not None:
            assert isinstance(symbol, Symbol)

        if symbol is not None:
            obj = Expr.__new__(cls, name, symbol)
        else:
            obj = Expr.__new__(cls, name)

        obj._name = name
        obj._symbol = symbol
        return obj
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def __new__(cls, name, permittivity=None, permeability=None, n=None):
        obj = super(Medium, cls).__new__(cls, name)
        obj._permittivity = sympify(permittivity)
        obj._permeability = sympify(permeability)
        obj._n = sympify(n)
        if n is not None:
            if permittivity != None and permeability == None:
                obj._permeability = n**2/(c**2*obj._permittivity)
            if permeability != None and permittivity == None:
                obj._permittivity = n**2/(c**2*obj._permeability)
            if permittivity != None and permittivity != None:
                if abs(n - c*sqrt(obj._permittivity*obj._permeability)) > 1e-6:
                   raise ValueError("Values are not consistent.")
        elif permittivity is not None and permeability is not None:
            obj._n = c*sqrt(permittivity*permeability)
        elif permittivity is None and permeability is None:
            obj._permittivity = _e0mksa
            obj._permeability = _u0mksa
        return obj
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
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
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_function_series1():
    """Create our new "sin" function."""

    class my_function(Function):

        def fdiff(self, argindex=1):
            return cos(self.args[0])

        @classmethod
        def eval(cls, arg):
            arg = sympify(arg)
            if arg == 0:
                return sympify(0)

    #Test that the taylor series is correct
    assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
    assert limit(my_function(x)/x, x, 0) == 1
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_function_series2():
    """Create our new "cos" function."""

    class my_function2(Function):

        def fdiff(self, argindex=1):
            return -sin(self.args[0])

        @classmethod
        def eval(cls, arg):
            arg = sympify(arg)
            if arg == 0:
                return sympify(1)

    #Test that the taylor series is correct
    assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_function_series3():
    """
    Test our easy "tanh" function.

    This test tests two things:
      * that the Function interface works as expected and it's easy to use
      * that the general algorithm for the series expansion works even when the
        derivative is defined recursively in terms of the original function,
        since tanh(x).diff(x) == 1-tanh(x)**2
    """

    class mytanh(Function):

        def fdiff(self, argindex=1):
            return 1 - mytanh(self.args[0])**2

        @classmethod
        def eval(cls, arg):
            arg = sympify(arg)
            if arg == 0:
                return sympify(0)

    e = tanh(x)
    f = mytanh(x)
    assert tanh(x).series(x, 0, 6) == mytanh(x).series(x, 0, 6)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
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)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def bench_R8():
    "right(x^2,0,5,10^4)"
    def right(f, a, b, n):
        a = sympify(a)
        b = sympify(b)
        n = sympify(n)
        x = f.atoms(Symbol).pop()
        Deltax = (b - a)/n
        c = a
        est = 0
        for i in range(n):
            c += Deltax
            est += f.subs(x, c)
        return est*Deltax

    a = right(x**2, 0, 5, 10**4)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_mathematica():
    d = {
        '- 6x': '-6*x',
        'Sin[x]^2': 'sin(x)**2',
        '2(x-1)': '2*(x-1)',
        '3y+8': '3*y+8',
        'Arcsin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
        'x+y': 'x+y',
        '355/113': '355/113',
        '2.718281828': '2.718281828',
        'Sin[12]': 'sin(12)',
        'Exp[Log[4]]': 'exp(log(4))',
        '(x+1)(x+3)': '(x+1)*(x+3)',
        'Cos[Arccos[3.6]]': 'cos(acos(3.6))',
        'Cos[x]==Sin[y]': 'cos(x)==sin(y)',
        '2*Sin[x+y]': '2*sin(x+y)',
        'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
        'Sin[Cos[x]]': 'sin(cos(x))',
        '2*Sqrt[x+y]': '2*sqrt(x+y)'}   # Test case from the issue 4259
    for e in d:
        assert mathematica(e) == sympify(d[e])
项目:ReGraph    作者:Kappa-Dev    | 项目源码 | 文件源码
def to_atset(value):
    """Convert an attribute value to AtSet object."""
    if isinstance(value, str):
        symset = safe_sympify(value)
        # check that there are no symbols
        return AtSet(convert(AtSymSet(symset)), AtEmptySet())
    elif isinstance(value, list) or isinstance(value, set):
        str_vals = []
        num_vals = []
        for val in value:
            if test_number(val):
                num_vals.append(val)
            else:
                str_vals.append(val)
        res = AtSet(convert(AtFinSet(set(sympify(num_vals)))),
                    convert(AtPosStringSet(set(str_vals))))
        return res
    elif isinstance(value, dict):
        return AtSet.from_json(value)
    elif isinstance(value, AtSet):
        return value
    else:
        raise ReGraphError("value {} should be a list, set, string or dict "
                           "representation of AtSet".format(value))
项目:LearningPyQt    作者:manashmndl    | 项目源码 | 文件源码
def evaluateExpression(self):
        sympified = sp.sympify(self.expression)

        valu = float(self.value)

        print sympified
        ans = sympified.subs([(self.var, valu)])
        self.ui.evaluatedExpressionLabel.setText(QtCore.QString.number(ans))
项目:ReGraph    作者:eugeniashurko    | 项目源码 | 文件源码
def from_json(json_data):
        if not isinstance(json_data["pos_list"], list):
            raise ReGraphError("pos_list field should contain a list")
        for el in json_data["pos_list"]:
            if not test_number(el):
                raise ReGraphError("{} is not a number".format(el))
        return convert(AtFinSet(set(sympify(json_data["pos_list"]))))
项目:ReGraph    作者:eugeniashurko    | 项目源码 | 文件源码
def safe_sympify(value):
    _check_input(value)
    return sympify(value)
项目:jitcdde    作者:neurophysik    | 项目源码 | 文件源码
def _find_max_delay(delays):
    if all(symengine.sympify(delay).is_Number for delay in delays):
        return float(max(delays))
    else:
        raise ValueError("Delay depends on time or dynamics; cannot determine max_delay automatically. You have to pass it as an argument to jitcdde.")
项目:transmutagen    作者:ergs    | 项目源码 | 文件源码
def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('degree', type=int)
    parser.add_argument('prec', type=int, default=50)
    parser.add_argument('data', help="""Data of matrix to compute exp of. Should
    be in scipy sparse csr format.""")
    parser.add_argument('time', type=float)
    parser.add_argument('--expr', type=lambda e: sympify(e, locals=globals()), help="""Precomputed CRAM
    expression. Should have the same prec as 'prec'. If not provided, will be
    computed from scratch.""")
    parser.add_argument('--log-level', default=None, choices=['debug', 'info',
        'warning', 'error', 'critical'])
    # TODO: Add options for arguments to pass to various functions as needed.
    try:
        import argcomplete
        argcomplete.autocomplete(parser)
    except ImportError:
        pass
    args = parser.parse_args()

    if args.log_level:
        logger.setLevel(getattr(logging, args.log_level.upper()))

    res = run_transmute_test(args.data, args.degree, args.prec,
        args.time,expr=args.expr,  _print=True)

    print("Column sums (min, max):")
    errors = {}
    colsums = {}
    for r in sorted(res):
        if res[r] is None:
            print('Could not compute', r)
            continue
        colsums[r] = np.sum(res[r], axis=1)
        errors[r] = np.max(colsums[r]) - np.min(colsums[r])
    for r in sorted(errors, key=lambda i:errors[i], reverse=True):
        print(r, np.min(colsums[r]), np.max(colsums[r]))
项目:cobrame    作者:SBRG    | 项目源码 | 文件源码
def get_sympy_expression(value):
    """
    Return sympy expression from json string using sympify


    mu is assumed to be positive but using sympify does not apply this
    assumption"""

    expression_value = sympify(value)
    return expression_value.subs(mu_temp, mu)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def rv(symbol, cls, *args):
    args = list(map(sympify, args))
    dist = cls(*args)
    dist.check(*args)
    return SingleDiscretePSpace(symbol, dist).value
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_meijerg_confluence():
    def t(m, a, b):
        from sympy import sympify, Piecewise
        a, b = sympify([a, b])
        m_ = m
        m = hyperexpand(m)
        if not m == Piecewise((a, abs(z) < 1), (b, abs(1/z) < 1), (m_, True)):
            return False
        if not (m.args[0].args[0] == a and m.args[1].args[0] == b):
            return False
        z0 = randcplx()/10
        if abs(m.subs(z, z0).n() - a.subs(z, z0).n()).n() > 1e-10:
            return False
        if abs(m.subs(z, 1/z0).n() - b.subs(z, 1/z0).n()).n() > 1e-10:
            return False
        return True

    assert t(meijerg([], [1, 1], [0, 0], [], z), -log(z), 0)
    assert t(meijerg(
        [], [3, 1], [0, 0], [], z), -z**2/4 + z - log(z)/2 - S(3)/4, 0)
    assert t(meijerg([], [3, 1], [-1, 0], [], z),
             z**2/12 - z/2 + log(z)/2 + S(1)/4 + 1/(6*z), 0)
    assert t(meijerg([], [1, 1, 1, 1], [0, 0, 0, 0], [], z), -log(z)**3/6, 0)
    assert t(meijerg([1, 1], [], [], [0, 0], z), 0, -log(1/z))
    assert t(meijerg([1, 1], [2, 2], [1, 1], [0, 0], z),
             -z*log(z) + 2*z, -log(1/z) + 2)
    assert t(meijerg([S(1)/2], [1, 1], [0, 0], [S(3)/2], z), log(z)/2 - 1, 0)

    def u(an, ap, bm, bq):
        m = meijerg(an, ap, bm, bq, z)
        m2 = hyperexpand(m, allow_hyper=True)
        if m2.has(meijerg) and not (m2.is_Piecewise and len(m2.args) == 3):
            return False
        return tn(m, m2, z)
    assert u([], [1], [0, 0], [])
    assert u([1, 1], [], [], [0])
    assert u([1, 1], [2, 2, 5], [1, 1, 6], [0, 0])
    assert u([1, 1], [2, 2, 5], [1, 1, 6], [0])
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_lt_gt():
    from sympy import sympify as S
    x, y = Symbol('x'), Symbol('y')

    assert (x >= y) == GreaterThan(x, y)
    assert (x >= 0) == GreaterThan(x, 0)
    assert (x <= y) == LessThan(x, y)
    assert (x <= 0) == LessThan(x, 0)

    assert (0 <= x) == GreaterThan(x, 0)
    assert (0 >= x) == LessThan(x, 0)
    assert (S(0) >= x) == GreaterThan(0, x)
    assert (S(0) <= x) == LessThan(0, x)

    assert (x > y) == StrictGreaterThan(x, y)
    assert (x > 0) == StrictGreaterThan(x, 0)
    assert (x < y) == StrictLessThan(x, y)
    assert (x < 0) == StrictLessThan(x, 0)

    assert (0 < x) == StrictGreaterThan(x, 0)
    assert (0 > x) == StrictLessThan(x, 0)
    assert (S(0) > x) == StrictGreaterThan(0, x)
    assert (S(0) < x) == StrictLessThan(0, x)

    e = x**2 + 4*x + 1
    assert (e >= 0) == GreaterThan(e, 0)
    assert (0 <= e) == GreaterThan(e, 0)
    assert (e > 0) == StrictGreaterThan(e, 0)
    assert (0 < e) == StrictGreaterThan(e, 0)

    assert (e <= 0) == LessThan(e, 0)
    assert (0 >= e) == LessThan(e, 0)
    assert (e < 0) == StrictLessThan(e, 0)
    assert (0 > e) == StrictLessThan(e, 0)

    assert (S(0) >= e) == GreaterThan(0, e)
    assert (S(0) <= e) == LessThan(0, e)
    assert (S(0) < e) == StrictLessThan(0, e)
    assert (S(0) > e) == StrictGreaterThan(0, e)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_Wild_properties():
    # these tests only include Atoms
    x = Symbol("x")
    y = Symbol("y")
    p = Symbol("p", positive=True)
    k = Symbol("k", integer=True)
    n = Symbol("n", integer=True, positive=True)

    given_patterns = [ x, y, p, k, -k, n, -n, sympify(-3), sympify(3),
                       pi, Rational(3, 2), I ]

    integerp = lambda k: k.is_integer
    positivep = lambda k: k.is_positive
    symbolp = lambda k: k.is_Symbol
    realp = lambda k: k.is_real

    S = Wild("S", properties=[symbolp])
    R = Wild("R", properties=[realp])
    Y = Wild("Y", exclude=[x, p, k, n])
    P = Wild("P", properties=[positivep])
    K = Wild("K", properties=[integerp])
    N = Wild("N", properties=[positivep, integerp])

    given_wildcards = [ S, R, Y, P, K, N ]

    goodmatch = {
        S: (x, y, p, k, n),
        R: (p, k, -k, n, -n, -3, 3, pi, Rational(3, 2)),
        Y: (y, -3, 3, pi, Rational(3, 2), I ),
        P: (p, n, 3, pi, Rational(3, 2)),
        K: (k, -k, n, -n, -3, 3),
        N: (n, 3)}

    for A in given_wildcards:
        for pat in given_patterns:
            d = pat.match(A)
            if pat in goodmatch[A]:
                assert d[A] in goodmatch[A]
            else:
                assert d is None
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _is_scalar(e):
    """ Helper method used in Tr"""

    # sympify to set proper attributes
    e = sympify(e)
    if isinstance(e, Expr):
        if (e.is_Integer or e.is_Float or
            e.is_Rational or e.is_Number or
            (e.is_Symbol and e.is_commutative)
                ):
            return True

    return False
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def set_v_min(self, v_min):
        if v_min is None:
            self._v_min = None
            return
        try:
            self._v_min = sympify(v_min)
            float(self._v_min.evalf())
        except TypeError:
            raise ValueError("v_min could not be interpreted as a number.")
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def set_v_max(self, v_max):
        if v_max is None:
            self._v_max = None
            return
        try:
            self._v_max = sympify(v_max)
            float(self._v_max.evalf())
        except TypeError:
            raise ValueError("v_max could not be interpreted as a number.")
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _interpret_args(args):
        interval_wrong_order = "PlotInterval %s was given before any function(s)."
        interpret_error = "Could not interpret %s as a function or interval."

        functions, intervals = [], []
        if isinstance(args[0], GeometryEntity):
            for coords in list(args[0].arbitrary_point()):
                functions.append(coords)
            intervals.append(PlotInterval.try_parse(args[0].plot_interval()))
        else:
            for a in args:
                i = PlotInterval.try_parse(a)
                if i is not None:
                    if len(functions) == 0:
                        raise ValueError(interval_wrong_order % (str(i)))
                    else:
                        intervals.append(i)
                else:
                    if is_sequence(a, include=str):
                        raise ValueError(interpret_error % (str(a)))
                    try:
                        f = sympify(a)
                        functions.append(f)
                    except TypeError:
                        raise ValueError(interpret_error % str(a))

        return functions, intervals
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(self, expr, var_start_end, **kwargs):
        super(LineOver1DRangeSeries, self).__init__()
        self.expr = sympify(expr)
        self.label = str(self.expr)
        self.var = sympify(var_start_end[0])
        self.start = float(var_start_end[1])
        self.end = float(var_start_end[2])
        self.nb_of_points = kwargs.get('nb_of_points', 300)
        self.adaptive = kwargs.get('adaptive', True)
        self.depth = kwargs.get('depth', 12)
        self.line_color = kwargs.get('line_color', None)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs):
        super(Parametric3DLineSeries, self).__init__()
        self.expr_x = sympify(expr_x)
        self.expr_y = sympify(expr_y)
        self.expr_z = sympify(expr_z)
        self.label = "(%s, %s)" % (str(self.expr_x), str(self.expr_y))
        self.var = sympify(var_start_end[0])
        self.start = float(var_start_end[1])
        self.end = float(var_start_end[2])
        self.nb_of_points = kwargs.get('nb_of_points', 300)
        self.line_color = kwargs.get('line_color', None)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs):
        super(SurfaceOver2DRangeSeries, self).__init__()
        self.expr = sympify(expr)
        self.var_x = sympify(var_start_end_x[0])
        self.start_x = float(var_start_end_x[1])
        self.end_x = float(var_start_end_x[2])
        self.var_y = sympify(var_start_end_y[0])
        self.start_y = float(var_start_end_y[1])
        self.end_y = float(var_start_end_y[2])
        self.nb_of_points_x = kwargs.get('nb_of_points_x', 50)
        self.nb_of_points_y = kwargs.get('nb_of_points_y', 50)
        self.surface_color = kwargs.get('surface_color', None)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(self, expr, var_start_end_x, var_start_end_y):
        super(ContourSeries, self).__init__()
        self.nb_of_points_x = 50
        self.nb_of_points_y = 50
        self.expr = sympify(expr)
        self.var_x = sympify(var_start_end_x[0])
        self.start_x = float(var_start_end_x[1])
        self.end_x = float(var_start_end_x[2])
        self.var_y = sympify(var_start_end_y[0])
        self.start_y = float(var_start_end_y[1])
        self.end_y = float(var_start_end_y[2])

        self.get_points = self.get_meshes
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _sympify_qubit_map(mapping):
    new_map = {}
    for key in mapping:
        new_map[key] = sympify(mapping[key])
    return new_map
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def targets(self):
        """A tuple of target qubits."""
        return sympify(tuple(range(self.args[0])))

    #-------------------------------------------------------------------------
    # Apply
    #-------------------------------------------------------------------------