Esempio n. 1
0
def prove(Eq):
    p = Symbol.p(complex=True)    
    n = Symbol.n(domain=Interval(1, oo, integer=True))
    x = Symbol.x(shape=(n,), given=True, complex=True)
    y = Symbol.y(shape=(n,), given=True, complex=True)
    k = Symbol.k(domain=Interval(1, oo, integer=True))
    
    given = Equality(x @ LAMBDA[k:n](p ** k), y @ LAMBDA[k:n](p ** k))
    
    Eq << apply(given)
    Eq << algebre.vector.cosine_similarity.apply(*given.lhs.args)
    Eq << algebre.vector.cosine_similarity.apply(*given.rhs.args)
    
    Eq << given.subs(Eq[-1], Eq[-2])
    
    Eq << matmul_equality.apply(Eq[-1])
Esempio n. 2
0
def apply(given):
    assert given.is_Equality
    lhs, rhs = given.args
    
    assert lhs.is_MatMul
    x, p_polynomial = lhs.args
    
    assert rhs.is_MatMul
    y, _p_polynomial = rhs.args
    
    assert p_polynomial == _p_polynomial
    
    assert p_polynomial.is_LAMBDA
    assert p_polynomial.shape == x.shape == y.shape    
    assert len(p_polynomial.shape) == 1
#     n = p_polynomial.shape[0]
    k = p_polynomial.variable
    polynomial = p_polynomial.function
    assert polynomial.is_Power
    
    b, e = polynomial.as_base_exp()    
    assert not b.has(k)
    assert e.as_poly(k).degree() == 1
    
    return Equality(x, y, given=given)
Esempio n. 3
0
def apply(given, i=None, j=None, w=None):
    assert given.is_Equality
    x_set_comprehension, interval = given.args
    n = interval.max() + 1
    assert interval.min() == 0
    assert len(x_set_comprehension.limits) == 1
    k, a, b = x_set_comprehension.limits[0]
    assert b - a == n - 1
    x = LAMBDA(x_set_comprehension.function.arg,
               *x_set_comprehension.limits).simplify()

    if j is None:
        j = Symbol.j(domain=[0, n - 1], integer=True, given=True)

    if i is None:
        i = Symbol.i(domain=[0, n - 1], integer=True, given=True)

    assert j >= 0 and j < n
    assert i >= 0 and i < n

    index = index_function(n)
    if w is None:
        _i = Symbol.i(integer=True)
        _j = Symbol.j(integer=True)
        w = Symbol.w(definition=LAMBDA[_j:n, _i:n](Swap(n, _i, _j)))

    return Equality(index[i](w[index[i](x[:n]), index[j](x[:n])] @ x[:n]),
                    index[j](x[:n]),
                    given=given)
Esempio n. 4
0
def apply(given):
    assert given.is_Equality
    assert given.lhs.is_Intersection and given.rhs.is_Union or given.lhs.is_Union and given.rhs.is_Intersection
    A, B = given.lhs.args
    _A, _B = given.rhs.args
    assert A == _A and B == _B
    return Equality(A, B, given=given)
Esempio n. 5
0
def test_core_relational():
    x = Symbol("x")
    y = Symbol("y")
    for c in (Equality, Equality(x,y), Inequality, Inequality(x,y), Relational,
              Relational(x,y), StrictInequality, StrictInequality(x,y), Unequality,
              Unequality(x,y)):
        check(c)
Esempio n. 6
0
def apply(m, n=1):
    m = sympify(m)
    n = sympify(n)

    x = Symbol.x(real=True)
    return Equality(Integral[x:0:S.Pi / 2](cos(x)**(m - 1) * sin(x)**(n - 1)),
                    beta(m / 2, n / 2) / 2)
