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

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

项目:cobrame    作者:SBRG    | 项目源码 | 文件源码
def _fix_type(value):
    """convert possible types to str, float, and bool"""
    # Because numpy floats can not be pickled to json
    if isinstance(value, string_types):
        return str(value)
    if isinstance(value, float_):
        return float(value)
    if isinstance(value, bool_):
        return bool(value)
    if isinstance(value, set):
        return list(value)
    if isinstance(value, Basic):
        return str(value)
    if hasattr(value, 'id'):
        return str(value.id)
    # if value is None:
    #     return ''
    return value
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_Tuple():
    t = (1, 2, 3, 4)
    st = Tuple(*t)
    assert set(sympify(t)) == set(st)
    assert len(t) == len(st)
    assert set(sympify(t[:2])) == set(st[:2])
    assert isinstance(st[:], Tuple)
    assert st == Tuple(1, 2, 3, 4)
    assert st.func(*st.args) == st
    p, q, r, s = symbols('p q r s')
    t2 = (p, q, r, s)
    st2 = Tuple(*t2)
    assert st2.atoms() == set(t2)
    assert st == st2.subs({p: 1, q: 2, r: 3, s: 4})
    # issue 5505
    assert all(isinstance(arg, Basic) for arg in st.args)
    assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1)
    assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1))

    assert Tuple(t2) == Tuple(Tuple(*t2))
    assert Tuple.fromiter(t2) == Tuple(*t2)
    assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3)
    assert st2.fromiter(st2.args) == st2
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.args = args
        self.f, self.gradient = None, ColorGradient()

        if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]):
            self.f = args[0]
        elif len(args) == 1 and isinstance(args[0], str):
            if args[0] in default_color_schemes:
                cs = default_color_schemes[args[0]]
                self.f, self.gradient = cs.f, cs.gradient.copy()
            else:
                self.f = lambdify('x,y,z,u,v', args[0])
        else:
            self.f, self.gradient = self._interpret_args(args, kwargs)
        self._test_color_function()
        if not isinstance(self.gradient, ColorGradient):
            raise ValueError("Color gradient not properly initialized. "
                             "(Not a ColorGradient instance.)")
项目:qiskit-sdk-py    作者:QISKit    | 项目源码 | 文件源码
def __init__(self, name, param, arg, circuit=None):
        """Create a new instruction.

        name = instruction name string
        param = list of real parameters
        arg = list of pairs (Register, index)
        circuit = QuantumCircuit or CompositeGate containing this instruction
        """
        for i in arg:
            if not isinstance(i[0], Register):
                raise QISKitError("argument not (Register, int) tuple")
        self.name = name
        self.param = []
        for p in param:
            if not isinstance(p, Basic):
                # if item in param not symbolic, make it symbolic
                self.param.append(Number(p))
            else:
                self.param.append(p)
        self.arg = arg
        self.control = None  # tuple (ClassicalRegister, int) for "if"
        self.circuit = circuit
项目:QuantEcon.lectures.code    作者:QuantEcon    | 项目源码 | 文件源码
def __init__(self, output, params):
        """
        Create an instance of the Solow growth model.

        Parameters
        ----------
        output : sym.Basic
            Symbolic expression defining the aggregate production
            function.
        params : dict
            Dictionary of model parameters.

        """
        self.irf = impulse_response.ImpulseResponse(self)
        self.output = output
        self.params = params
