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

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

项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_func_args():
    class MyClass(Expr):
        # A class with nontrivial .func

        def __init__(self, *args):
            self.my_member = ""

        @property
        def func(self):
            def my_func(*args):
                obj = MyClass(*args)
                obj.my_member = self.my_member
                return obj
            return my_func

    x = MyClass()
    x.my_member = "A very important value"
    assert x.my_member == refine(x).my_member
项目:simupy    作者:sixpearls    | 项目源码 | 文件源码
def output_equation(self, output_equation):
        if isinstance(output_equation, sp.Expr):
            output_equation = Array([output_equation])
        if output_equation is None and self.dim_state == 0:
            output_equation = empty_array()
        else:
            if output_equation is None:
                output_equation = self.state

            assert output_equation.atoms(sp.Symbol) <= (
                    set(self.constants_values.keys())
                    | set([dynamicsymbols._t])
                   )

            if self.dim_state:
                assert find_dynamicsymbols(output_equation) <= set(self.state)
            else:
                assert find_dynamicsymbols(output_equation) <= set(self.input)

        self.dim_output = len(output_equation)

        self._output_equation = output_equation
        self.update_output_equation_function()
项目:shenfun    作者:spectralDNS    | 项目源码 | 文件源码
def update_bcs(self, sympy_params={}, bc=None):
        if not sympy_params is {}:
            for i in range(2):
                if isinstance(self.bc[i], sympy.Expr):
                    self.bcs[i] = self.bc[i].evalf(subs=sympy_params)
            self.bcs_final[:] = self.bcs

        if bc is not None:
            assert isinstance(bc, (list, tuple))
            assert len(bc) == 2
            self.bc = list(bc)
            for i in range(2):
                if isinstance(bc[i], (Number, sympy.Expr, np.ndarray)) :
                    self.bcs[i] = bc[i]
                else:
                    raise NotImplementedError

            self.bcs_final[:] = self.bcs
项目:amphitrite    作者:cosine0    | 项目源码 | 文件源码
def resolve_expression(expression):
    if not isinstance(expression, sympy.Expr):
        return expression
    substitution = []
    for sym in expression.free_symbols:
        register = getattr(REG, sym.name.upper())
        value = getCurrentRegisterValue(register)
        substitution.append((sym, value))
    return int(expression.subs(substitution))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def sympy_to_numpy(m, **options):
    """Convert a sympy Matrix/complex number to a numpy matrix or scalar."""
    if not np:
        raise ImportError
    dtype = options.get('dtype', 'complex')
    if isinstance(m, Matrix):
        return np.matrix(m.tolist(), dtype=dtype)
    elif isinstance(m, Expr):
        if m.is_Number or m.is_NumberSymbol or m == I:
            return complex(m)
    raise TypeError('Expected Matrix or complex scalar, got: %r' % m)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def sympy_to_scipy_sparse(m, **options):
    """Convert a sympy Matrix/complex number to a numpy matrix or scalar."""
    if not np or not sparse:
        raise ImportError
    dtype = options.get('dtype', 'complex')
    if isinstance(m, Matrix):
        return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype))
    elif isinstance(m, Expr):
        if m.is_Number or m.is_NumberSymbol or m == I:
            return complex(m)
    raise TypeError('Expected Matrix or complex scalar, got: %r' % m)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def to_sympy(m, **options):
    """Convert a numpy/scipy.sparse matrix to a sympy matrix."""
    if isinstance(m, Matrix):
        return m
    elif isinstance(m, numpy_ndarray):
        return numpy_to_sympy(m)
    elif isinstance(m, scipy_sparse_matrix):
        return scipy_sparse_to_sympy(m)
    elif isinstance(m, Expr):
        return m
    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def to_scipy_sparse(m, **options):
    """Convert a sympy/numpy matrix to a scipy.sparse matrix."""
    dtype = options.get('dtype', 'complex')
    if isinstance(m, (Matrix, Expr)):
        return sympy_to_scipy_sparse(m, dtype=dtype)
    elif isinstance(m, numpy_ndarray):
        if not sparse:
            raise ImportError
        return sparse.csr_matrix(m)
    elif isinstance(m, scipy_sparse_matrix):
        return m
    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _sympy_to_scalar(e):
    """Convert from a sympy scalar to a Python scalar."""
    if isinstance(e, Expr):
        if e.is_Integer:
            return int(e)
        elif e.is_Float:
            return float(e)
        elif e.is_Rational:
            return float(e)
        elif e.is_Number or e.is_NumberSymbol or e == I:
            return complex(e)
    raise TypeError('Expected number, got: %r' % e)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_styleof():
    styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
              (Expr,  {'color': 'black'})]
    assert styleof(Basic(1), styles) == {'color': 'blue', 'shape': 'ellipse'}

    assert styleof(x + 1, styles) == {'color': 'black', 'shape': 'ellipse'}
