예제 #1
0
    def visit(current_expr):
        if current_expr.is_Add:
            expr_max_length = max(len(current_expr.args), len(subexpression.args))
            normalized_current_expr_match = normalize_match_parameter(required_match_original, expr_max_length)
            expr_coefficients = current_expr.as_coefficients_dict()
            subexpression_coefficient_dict = subexpression.as_coefficients_dict()
            intersection = set(subexpression_coefficient_dict.keys()).intersection(set(expr_coefficients))
            if len(intersection) >= max(normalized_replacement_match, normalized_current_expr_match):
                # find common factor
                factors = defaultdict(int)
                skips = 0
                for common_symbol in subexpression_coefficient_dict.keys():
                    if common_symbol not in expr_coefficients:
                        skips += 1
                        continue
                    factor = expr_coefficients[common_symbol] / subexpression_coefficient_dict[common_symbol]
                    factors[sp.simplify(factor)] += 1

                common_factor = max(factors.items(), key=operator.itemgetter(1))[0]
                if factors[common_factor] >= max(normalized_current_expr_match, normalized_replacement_match):
                    return current_expr - common_factor * subexpression + common_factor * replacement

        # if no subexpression was found
        param_list = [visit(a) for a in current_expr.args]
        if not param_list:
            return current_expr
        else:
            if current_expr.func == sp.Mul and Zero() in param_list:
                return Zero()
            else:
                return current_expr.func(*param_list, evaluate=False)
예제 #2
0
def find_simple_recurrence(v, A=Function('a'), N=Symbol('n')):
    """
    Detects and returns a recurrence relation from a sequence of several integer
    (or rational) terms. The name of the function in the returned expression is
    'a' by default; the main variable is 'n' by default. The smallest index in
    the returned expression is always n (and never n-1, n-2, etc.).

    Examples
    ========

    >>> from sympy.concrete.guess import find_simple_recurrence
    >>> from sympy import fibonacci
    >>> find_simple_recurrence([fibonacci(k) for k in range(12)])
    -a(n) - a(n + 1) + a(n + 2)

    >>> from sympy import Function, Symbol
    >>> a = [1, 1, 1]
    >>> for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
    >>> find_simple_recurrence(a, A=Function('f'), N=Symbol('i'))
    -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3)

    """
    p = find_simple_recurrence_vector(v)
    n = len(p)
    if n <= 1: return Zero()

    rel = Zero()
    for k in range(n):
        rel += A(N + n - 1 - k) * p[k]

    return rel
예제 #3
0
    def update_dynamics(self):
        eqs = dict(self.rhs())
        keys = set(eqs.keys())
        symvars = [getattr(self, v) for v in self.vars]
        if keys <= set(self.nodes):
            # by node
            dep = flatten(zip(*symvars))
            expr = flatten(sym.Matrix([eqs[node] for node in self]))
        elif keys <= set(self.vars):
            # by variable
            dep = it.chain.from_iterable(symvars)
            expr = flatten(sym.Matrix([eqs[v] for v in self.vars]))
        else:
            raise ValueError(
                "rhs must map either nodes to rhs or variables to rhs")

        dep_expr = [(d, e + Zero()) for d, e in zip(dep, expr)]
        if any(expr == sym.nan for _, expr in dep_expr):
            raise ValueError(
                "At least one rhs expression is NaN. Missing parameters?")

        self._sys = SymbolicSys(dep_expr, self.t)
        if self.use_native:
            self._native_sys = native_sys[self.integrator].from_other(
                self._sys)

        self._stale_dynamics = False