项目:QuantEcon.lectures.code    作者:QuantEcon    | 项目源码 | 文件源码
def marginal_product_capital(self):
        r"""
        Symbolic expression for the marginal product of capital (per
        unit effective labor).

        :getter: Return the current marginal product of capital (per
        unit effective labor).
        :type: sym.Basic

        Notes
        -----
        The marginal product of capital is defined as follows:

        .. math::

            \frac{\partial F(K, AL)}{\partial K} \equiv f'(k)

        where :math:`k=K/AL` is capital stock (per unit effective labor)

        """
        return sym.diff(self.intensive_output, k)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_Tuple():
    t = (1, 2, 3, 4)
    st = Tuple(*t)
    assert set(sympify(t)) == set(st)
    assert len(t) == len(st)
    assert set(sympify(t[:2])) == set(st[:2])
    assert isinstance(st[:], Tuple)
    assert st == Tuple(1, 2, 3, 4)
    assert st.func(*st.args) == st
    p, q, r, s = symbols('p q r s')
    t2 = (p, q, r, s)
    st2 = Tuple(*t2)
    assert st2.atoms() == set(t2)
    assert st == st2.subs({p: 1, q: 2, r: 3, s: 4})
    # issue 5505
    assert all(isinstance(arg, Basic) for arg in st.args)
    assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1)
    assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1))

    assert Tuple(t2) == Tuple(Tuple(*t2))
    assert Tuple.fromiter(t2) == Tuple(*t2)
    assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3)
    assert st2.fromiter(st2.args) == st2
项目:cobrame    作者:SBRG    | 项目源码 | 文件源码
def save_json_me(me0, file_name):
    """
    Save a stripped-down JSON version of the ME-model. This will exclude all of
    ME-Model information except the reaction stoichiometry information and the
    reaction bounds. Saving/loading a model in this format will thus occur much
    quicker, but limit the ability to edit the model and use most of its
    features.

    :param :class:`~cobrame.core.model.MEModel` me0:
        A full ME-model

    :param str or file-like object file_name:
        Filename of the JSON output

    :returns JSON-object:
        Stripped-down JSON representation of full ME-model
    """
    me = copy.deepcopy(me0)

    for rxn in me.reactions:
        for met in rxn.metabolites:
            s = rxn._metabolites[met]
            if isinstance(s, Basic):
                rxn._metabolites[met] = str(s)
        if isinstance(rxn.lower_bound, Basic):
            rxn.lower_bound = str(rxn.lower_bound)
        if isinstance(rxn.upper_bound, Basic):
            rxn.upper_bound = str(rxn.upper_bound)

    for met in me.metabolites:
        if isinstance(met._bound, Basic):
            met._bound = str(met._bound)

    save_json_model(me, file_name)
项目:cobrame    作者:SBRG    | 项目源码 | 文件源码
def eval_reaction_at_growth_rate(reaction, growth_rate):
    for key, value in reaction._metabolites.items():
        if isinstance(value, Basic):
            reaction._metabolites[key] = value.subs(cobrame.mu, growth_rate)
        if isinstance(reaction, cobrame.TranslationReaction) and \
                (isinstance(key, cobrame.Ribosome) or
                 isinstance(key, cobrame.TranscribedGene)):
            reaction._metabolites[key] = 0.
        if isinstance(reaction, cobrame.TranscriptionReaction) and \
                isinstance(key, cobrame.RNAP):
            reaction._metabolites[key] = 0.
    return reaction
项目:cobrame    作者:SBRG    | 项目源码 | 文件源码
def _compile(expr, variable=mu):
    """compiles a sympy expression"""
    return lambdify(variable, expr) if isinstance(expr, Basic) else expr