项目:simupy    作者:sixpearls    | 项目源码 | 文件源码
def state(self, state):
        if state is None:  # or other checks?
            state = empty_array()
        if isinstance(state, sp.Expr):
            state = Array([state])
        self.dim_state = len(state)
        self._state = state
项目:simupy    作者:sixpearls    | 项目源码 | 文件源码
def input(self, input_):
        if input_ is None:  # or other checks?
            input_ = empty_array()
        if isinstance(input_, sp.Expr):  # check it's a single dynamicsymbol?
            input_ = Array([input_])
        self.dim_input = len(input_)
        self._inputs = input_
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_class_handler_registry():
    my_handler_registry = ClassFactRegistry()

    # The predicate doesn't matter here, so just use is_true
    fact1 = Equivalent(Q.is_true, AllArgs(Q.is_true))
    fact2 = Equivalent(Q.is_true, AnyArgs(Q.is_true))

    my_handler_registry[Mul] = {fact1}
    my_handler_registry[Expr] = {fact2}

    assert my_handler_registry[Basic] == set()
    assert my_handler_registry[Expr] == {fact2}
    assert my_handler_registry[Mul] == {fact1, fact2}
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_CheckOldAssump():
    # TODO: Make these tests more complete

    class Test1(Expr):
        def _eval_is_positive(self):
            return True
        def _eval_is_negative(self):
            return False

    class Test2(Expr):
        def _eval_is_finite(self):
            return True
        def _eval_is_positive(self):
            return True
        def _eval_is_negative(self):
            return False

    t1 = Test1()
    t2 = Test2()

    # We can't say if it's positive or negative in the old assumptions without
    # bounded. Remember, True means "no new knowledge", and
    # Q.positive(t2) means "t2 is positive."
    assert CheckOldAssump(Q.positive(t1)) == True
    assert CheckOldAssump(Q.negative(t1)) == ~Q.negative(t1)

    assert CheckOldAssump(Q.positive(t2)) == Q.positive(t2)
    assert CheckOldAssump(Q.negative(t2)) == ~Q.negative(t2)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def sympy_to_numpy(m, **options):
    """Convert a sympy Matrix/complex number to a numpy matrix or scalar."""
    if not np:
        raise ImportError
    dtype = options.get('dtype', 'complex')
    if isinstance(m, Matrix):
        return np.matrix(m.tolist(), dtype=dtype)
    elif isinstance(m, Expr):
        if m.is_Number or m.is_NumberSymbol or m == I:
            return complex(m)
    raise TypeError('Expected Matrix or complex scalar, got: %r' % m)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def sympy_to_scipy_sparse(m, **options):
    """Convert a sympy Matrix/complex number to a numpy matrix or scalar."""
    if not np or not sparse:
        raise ImportError
    dtype = options.get('dtype', 'complex')
    if isinstance(m, Matrix):
        return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype))
    elif isinstance(m, Expr):
        if m.is_Number or m.is_NumberSymbol or m == I:
            return complex(m)
    raise TypeError('Expected Matrix or complex scalar, got: %r' % m)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def to_numpy(m, **options):
    """Convert a sympy/scipy.sparse matrix to a numpy matrix."""
    dtype = options.get('dtype', 'complex')
    if isinstance(m, (Matrix, Expr)):
        return sympy_to_numpy(m, dtype=dtype)
    elif isinstance(m, numpy_ndarray):
        return m
    elif isinstance(m, scipy_sparse_matrix):
        return m.todense()
    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def to_scipy_sparse(m, **options):
    """Convert a sympy/numpy matrix to a scipy.sparse matrix."""
    dtype = options.get('dtype', 'complex')
    if isinstance(m, (Matrix, Expr)):
        return sympy_to_scipy_sparse(m, dtype=dtype)
    elif isinstance(m, numpy_ndarray):
        if not sparse:
            raise ImportError
        return sparse.csr_matrix(m)
    elif isinstance(m, scipy_sparse_matrix):
        return m
    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def _sympy_to_scalar(e):
    """Convert from a sympy scalar to a Python scalar."""
    if isinstance(e, Expr):
        if e.is_Integer:
            return int(e)
        elif e.is_Float:
            return float(e)
        elif e.is_Rational:
            return float(e)
        elif e.is_Number or e.is_NumberSymbol or e == I:
            return complex(e)
    raise TypeError('Expected number, got: %r' % e)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_styleof():
    styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
              (Expr,  {'color': 'black'})]
    assert styleof(Basic(1), styles) == {'color': 'blue', 'shape': 'ellipse'}

    assert styleof(x + 1, styles) == {'color': 'black', 'shape': 'ellipse'}