예제 #4
0
파일: test_ops.py 프로젝트: gyc567/devito
    def test_create_ops_dat_function(self):
        grid = Grid(shape=(4))

        u = Function(name='u', grid=grid, space_order=2)

        block = OpsBlock('block')

        name_to_ops_dat = {}

        result = create_ops_dat(u, name_to_ops_dat, block)

        assert name_to_ops_dat['u'].name == namespace['ops_dat_name'](u.name)
        assert name_to_ops_dat['u']._C_typename == namespace['ops_dat_type']

        assert result[0].expr.lhs.name == namespace['ops_dat_dim'](u.name)
        assert result[0].expr.rhs.params == (Integer(4), )

        assert result[1].expr.lhs.name == namespace['ops_dat_base'](u.name)
        assert result[1].expr.rhs.params == (Zero(), )

        assert result[2].expr.lhs.name == namespace['ops_dat_d_p'](u.name)
        assert result[2].expr.rhs.params == (Integer(2), )

        assert result[3].expr.lhs.name == namespace['ops_dat_d_m'](u.name)
        assert result[3].expr.rhs.params == (Integer(-2), )

        assert result[4].expr.lhs == name_to_ops_dat['u']
        assert type(result[4].expr.rhs) == namespace['ops_decl_dat']
        assert result[4].expr.rhs.args == (
            block, 1, Symbol(namespace['ops_dat_dim'](u.name)),
            Symbol(namespace['ops_dat_base'](u.name)),
            Symbol(namespace['ops_dat_d_m'](u.name)),
            Symbol(namespace['ops_dat_d_p'](u.name)), Byref(u.indexify(
                (0, ))), Literal('"%s"' % u._C_typedata), Literal('"u"'))
예제 #5
0
def test_core_numbers():
    for c in (Catalan, Catalan(), ComplexInfinity, ComplexInfinity(),
              EulerGamma, EulerGamma(), Exp1, Exp1(), GoldenRatio, GoldenRatio(),
              Half, Half(), ImaginaryUnit, ImaginaryUnit(), Infinity, Infinity(),
              Integer, Integer(2), NaN, NaN(), NegativeInfinity,
              NegativeInfinity(), NegativeOne, NegativeOne(), Number, Number(15),
              NumberSymbol, NumberSymbol(), One, One(), Pi, Pi(), Rational,
              Rational(1,2), Real, Real("1.2"), Zero, Zero()):
        check(c)
예제 #6
0
def evaluateAdd(expr):
    newargs = []
    for arg in expr.args:
        if isinstance(arg, Mul):
            arg = evaluateMul(arg)
        elif isinstance(arg, Add):
            arg = evaluateAdd(arg)
        elif isinstance(arg, D):
            arg = Zero()
        else:
            pass
        newargs.append(arg)
    return Add(*newargs)
예제 #7
0
def evaluateExpr(expr):
    if isinstance(expr, Matrix):
        for i, elem in enumerate(expr):
            elem = elem.expand()
            expr[i] = evaluateExpr(elem)
        return expr
    expr = expr.expand()
    if isinstance(expr, Mul):
        expr = evaluateMul(expr)
    elif isinstance(expr, Add):
        expr = evaluateAdd(expr)
    elif isinstance(expr, D):
        expr = Zero()
    return expr
예제 #8
0
def sym_predict_proba_parts__calibrated_classifier(estimator):
    if hasattr(estimator.base_estimator, 'decision_function'):
        inner_pred = sym_decision_function(estimator.base_estimator)
    elif hasattr(estimator.base_estimator, 'predict_proba'):
        inner_pred = sym_predict_proba(estimator.base_estimator)
    result = Zero()
    var = None
    for cal in estimator.calibrators_:
        variables = syms(cal)
        if len(variables) != 1 or (var != variables[0] and var is not None):
            raise ValueError()
        var = variables[0]
        result += sym_predict(cal)
    result = result / RealNumber(len(estimator.calibrators_))
    return ((var, ), [result], (syms(estimator.base_estimato), inner_pred,
                                None))
예제 #9
0
def sym_predict_proba__calibrated_classifier(estimator):
    if hasattr(estimator.base_estimator, 'decision_function'):
        inner_pred = sym_decision_function(estimator.base_estimator)
    elif hasattr(estimator.base_estimator, 'predict_proba'):
        inner_pred = sym_predict_proba(estimator.base_estimator)