项目:cobrame    作者:SBRG    | 项目源码 | 文件源码
def compile_expressions(me_model, variable=mu):
    """compiles symbolic expressions of mu to functions

    The compiled expressions dict has the following key value pairs:
    (met_index, rxn_index): stoichiometry,
    (None, rxn_index): (lower_bound, upper_bound)
    (met_index, None): (met_bound, met_constraint_sense)

    """
    expressions = {}
    for i, r in enumerate(me_model.reactions):
        # stoichiometry
        for met, stoic in iteritems(r._metabolites):
            if isinstance(stoic, Basic):
                expressions[(me_model.metabolites.index(met), i)] = \
                    lambdify(variable, stoic)
        # If either the lower or upper reaction bounds are symbolic
        if isinstance(r.lower_bound, Basic) or \
                isinstance(r.upper_bound, Basic):
            expressions[(None, i)] = (_compile(r.lower_bound, variable),
                                      _compile(r.upper_bound, variable))
    # Metabolite bound
    for i, metabolite in enumerate(me_model.metabolites):
        if isinstance(metabolite._bound, Basic):
            expressions[(i, None)] = (_compile(metabolite._bound, variable),
                                      metabolite._constraint_sense)
    return expressions
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_Dict():
    x, y, z = symbols('x y z')
    d = Dict({x: 1, y: 2, z: 3})
    assert d[x] == 1
    assert d[y] == 2
    raises(KeyError, lambda: d[2])
    assert len(d) == 3
    assert set(d.keys()) == set((x, y, z))
    assert set(d.values()) == set((S(1), S(2), S(3)))
    assert d.get(5, 'default') == 'default'
    assert x in d and z in d and not 5 in d
    assert d.has(x) and d.has(1)  # SymPy Basic .has method

    # Test input types
    # input - a python dict
    # input - items as args - SymPy style
    assert (Dict({x: 1, y: 2, z: 3}) ==
            Dict((x, 1), (y, 2), (z, 3)))

    raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3))))
    with raises(NotImplementedError):
        d[5] = 6  # assert immutability

    assert set(
        d.items()) == set((Tuple(x, S(1)), Tuple(y, S(2)), Tuple(z, S(3))))
    assert set(d) == set([x, y, z])
    assert str(d) == '{x: 1, y: 2, z: 3}'
    assert d.__repr__() == '{x: 1, y: 2, z: 3}'

    # Test creating a Dict from a Dict.
    d = Dict({x: 1, y: 2, z: 3})
    assert d == Dict(d)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _test_args(obj):
    return all(isinstance(arg, Basic) for arg in obj.args)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_sympy__core__basic__Basic():
    from sympy.core.basic import Basic
    assert _test_args(Basic())
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_simple_variables():
    rl = rewriterule(Basic(x, 1), Basic(x, 2), variables=(x,))
    assert list(rl(Basic(3, 1))) == [Basic(3, 2)]

    rl = rewriterule(x**2, x**3, variables=(x,))
    assert list(rl(y**2)) == [y**3]
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def doit(self, **hints):
        arg = self.arg
        if hints.get('deep', True) and isinstance(arg, Basic):
            arg = arg.doit(**hints)
        try:
            result = arg._eval_transpose()
            return result if result is not None else Transpose(arg)
        except AttributeError:
            return Transpose(arg)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_matadd_sympify():
    assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_purestr():
    assert purestr(Symbol('x')) == "Symbol(x)"
    assert purestr(Basic(1, 2)) == "Basic(1, 2)"
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _print_slice(self, expr, **kwargs):
        return slice(*[self._print(i, **kwargs)
                        if isinstance(i, sympy.Basic) else i
                        for i in (expr.start, expr.stop, expr.step)])
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def check_expression(expr, var_symbols):
    """Does eval(expr) both in Sage and SymPy and does other checks."""

    # evaluate the expression in the context of Sage:
    if var_symbols:
        sage.var(var_symbols)
    a = globals().copy()
    # safety checks...
    assert not "sin" in a
    a.update(sage.__dict__)
    assert "sin" in a
    e_sage = eval(expr, a)
    assert not isinstance(e_sage, sympy.Basic)

    # evaluate the expression in the context of SymPy:
    if var_symbols:
        sympy.var(var_symbols)
    b = globals().copy()
    assert not "sin" in b
    b.update(sympy.__dict__)
    assert "sin" in b
    b.update(sympy.__dict__)
    e_sympy = eval(expr, b)
    assert isinstance(e_sympy, sympy.Basic)

    # Do the actual checks:
    assert sympy.S(e_sage) == e_sympy
    assert e_sage == sage.SR(e_sympy)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_top_down_easy():
    expr     = Basic(1, 2)
    expected = Basic(2, 3)
    brl = top_down(inc)

    assert set(brl(expr)) == set([expected])
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_top_down_big_tree():
    expr     = Basic(1, Basic(2), Basic(3, Basic(4), 5))
    expected = Basic(2, Basic(3), Basic(4, Basic(5), 6))
    brl = top_down(inc)

    assert set(brl(expr)) == set([expected])
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_top_down_harder_function():
    def split5(x):
        if x == 5:
            yield x - 1
            yield x + 1

    expr     = Basic(Basic(5, 6), 1)
    expected = set([Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)])
    brl = top_down(split5)

    assert set(brl(expr)) == expected
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_zero_ints():
    expr = Basic(2, Basic(5, 3), 8)
    expected = set([Basic(0, Basic(0, 0), 0)])

    brl = canon(posdec)
    assert set(brl(expr)) == expected
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_split5():
    expr = Basic(2, Basic(5,  3), 8)
    expected = set([Basic(0, Basic(0,  0), 10),
                 Basic(0, Basic(10, 0), 10)])

    brl = canon(branch5)
    assert set(brl(expr)) == expected
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_subs():
    from sympy import symbols
    a,b,c,d,e,f = symbols('a,b,c,d,e,f')
    mapping = {a: d, d: a, Basic(e): Basic(f)}
    expr   = Basic(a, Basic(b, c), Basic(d, Basic(e)))
    result = Basic(d, Basic(b, c), Basic(a, Basic(f)))
    assert subs(mapping)(expr) == result
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_subs_empty():
    assert subs({})(Basic(1, 2)) == Basic(1, 2)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_typed():
    class A(Basic):
        pass
    class B(Basic):
        pass
    rmzeros = rm_id(lambda x: x == 0)
    rmones  = rm_id(lambda x: x == 1)
    remove_something = typed({A: rmzeros, B: rmones})

    assert remove_something(A(0, 1)) == A(1)
    assert remove_something(B(0, 1)) == B(0)