Esempio n. 7
0
def apply(given, excludes=None):
    assert given.is_Equality
    x_union_abs, x_abs_sum = given.args
    if not x_union_abs.is_Abs:
        tmp = x_union_abs
        x_union_abs = x_abs_sum
        x_abs_sum = tmp
        assert x_union_abs.is_Abs

    x_union = x_union_abs.arg
    assert x_union.is_UNION
    if x_abs_sum.is_Sum:
        assert x_abs_sum.function.is_Abs
        assert x_abs_sum.function.arg == x_union.function
    else:
        assert x_abs_sum == summation(abs(x_union.function), *x_union.limits)

    limits_dict = x_union.limits_dict
    i, *_ = limits_dict.keys()
    xi = x_union.function
    kwargs = i._assumptions.copy()
    if 'domain' in kwargs:
        del kwargs['domain']

    j = xi.generate_free_symbol(excludes=excludes, **kwargs)
    xj = xi.subs(i, j)

    i_domain = limits_dict[i] or i.domain

    limits = [(j, i_domain - {i})] + [*x_union.limits]
    return ForAll(Equality(xi & xj, S.EmptySet).simplify(),
                  *limits,
                  given=given)
Esempio n. 8
0
def test_jl_matrixsymbol_slice3():
    A = MatrixSymbol('A', 8, 7)
    B = MatrixSymbol('B', 2, 2)
    C = MatrixSymbol('C', 4, 2)
    name_expr = ("test", [Equality(B, A[6:, 1::3]),
                          Equality(C, A[::2, ::3])])
    result, = codegen(name_expr, "Julia", header=False, empty=False)
    source = result[1]
    expected = (
        "function test(A)\n"
        "    B = A[7:end,2:3:end]\n"
        "    C = A[1:2:end,1:3:end]\n"
        "    return B, C\n"
        "end\n"
    )
    assert source == expected
Esempio n. 9
0
def _common_new(cls, function, *symbols, **assumptions):
    """Return either a special return value or the tuple,
    (function, limits, orientation). This code is common to
    both ExprWithLimits and AddWithLimits."""
    function = sympify(function)

    if isinstance(function, Equality):
        # This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y))
        # but that is only valid for definite integrals.
        limits, orientation = _process_limits(*symbols)
        if not (limits and all(len(limit) == 3 for limit in limits)):
            SymPyDeprecationWarning(
                feature='Integral(Eq(x, y))',
                useinstead='Eq(Integral(x, z), Integral(y, z))',
                issue=18053,
                deprecated_since_version=1.6,
            ).warn()

        lhs = function.lhs
        rhs = function.rhs
        return Equality(cls(lhs, *symbols, **assumptions), \
                        cls(rhs, *symbols, **assumptions))

    if function is S.NaN:
        return S.NaN

    if symbols:
        limits, orientation = _process_limits(*symbols)
        for i, li in enumerate(limits):
            if len(li) == 4:
                function = function.subs(li[0], li[-1])
                limits[i] = Tuple(*li[:-1])
    else:
        # symbol not provided -- we can still try to compute a general form
        free = function.free_symbols
        if len(free) != 1:
            raise ValueError("specify dummy variables for %s" % function)
        limits, orientation = [Tuple(s) for s in free], 1

    # denest any nested calls
    while cls == type(function):
        limits = list(function.limits) + limits
        function = function.function

    # Any embedded piecewise functions need to be brought out to the
    # top level. We only fold Piecewise that contain the integration
    # variable.
    reps = {}
    symbols_of_integration = {i[0] for i in limits}
    for p in function.atoms(Piecewise):
        if not p.has(*symbols_of_integration):
            reps[p] = Dummy()
    # mask off those that don't
    function = function.xreplace(reps)
    # do the fold
    function = piecewise_fold(function)
    # remove the masking
    function = function.xreplace({v: k for k, v in reps.items()})

    return function, limits, orientation