#     inner_pred = fallback(sym_decision_function, sym_predict_proba)(estimator.base_estimator)
    result = Zero()
    for cal in estimator.calibrators_:
        variables = syms(cal)
        if len(variables) != 1:
            raise ValueError()
        var = variables[0]
        result += sym_predict(cal).subs({var: inner_pred})
    return result / RealNumber(len(estimator.calibrators_))
예제 #10
0
def evaluateMul(expr):
    end = 0
    if expr.args <> ():
        if isinstance(expr.args[-1], D):
            return Zero()
    for i in range(len(expr.args) - 1 + end, -1, -1):
        arg = expr.args[i]
        if isinstance(arg, Add):
            arg = evaluateAdd(arg)
        elif isinstance(arg, Mul):
            arg = evaluateMul(arg)
        elif isinstance(arg, D):
            left = Mul(*expr.args[:i])
            right = Mul(*expr.args[i + 1:])
            right = mydiff(right, *arg.variables)
            ans = left * right
            return evaluateMul(ans)
        else:
            pass
    return expr
예제 #11
0
def sym_predict_zero_estimator(estimator):
    return Zero()
예제 #12
0
def create_ops_dat(f, name_to_ops_dat, block):
    ndim = f.ndim - (1 if f.is_TimeFunction else 0)

    dim = Array(name=namespace['ops_dat_dim'](f.name),
                dimensions=(DefaultDimension(name='dim',
                                             default_value=ndim), ),
                dtype=np.int32,
                scope='stack')
    base = Array(name=namespace['ops_dat_base'](f.name),
                 dimensions=(DefaultDimension(name='base',
                                              default_value=ndim), ),
                 dtype=np.int32,
                 scope='stack')
    d_p = Array(name=namespace['ops_dat_d_p'](f.name),
                dimensions=(DefaultDimension(name='d_p',
                                             default_value=ndim), ),
                dtype=np.int32,
                scope='stack')
    d_m = Array(name=namespace['ops_dat_d_m'](f.name),
                dimensions=(DefaultDimension(name='d_m',
                                             default_value=ndim), ),
                dtype=np.int32,
                scope='stack')

    base_val = [Zero() for i in range(ndim)]

    # If f is a TimeFunction we need to create a ops_dat for each time stepping
    # variable (eg: t1, t2)
    if f.is_TimeFunction:
        time_pos = f._time_position
        time_index = f.indices[time_pos]
        time_dims = f.shape[time_pos]

        dim_val = f.shape[:time_pos] + f.shape[time_pos + 1:]
        d_p_val = f._size_nodomain.left[time_pos + 1:]
        d_m_val = [-i for i in f._size_nodomain.right[time_pos + 1:]]

        ops_dat_array = Array(name=namespace['ops_dat_name'](f.name),
                              dimensions=(DefaultDimension(
                                  name='dat', default_value=time_dims), ),
                              dtype=namespace['ops_dat_type'],
                              scope='stack')

        dat_decls = []
        for i in range(time_dims):
            name = '%s%s%s' % (f.name, time_index, i)

            dat_decls.append(namespace['ops_decl_dat'](block, 1,
                                                       Symbol(dim.name),
                                                       Symbol(base.name),
                                                       Symbol(d_m.name),
                                                       Symbol(d_p.name),
                                                       Byref(f.indexify([i])),
                                                       Literal('"%s"' %
                                                               f._C_typedata),
                                                       Literal('"%s"' % name)))

        ops_decl_dat = Expression(
            ClusterizedEq(Eq(ops_dat_array, ListInitializer(dat_decls))))

        # Inserting the ops_dat array in case of TimeFunction.
        name_to_ops_dat[f.name] = ops_dat_array

    else:
        ops_dat = OpsDat("%s_dat" % f.name)
        name_to_ops_dat[f.name] = ops_dat

        dim_val = f.shape
        d_p_val = f._size_nodomain.left
        d_m_val = [-i for i in f._size_nodomain.right]

        ops_decl_dat = Expression(
            ClusterizedEq(
                Eq(
                    ops_dat,
                    namespace['ops_decl_dat'](block, 1, Symbol(dim.name),
                                              Symbol(base.name),
                                              Symbol(d_m.name),
                                              Symbol(d_p.name),
                                              Byref(f.indexify([0])),
                                              Literal('"%s"' % f._C_typedata),
                                              Literal('"%s"' % f.name)))))

    dim_val = Expression(ClusterizedEq(Eq(dim, ListInitializer(dim_val))))
    base_val = Expression(ClusterizedEq(Eq(base, ListInitializer(base_val))))
    d_p_val = Expression(ClusterizedEq(Eq(d_p, ListInitializer(d_p_val))))
    d_m_val = Expression(ClusterizedEq(Eq(d_m, ListInitializer(d_m_val))))

    return OpsDatDecl(dim_val=dim_val,
                      base_val=base_val,
                      d_p_val=d_p_val,
                      d_m_val=d_m_val,
                      ops_decl_dat=ops_decl_dat)