项目:qiskit-sdk-py    作者:QISKit    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, Basic):  # The element to serialize is a Symbolic type
            if obj.is_Integer: return int(obj)
            if obj.is_Float: return float(obj)
            return str(obj)
        else:
            return json.JSONEncoder.default(self, obj)
项目:QuantEcon.lectures.code    作者:QuantEcon    | 项目源码 | 文件源码
def test_validate_output():
    """Testing validation of output attribute."""
    # output must have type sym.Basic
    with nose.tools.assert_raises(AttributeError):
        solow.Model(output=invalid_output_1, params=valid_params)

    # output must be function of K, A, L
    with nose.tools.assert_raises(AttributeError):
        solow.Model(output=invalid_output_2, params=valid_params)
项目:QuantEcon.lectures.code    作者:QuantEcon    | 项目源码 | 文件源码
def solow_residual(self):
        """
        Symbolic expression for the Solow residual which is used as a
        measure of technology.

        :getter: Return the symbolic expression.
        :type: sym.Basic

        """
        return sym.solve(Y - self.output, A)[0]
项目:QuantEcon.lectures.code    作者:QuantEcon    | 项目源码 | 文件源码
def _validate_output(self, output):
        """Validate the production function."""
        if not isinstance(output, sym.Basic):
            mesg = ("Output must be an instance of {}.".format(sym.Basic))
            raise AttributeError(mesg)
        elif not ({A, K, L} < output.atoms()):
            mesg = ("Output must be an expression of technology, 'A', " +
                    "capital, 'K', and labor, 'L'.")
            raise AttributeError(mesg)
        else:
            return output