Esempio n. 10
0
def apply(given, i=None, j=None):
    assert given.is_Equality
    x_set_comprehension, interval = given.args
    n = interval.max() + 1
    assert interval.min() == 0
    assert len(x_set_comprehension.limits) == 1
    k, a, b = x_set_comprehension.limits[0]
    assert b - a == n - 1
    x = LAMBDA(x_set_comprehension.function.arg,
               *x_set_comprehension.limits).simplify()

    if j is None:
        j = Symbol.j(domain=[0, n - 1], integer=True, given=True)

    if i is None:
        i = Symbol.i(domain=[0, n - 1], integer=True, given=True)

    assert j >= 0 and j < n
    assert i >= 0 and i < n

    index = index_function(n)

    di = index[i](x[:n])
    dj = index[j](x[:n])

    return Equality(KroneckerDelta(di, dj), KroneckerDelta(i, j), given=given)
Esempio n. 11
0
def apply(n, u, v):
    Q, w, x = predefined_symbols(n)
    X, index = X_definition(n, w, x)
    return ForAll[x[:n +
                    1]:Q[u]](Contains(X[v], Q[v])
                             & Equality(x[:n +
                                          1], w[n, index[u](X[v])] @ X[v]))
Esempio n. 12
0
def apply(given):   
    assert given.is_Unequality
    A_det, zero = given.args
    assert A_det.is_Determinant
    assert zero.is_zero
    A = A_det.arg
    return Equality(Cofactors(A).T / Determinant(A), Inverse(A), given=given)
Esempio n. 13
0
    def subs(self, *args, **kwargs):
        if len(args) == 1:
            eq, *_ = args
            if isinstance(eq, Equality):
                args = eq.args
                return self.func(self.lhs._subs(*args, **kwargs),
                                 self.rhs._subs(*args, **kwargs),
                                 equivalent=[self, eq])
            if isinstance(eq, Subset):
                A, B = self.args
                _A, _B = eq.args
                if A == _A and _B == B:
                    return Equality(A, B, equivalent=[self, eq])
            if isinstance(eq, Supset):
                A, B = self.args
                _B, _A = eq.args
                if A == _A and _B == B:
                    return Equality(A, B, equivalent=[self, eq])

            return self
        old, new = args
        new = _sympify(new)

        if self.plausible:

            lhs, rhs = self.lhs._subs(old, new), self.rhs._subs(old, new)
            if hasattr(new, 'has') and new.has(old):
                eq = self.func(lhs, rhs, substituent=self)
            else:
                eq = self.func(lhs, rhs, given=self)
            derivative = self.derivative
            if derivative is None:
                derivative = {}
                self.derivative = derivative

            if old not in derivative:
                derivative[old] = {}

            derivative[old][new] = eq
            return eq

        if old.is_symbol and new in old.domain:
            lhs = self.lhs._subs(old, new)
            rhs = self.rhs._subs(old, new)
            return self.func(lhs, rhs, given=self)

        return self
Esempio n. 14
0
def prove(Eq):
    n = Symbol.n(domain=Interval(2, oo, integer=True))
    S = Symbol.S(dtype=dtype.integer * n)

    x = Symbol.x(**S.element_symbol().dtype.dict)

    i = Symbol.i(integer=True)
    j = Symbol.j(integer=True)

    given = ForAll(
        Contains(
            LAMBDA[i:n](Piecewise((x[0], Equality(i, j)),
                                  (x[j], Equality(i, 0)), (x[i], True))), S),
        (j, 1, n - 1), (x, S))

    Eq << apply(given)

    w = Eq[0].lhs.base

    Eq << swap1.utility.apply(x, w[0])

    Eq << Eq[-1].reference(*Eq[-1].limits)

    Eq.given = Eq[1].subs(Eq[-1].reversed)

    Eq << axiom.algebre.matrix.elementary.swap.identity.apply(x, w)

    Eq << Eq[-1].subs(Eq[-1].rhs.args[0].indices[0], 0)

    Eq << Eq[-1].this.lhs.limits_subs(Eq[-1].lhs.variable, i)

    Eq << Eq[-1].this.lhs.function.indices[0].args[1].limits_subs(
        Eq[-1].lhs.function.indices[0].args[1].variable, i)

    Eq << Eq[-1].subs(Eq[-1].rhs.args[0].indices[1], j)

    Eq.given = Eq.given.subs(Eq[-1])

    Eq << Eq.given.limits_swap()

    Eq << ForAll[x:S](Eq[-1].function.subs(j, 0), plausible=True)

    Eq << Eq[-1].subs(w[0, 0].this.definition)

    Eq <<= Eq[-1] & Eq[-2]

    Eq << combinatorics.permutation.adjacent.swap2.contains.apply(Eq[-1])