예제 #13
0
파일: test_args.py 프로젝트: Visheshk/sympy
def test_sympy__core__numbers__Zero():
    from sympy.core.numbers import Zero
    assert _test_args(Zero())
예제 #14
0
    def test_create_ops_dat_function(self):
        grid = Grid(shape=(4))

        u = Function(name='u', grid=grid, space_order=2)

        block = OpsBlock('block')

        name_to_ops_dat = {}

        result = create_ops_dat(u, name_to_ops_dat, block)

        assert name_to_ops_dat['u'].name == namespace['ops_dat_name'](u.name)
        assert name_to_ops_dat['u']._C_typename == namespace['ops_dat_type']

        assert result[0].expr.lhs.name == namespace['ops_dat_dim'](u.name)
        assert result[0].expr.rhs.params == (Integer(4), )

        assert result[1].expr.lhs.name == namespace['ops_dat_base'](u.name)
        assert result[1].expr.rhs.params == (Zero(), )

        assert result[2].expr.lhs.name == namespace['ops_dat_d_p'](u.name)
        assert result[2].expr.rhs.params == (Integer(2), )

        assert result[3].expr.lhs.name == namespace['ops_dat_d_m'](u.name)
        assert result[3].expr.rhs.params == (Integer(-2), )

        assert result[4].expr.lhs == name_to_ops_dat['u']
        assert result[4].expr.rhs.name == namespace['ops_decl_dat'].name
        assert result[4].expr.rhs.args == (
            block, 1, Symbol(namespace['ops_dat_dim'](u.name)),
            Symbol(namespace['ops_dat_base'](u.name)),
            Symbol(namespace['ops_dat_d_m'](u.name)),
            Symbol(namespace['ops_dat_d_p'](u.name)), Byref(u.indexify(
                (0, ))), Literal('"%s"' % u._C_typedata), Literal('"u"'))

        def test_create_ops_arg_constant(self):
            a = Constant(name='*a')

            res = create_ops_arg(a, {}, {})

            assert res.name == namespace['ops_arg_gbl'].name
            assert res.args == [
                Byref(Constant(name='a')), 1,
                Literal('"%s"' % dtype_to_cstr(a.dtype)), namespace['ops_read']
            ]

        @pytest.mark.parametrize('read', [True, False])
        def test_create_ops_arg_function(self, read):
            u = OpsAccessible('u', np.float32, read)

            dat = OpsDat('u_dat')
            stencil = OpsStencil('stencil')

            res = create_ops_arg(u, {'u': dat}, {u: stencil})

            assert res.name == namespace['ops_arg_dat'].name
            assert res.args == [
                dat, 1, stencil,
                Literal('"%s"' % dtype_to_cstr(u.dtype)),
                namespace['ops_read'] if read else namespace['ops_write']
            ]