项目:fillygons    作者:Fillygons    | 项目源码 | 文件源码
def serialize_value(value):
    if isinstance(value, list):
        return '[{}]'.format(', '.join(map(serialize_value, value)))
    elif isinstance(value, expression):
        return value
    elif isinstance(value, Expr):
        return str(float(value))
    else:
        return json.dumps(value)
项目:vadouvan    作者:vadouvan    | 项目源码 | 文件源码
def __init__(
            self,
            root,
            outputs,
            inputs=None,
            name="unnamed_tree",
            ):
        self.root = copy.deepcopy(root)
        if not self.root.prototype.get("root"):
            raise vadouvan.exceptions.WDFError(
                "Attempted to use non-root node type '{}' as root of a "
                "WDFTree."
                .format(self.root.prototype["name"]))

        self.name = name

        if isinstance(outputs, numbers.Number):
            outputs = sympy.sympify(outputs)
        if isinstance(outputs, sympy.Expr):
            outputs = [("out", outputs)]
        self.outputs = collections.OrderedDict(outputs)

        actual_inputs_set = self._normalize_parameters_and_get_inputs()
        if inputs is None:
            self.inputs = sorted(list(actual_inputs_set))
        else:
            if set(inputs) != actual_inputs_set:
                raise vadouvan.exceptions.WDFError(
                    "Discrepancy between provided inputs list and tree"
                    " inputs.")
            self.inputs = inputs

        self._assign_names_to_unnamed_nodes()
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def rewriterule(source, target, variables=(), condition=None, assume=None):
    """ Rewrite rule

    Transform expressions that match source into expressions that match target
    treating all `variables` as wilds.

    >>> from sympy.abc import w, x, y, z
    >>> from sympy.unify.rewrite import rewriterule
    >>> from sympy.utilities import default_sort_key
    >>> rl = rewriterule(x + y, x**y, [x, y])
    >>> sorted(rl(z + 3), key=default_sort_key)
    [3**z, z**3]

    Use ``condition`` to specify additional requirements.  Inputs are taken in
    the same order as is found in variables.

    >>> rl = rewriterule(x + y, x**y, [x, y], lambda x, y: x.is_integer)
    >>> list(rl(z + 3))
    [3**z]

    Use ``assume`` to specify additional requirements using new assumptions.

    >>> from sympy.assumptions import Q
    >>> rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x))
    >>> list(rl(z + 3))
    [3**z]

    Assumptions for the local context are provided at rule runtime

    >>> list(rl(w + z, Q.integer(z)))
    [z**w]
    """

    def rewrite_rl(expr, assumptions=True):
        for match in unify(source, expr, {}, variables=variables):
            if (condition and
                not condition(*[match.get(var, var) for var in variables])):
                continue
            if (assume and not ask(assume.xreplace(match), assumptions)):
                continue
            expr2 = subs(match)(target)
            if isinstance(expr2, Expr):
                expr2 = rebuild(expr2)
            yield expr2
    return rewrite_rl
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def rewriterule(source, target, variables=(), condition=None, assume=None):
    """ Rewrite rule

    Transform expressions that match source into expressions that match target
    treating all `variables` as wilds.

    >>> from sympy.abc import w, x, y, z
    >>> from sympy.unify.rewrite import rewriterule
    >>> from sympy.utilities import default_sort_key
    >>> rl = rewriterule(x + y, x**y, [x, y])
    >>> sorted(rl(z + 3), key=default_sort_key)
    [3**z, z**3]

    Use ``condition`` to specify additional requirements.  Inputs are taken in
    the same order as is found in variables.

    >>> rl = rewriterule(x + y, x**y, [x, y], lambda x, y: x.is_integer)
    >>> list(rl(z + 3))
    [3**z]

    Use ``assume`` to specify additional requirements using new assumptions.

    >>> from sympy.assumptions import Q
    >>> rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x))
    >>> list(rl(z + 3))
    [3**z]

    Assumptions for the local context are provided at rule runtime

    >>> list(rl(w + z, Q.integer(z)))
    [z**w]
    """

    def rewrite_rl(expr, assumptions=True):
        for match in unify(source, expr, {}, variables=variables):
            if (condition and
                not condition(*[match.get(var, var) for var in variables])):
                continue
            if (assume and not ask(assume.xreplace(match), assumptions)):
                continue
            expr2 = subs(match)(target)
            if isinstance(expr2, Expr):
                expr2 = rebuild(expr2)
            yield expr2
    return rewrite_rl