Esempio n. 15
0
def apply(n, m, b):
    i = Symbol.i(integer=True)

    return Equality(
        Concatenate(
            Concatenate(MatProduct[i:m](Swap(n, i, b[i])), ZeroMatrix(n)).T,
            Concatenate(ZeroMatrix(n), 1)).T,
        MatProduct[i:m](Swap(n + 1, i, b[i])))
Esempio n. 16
0
def apply(n, d):
    Q = Symbol.Q(shape=(n, d), real=True)
    K = Symbol.K(shape=(n, d), real=True)
    V = Symbol.V(shape=(n, d), real=True)

    S = Symbol.S(shape=(n, d), definition=softmax(Q @ K.T / sympy.sqrt(d)) @ V)

    return Equality(S[0], softmax(Q[0] @ K.T / sympy.sqrt(d)) @ V)
Esempio n. 17
0
def apply(x):
    n = x.shape[0]
    i = Symbol.i(domain=Interval(0, n - 1, integer=True))
    j = Symbol.j(domain=Interval(0, n - 1, integer=True))
    
    w = Symbol.w(integer=True, shape=(n, n, n, n), definition=LAMBDA[j, i](Swap(n, i, j)))
    
    return Equality(x @ w[i, j] @ w[i, j], x)
Esempio n. 18
0
def test_core_relational():
    x = Symbol("x")
    y = Symbol("y")
    for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y),
              LessThan, LessThan(x, y), Relational, Relational(x, y),
              StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan,
              StrictLessThan(x, y), Unequality, Unequality(x, y)):
        check(c)
Esempio n. 19
0
def apply(given):
    assert given.is_Equality
    S_abs, one = given.args

    assert S_abs.is_Abs and one == 1
    S = S_abs.arg
    x = S.element_symbol()
    return Exists(Equality(x.set, S), (x, ), given=given)
Esempio n. 20
0
def apply(n):
    i = Symbol.i(integer=True)
    j = Symbol.j(integer=True)

    return Equality(
        Concatenate(
            Concatenate(Swap(n, i, j), ZeroMatrix(n)).T,
            Concatenate(ZeroMatrix(n), 1)), Swap(n + 1, i, j))
Esempio n. 21
0
def prove(Eq):
    x = Symbol.x(real=True)
    a = Symbol.a(real=True)
    b = Symbol.b(real=True)
    Eq << apply(Unequal(x, 0), Equality(x * a, b))

    Eq << Eq[1] / x
    Eq << (Eq[-1] & Eq[0]).split()
Esempio n. 22
0
def test_Equivalent():
    assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A)
    assert Equivalent() is true
    assert Equivalent(A, A) == Equivalent(A) is true
    assert Equivalent(True, True) == Equivalent(False, False) is true
    assert Equivalent(True, False) == Equivalent(False, True) is false
    assert Equivalent(A, True) == A
    assert Equivalent(A, False) == Not(A)
    assert Equivalent(A, B, True) == A & B
    assert Equivalent(A, B, False) == ~A & ~B
    assert Equivalent(1, A) == A
    assert Equivalent(0, A) == Not(A)
    assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C)
    assert Equivalent(A < 1, A >= 1) is false
    assert Equivalent(A < 1, A >= 1, 0) is false
    assert Equivalent(A < 1, A >= 1, 1) is false
    assert Equivalent(A < 1, S(1) > A) == Equivalent(1, 1) == Equivalent(0, 0)
    assert Equivalent(Equality(A, B), Equality(B, A)) is true