예제 #15
0
 def sym_transform(self, xlabels):
     arg = self.arg.sym_transform(xlabels)
     return Piecewise((Zero(), Eq(arg, Zero())), (One(), True))
예제 #16
0
파일: resist.py 프로젝트: riteme/toys
def calc(n, start, end, E, generate_dot=False):
    """Calculate the resistance of a network.
    A node represent a crossroads of electric lines,
    each segment has a resistance

    Parameters:
    n     (int): the number of nodes in the network, which are
        labelled from 1 to n.
    start (int): the node with input current.
    end   (int): the node with output current.
    E (list[(u, v, r)]): network data. (u, v, r) represent
        a segment between u and v with a resistance of r.

    Flags:
    generate_dot (bool, False): If set to True, this function will return
        the result in dot script for analysis.

    Return values:
    (sympy.core.numbers.Rational / str)
    the resistance of the network represented in rational.
    When `generate_dot` is set, return str instead.
    """

    start, end = start - 1, end - 1

    # Set up a graph, whose edges are bidirectional.
    # Each pair of directed edge has different coefficients (1 and -1).
    G = [[] for i in range(n)]
    for i in range(len(E)):
        u, v, r = E[i]
        u, v = u - 1, v - 1
        s = sym('I' + str(i))
        G[u].append((v, 1, r, s))
        G[v].append((u, -1, r, s))

    # Set up equations.
    A = []
    for v in range(n - 1):
        if v == start:
            eq = One()
        elif v == end:
            eq = -One()
        else:
            eq = Zero()

        for u, f, r, s in G[v]:
            eq -= f * s

        A.append(eq)

    father, depth = [None] * n, [0] * n

    def dfs(A, G, father, tm, x):
        for v, f, r, s in G[x]:
            if s == father[x][3]:
                continue
            if depth[v] and depth[v] < depth[x]:
                eq, u = f * r * s, x
                while u != v:
                    u, f1, r1, s1 = father[u]
                    eq += f1 * r1 * s1
                A.append(eq)
            elif not depth[v]:
                father[v] = (x, f, r, s)
                depth[v] = depth[x] + 1
                dfs(A, G, father, depth, v)

    # Solve it.
    father[start], depth[start] = (0, ) * 4, 1
    dfs(A, G, father, depth, start)
    sol = solve(A)

    # Calculate the resistance.
    ret, x = 0, end
    while x != start:
        x, f, r, s = father[x]
        ret += f * r * sol[s]

    if generate_dot:
        buf = ['digraph {', '    rankdir = "LR";']

        buf.append('    r [shape = rectangle, label = "%sΩ"];' % ret)
        for i in range(1, n + 1):
            if i == start + 1:
                c = 'green'
            elif i == end + 1:
                c = 'red'
            else:
                c = 'blue'

            buf.append('    %s [shape = point, color = %s];' % (i, c))

        for u in range(1, n + 1):
            for v, f, r, s in G[u - 1]:
                if f < 0:
                    continue

                I, v = sol[s], v + 1
                if I < 0:
                    e = '%s -> %s [' % (v, u)
                elif I > 0:
                    e = '%s -> %s [' % (u, v)
                else:
                    e = '%s -> %s [arrowhead = none, ' % (u, v)

                buf.append('    %slabel = "%sA,%sΩ"];' % (e, abs(I), r))

        buf += '}'
        return '\n'.join(buf)
    else:
        return ret
예제 #17
0
 def sym_transform(self, xlabels):
     left = self.left.sym_transform(xlabels)
     right = self.right.sym_transform(xlabels)
     return Piecewise((One(), left >= right), (Zero(), True))