项目:QuantEcon.lectures.code    作者:QuantEcon    | 项目源码 | 文件源码
def solow_residual(self):
        """
        Symbolic expression for the Solow residual which is used as a measure
        of technology.

        :getter: Return the symbolic expression.
        :type: sym.Basic

        """
        rho = (sigma - 1) / sigma
        residual = (((1 / (1 - alpha)) * (Y / L)**rho -
                     (alpha / (1 - alpha)) * (K / L)**rho)**(1 / rho))
        return residual
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_simple():
    rl = rewriterule(Basic(p, 1), Basic(p, 2), variables=(p,))
    assert list(rl(Basic(3, 1))) == [Basic(3, 2)]

    p1 = p**2
    p2 = p**3
    rl = rewriterule(p1, p2, variables=(p,))

    expr = x**2
    assert list(rl(expr)) == [x**3]
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_simple_variables():
    rl = rewriterule(Basic(x, 1), Basic(x, 2), variables=(x,))
    assert list(rl(Basic(3, 1))) == [Basic(3, 2)]

    rl = rewriterule(x**2, x**3, variables=(x,))
    assert list(rl(y**2)) == [y**3]
项目: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 doit(self, **hints):
        arg = self.arg
        if hints.get('deep', True) and isinstance(arg, Basic):
            arg = arg.doit(**hints)
        try:
            result = arg._eval_transpose()
            return result if result is not None else Transpose(arg)
        except AttributeError:
            return Transpose(arg)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_matadd_sympify():
    assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_purestr():
    assert purestr(Symbol('x')) == "Symbol(x)"
    assert purestr(Basic(1, 2)) == "Basic(1, 2)"
项目: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'}
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def _print_slice(self, expr, **kwargs):
        return slice(*[self._print(i, **kwargs)
                        if isinstance(i, sympy.Basic) else i
                        for i in (expr.start, expr.stop, expr.step)])
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_top_down_easy():
    expr     = Basic(1, 2)
    expected = Basic(2, 3)
    brl = top_down(inc)

    assert set(brl(expr)) == {expected}
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_top_down_big_tree():
    expr     = Basic(1, Basic(2), Basic(3, Basic(4), 5))
    expected = Basic(2, Basic(3), Basic(4, Basic(5), 6))
    brl = top_down(inc)

    assert set(brl(expr)) == {expected}
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_top_down_harder_function():
    def split5(x):
        if x == 5:
            yield x - 1
            yield x + 1

    expr     = Basic(Basic(5, 6), 1)
    expected = {Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)}
    brl = top_down(split5)

    assert set(brl(expr)) == expected
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_sall():
    expr     = Basic(1, 2)
    expected = Basic(2, 3)
    brl = sall(inc)

    assert list(brl(expr)) == [expected]

    expr     = Basic(1, 2, Basic(3, 4))
    expected = Basic(2, 3, Basic(3, 4))
    brl = sall(do_one(inc, identity))

    assert list(brl(expr)) == [expected]
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_zero_ints():
    expr = Basic(2, Basic(5, 3), 8)
    expected = {Basic(0, Basic(0, 0), 0)}

    brl = canon(posdec)
    assert set(brl(expr)) == expected
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_subs():
    from sympy import symbols
    a,b,c,d,e,f = symbols('a,b,c,d,e,f')
    mapping = {a: d, d: a, Basic(e): Basic(f)}
    expr   = Basic(a, Basic(b, c), Basic(d, Basic(e)))
    result = Basic(d, Basic(b, c), Basic(a, Basic(f)))
    assert subs(mapping)(expr) == result
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_subs_empty():
    assert subs({})(Basic(1, 2)) == Basic(1, 2)
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def test_typed():
    class A(Basic):
        pass
    class B(Basic):
        pass
    rmzeros = rm_id(lambda x: x == 0)
    rmones  = rm_id(lambda x: x == 1)
    remove_something = typed({A: rmzeros, B: rmones})

    assert remove_something(A(0, 1)) == A(1)
    assert remove_something(B(0, 1)) == B(0)
项目:chemcoord    作者:mcocdawc    | 项目源码 | 文件源码
def _sympy_formatter(self):
        def formatter(x):
            if (isinstance(x, sympy.Basic)):
                return '${}$'.format(sympy.latex(x))
            else:
                return x
        new = self.copy()
        for col in self.columns.drop('atom'):
            if self[col].dtype == np.dtype('O'):
                new._frame.loc[:, col] = self[col].apply(formatter)
        return new