Esempio n. 23
0
def prove(Eq):
    n = Symbol.n(integer=True)
    S = Symbol.A(dtype=dtype.integer * n)

    Eq << apply(Equality(Abs(S), 1))

    Eq << sets.equality.imply.exists_equality.apply(Eq[0]).reversed

    Eq << Eq[1].subs(Eq[-1])
Esempio n. 24
0
def prove(Eq):
    A = Symbol.A(dtype=dtype.integer, given=True)
    B = Symbol.B(dtype=dtype.integer, given=True)

    Eq << apply(Equality(B - A, EmptySet()))

    Eq << Eq[0].union(A).reversed

    Eq << Eq[1].subs(Eq[-1])
Esempio n. 25
0
def apply(w):
    n = w.shape[0]
    i = w.generate_free_symbol(integer=True)
    j = w.generate_free_symbol({i}, integer=True)
    
    assert len(w.shape) == 4 and all(s == n for s in w.shape)
    assert w[i, j].is_Swap or w[i, j].definition.is_Swap 
    
    return Equality(w[i, j], w[j, i])
Esempio n. 26
0
def test_m_matrixsymbol_slice():
    A = MatrixSymbol('A', 2, 3)
    B = MatrixSymbol('B', 1, 3)
    C = MatrixSymbol('C', 1, 3)
    D = MatrixSymbol('D', 2, 1)
    name_expr = ("test", [
        Equality(B, A[0, :]),
        Equality(C, A[1, :]),
        Equality(D, A[:, 2])
    ])
    result, = codegen(name_expr, "Octave", header=False, empty=False)
    source = result[1]
    expected = ("function [B, C, D] = test(A)\n"
                "  B = A(1, :);\n"
                "  C = A(2, :);\n"
                "  D = A(:, 3);\n"
                "end\n")
    assert source == expected
Esempio n. 27
0
def test_results_named_unordered():
    # Here output order is based on name_expr
    A, B, C = symbols('A,B,C')
    expr1 = Equality(C, (x + y)*z)
    expr2 = Equality(A, (x - y)*z)
    expr3 = Equality(B, 2*x)
    name_expr = ("test", [expr1, expr2, expr3])
    result, = codegen(name_expr, "Julia", header=False, empty=False)
    source = result[1]
    expected = (
        "function test(x, y, z)\n"
        "    C = z.*(x + y)\n"
        "    A = z.*(x - y)\n"
        "    B = 2*x\n"
        "    return C, A, B\n"
        "end\n"
    )
    assert source == expected
Esempio n. 28
0
def apply(given):
    assert given.is_Equality
    A, B = given.args
    if B != 0:
        A = B
    assert A.is_Abs
    A = A.arg

    return Equality(A, S.EmptySet, given=given)
Esempio n. 29
0
def test_jl_output_arg_mixed_unordered():
    # named outputs are alphabetical, unnamed output appear in the given order
    from sympy.functions.elementary.trigonometric import (cos, sin)
    a = symbols("a")
    name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
    result, = codegen(name_expr, "Julia", header=False, empty=False)
    assert result[0] == "foo.jl"
    source = result[1];
    expected = (
        'function foo(x)\n'
        '    out1 = cos(2*x)\n'
        '    y = sin(x)\n'
        '    out3 = cos(x)\n'
        '    a = sin(2*x)\n'
        '    return out1, y, out3, a\n'
        'end\n'
    )
    assert source == expected
Esempio n. 30
0
def apply(a, b):
    n = a.shape[0]

    i = Symbol.i(integer=True)
    j = Symbol.j(integer=True)

    return Equality(
        Det(LAMBDA[j:n, i:n](a[Min(i, j)] * b[Max(i, j)])),
        a[0] * b[n - 1] * Product(a[i] * b[i - 1] - a[i - 1] * b[i],
                                  (i, 1, n - 1)))