예제 #18
0
def create_ops_dat(f, name_to_ops_dat, block):
    ndim = f.ndim - (1 if f.is_TimeFunction else 0)

    dim = Array(name=namespace['ops_dat_dim'](f.name),
                dimensions=(DefaultDimension(name='dim',
                                             default_value=ndim), ),
                dtype=np.int32,
                scope='stack')
    base = Array(name=namespace['ops_dat_base'](f.name),
                 dimensions=(DefaultDimension(name='base',
                                              default_value=ndim), ),
                 dtype=np.int32,
                 scope='stack')
    d_p = Array(name=namespace['ops_dat_d_p'](f.name),
                dimensions=(DefaultDimension(name='d_p',
                                             default_value=ndim), ),
                dtype=np.int32,
                scope='stack')
    d_m = Array(name=namespace['ops_dat_d_m'](f.name),
                dimensions=(DefaultDimension(name='d_m',
                                             default_value=ndim), ),
                dtype=np.int32,
                scope='stack')

    res = []
    base_val = [Zero() for i in range(ndim)]

    # If f is a TimeFunction we need to create a ops_dat for each time stepping
    # variable (eg: t1, t2)
    if f.is_TimeFunction:
        time_pos = f._time_position
        time_index = f.indices[time_pos]
        time_dims = f.shape[time_pos]

        dim_shape = sympify(f.shape[:time_pos] + f.shape[time_pos + 1:])
        padding = f.padding[:time_pos] + f.padding[time_pos + 1:]
        halo = f.halo[:time_pos] + f.halo[time_pos + 1:]
        d_p_val = tuple(sympify([p[0] + h[0] for p, h in zip(padding, halo)]))
        d_m_val = tuple(
            sympify([-(p[1] + h[1]) for p, h in zip(padding, halo)]))

        ops_dat_array = Array(name=namespace['ops_dat_name'](f.name),
                              dimensions=(DefaultDimension(
                                  name='dat', default_value=time_dims), ),
                              dtype='ops_dat',
                              scope='stack')

        dat_decls = []
        for i in range(time_dims):
            name = '%s%s%s' % (f.name, time_index, i)
            name_to_ops_dat[name] = ops_dat_array.indexify(
                [Symbol('%s%s' % (time_index, i))])
            dat_decls.append(namespace['ops_decl_dat'](block, 1,
                                                       Symbol(dim.name),
                                                       Symbol(base.name),
                                                       Symbol(d_m.name),
                                                       Symbol(d_p.name),
                                                       Byref(f.indexify([i])),
                                                       Literal('"%s"' %
                                                               f._C_typedata),
                                                       Literal('"%s"' % name)))

        ops_decl_dat = Expression(
            ClusterizedEq(Eq(ops_dat_array, ListInitializer(dat_decls))))
    else:
        ops_dat = OpsDat("%s_dat" % f.name)
        name_to_ops_dat[f.name] = ops_dat

        d_p_val = tuple(
            sympify([p[0] + h[0] for p, h in zip(f.padding, f.halo)]))
        d_m_val = tuple(
            sympify([-(p[1] + h[1]) for p, h in zip(f.padding, f.halo)]))
        dim_shape = sympify(f.shape)

        ops_decl_dat = Expression(
            ClusterizedEq(
                Eq(
                    ops_dat,
                    namespace['ops_decl_dat'](block, 1, Symbol(dim.name),
                                              Symbol(base.name),
                                              Symbol(d_m.name),
                                              Symbol(d_p.name),
                                              Byref(f.indexify([0])),
                                              Literal('"%s"' % f._C_typedata),
                                              Literal('"%s"' % f.name)))))

    res.append(Expression(ClusterizedEq(Eq(dim, ListInitializer(dim_shape)))))
    res.append(Expression(ClusterizedEq(Eq(base, ListInitializer(base_val)))))
    res.append(Expression(ClusterizedEq(Eq(d_p, ListInitializer(d_p_val)))))
    res.append(Expression(ClusterizedEq(Eq(d_m, ListInitializer(d_m_val)))))
    res.append(ops_decl_dat)

    return res