Пример #1
0
    def build_from_float_array(self, name="fromArray", separator=", "):
        if self.base_ring == "float":
            return ""
        if not self.uniform_member_type:
            raise TypeError(
                "To generate an array constructor, GlslStruct must have members of\
                uniform type"
            )

        template = Template(
            """\
$type_name $fn_name(float X[$size]){
    return $type_name($array_members);
}"""
        )

        x = IndexedBase("X")
        array_members = separator.join(["{}({})".format(self.typed_name(SCALAR, self.base_ring), str(x[i])) for i in range(len(self))])
        return template.substitute(
            fn_name=name,
            type_name=self.type_name,
            base_type=self.uniform_member_type,
            array_members=array_members,
            size=len(self),
        )
Пример #2
0
 def initSyms(syms, deferred=False):
     sym_dict = {}
     if not isinstance(syms, list) and not isinstance(syms, set):
         syms = [syms]
     for sym in syms:
         sym_dict[sym] = symbols(sym) if not deferred else IndexedBase(sym)
     return sym_dict
Пример #3
0
def test_canonicalization_of_vectors_w_symm(free_alg):
    """Test the canonicalization when vectors are given (anti-)symmetries.
    """

    dr = free_alg
    p = dr.names
    x = IndexedBase('x')
    r = p.R
    i, j = p.i, p.j

    vs = Vec('vs')
    dr.set_symm(vs, Perm([1, 0]), valence=2)
    tensor = dr.sum((i, r), (j, r), x[i, j] * vs[j, i])
    res = tensor.simplify()
    assert res.n_terms == 1
    term = res.local_terms[0]
    assert term.sums == ((i, r), (j, r))
    assert term.amp == x[i, j]
    assert term.vecs == (vs[i, j], )

    va = Vec('va')
    dr.set_symm(va, Perm([1, 0], NEG), valence=2)
    tensor = dr.sum((i, r), (j, r), x[i, j] * va[j, i])
    res = tensor.simplify()
    assert res.n_terms == 1
    term = res.local_terms[0]
    assert term.sums == ((i, r), (j, r))
    assert term.amp == -x[i, j]
    assert term.vecs == (va[i, j], )
Пример #4
0
def test_IndexedBase_assumptions():
    i = Symbol('i', integer=True)
    a = Symbol('a')
    A = IndexedBase(a, positive=True)
    for c in (A, A[i]):
        assert c.is_real
        assert c.is_complex
        assert not c.is_imaginary
        assert c.is_nonnegative
        assert c.is_nonzero
        assert c.is_commutative
        assert log(exp(c)) == c

    assert A != IndexedBase(a)
    assert A == IndexedBase(a, positive=True, real=True)
    assert A[i] != Indexed(a, i)
Пример #5
0
def test_sum_instantiator():
    """Test use of Sum instantiator."""
    i = IdxSym('i')
    j = IdxSym('j')
    ket_i = BasisKet(FockIndex(i), hs=0)
    ket_j = BasisKet(FockIndex(j), hs=0)
    A_i = OperatorSymbol(StrLabel(IndexedBase('A')[i]), hs=0)
    hs0 = LocalSpace('0')

    sum = Sum(i)(ket_i)
    ful = KetIndexedSum(ket_i, ranges=IndexOverFockSpace(i, hs=hs0))
    assert sum == ful
    assert sum == Sum(i, hs0)(ket_i)
    assert sum == Sum(i, hs=hs0)(ket_i)

    sum = Sum(i, 1, 10)(ket_i)
    ful = KetIndexedSum(ket_i, ranges=IndexOverRange(i, 1, 10))
    assert sum == ful
    assert sum == Sum(i, 1, 10, 1)(ket_i)
    assert sum == Sum(i, 1, to=10, step=1)(ket_i)
    assert sum == Sum(i, 1, 10, step=1)(ket_i)

    sum = Sum(i, (1, 2, 3))(ket_i)
    ful = KetIndexedSum(ket_i, ranges=IndexOverList(i, (1, 2, 3)))
    assert sum == KetIndexedSum(ket_i, ranges=IndexOverList(i, (1, 2, 3)))
    assert sum == Sum(i, [1, 2, 3])(ket_i)

    sum = Sum(i)(Sum(j)(ket_i * ket_j.dag()))
    ful = OperatorIndexedSum(
        ket_i * ket_j.dag(),
        ranges=(IndexOverFockSpace(i, hs0), IndexOverFockSpace(j, hs0)),
    )
    assert sum == ful
Пример #6
0
def indexed_symbol(symbol, shape, idx_symbols):
    base = IndexedBase(symbol,
                       shape=tuple(s for s in shape if s > 1),
                       strides='C')
    index = tuple(idx_sym for idx, idx_sym in enumerate(idx_symbols)
                  if shape[idx] > 1)
    return IndexedEx(base, *index)
Пример #7
0
def test_MultivariateEwens():
    from sympy.stats.joint_rv_types import MultivariateEwens

    n, theta, i = symbols('n theta i', positive=True)

    # tests for integer dimensions
    theta_f = symbols('t_f', negative=True)
    a = symbols('a_1:4', positive=True, integer=True)
    ed = MultivariateEwens('E', 3, theta)
    assert density(ed)(a[0], a[1], a[2]) == Piecewise(
        (6 * 2**(-a[1]) * 3**(-a[2]) * theta**a[0] * theta**a[1] *
         theta**a[2] /
         (theta * (theta + 1) *
          (theta + 2) * factorial(a[0]) * factorial(a[1]) * factorial(a[2])),
         Eq(a[0] + 2 * a[1] + 3 * a[2], 3)), (0, True))
    assert marginal_distribution(ed, ed[1])(a[1]) == Piecewise(
        (6 * 2**(-a[1]) * theta**a[1] /
         ((theta + 1) * (theta + 2) * factorial(a[1])), Eq(2 * a[1] + 1, 3)),
        (0, True))
    raises(ValueError, lambda: MultivariateEwens('e1', 5, theta_f))

    # tests for symbolic dimensions
    eds = MultivariateEwens('E', n, theta)
    a = IndexedBase('a')
    j, k = symbols('j, k')
    den = Piecewise((factorial(n) *
                     Product(theta**a[j] * (j + 1)**(-a[j]) / factorial(a[j]),
                             (j, 0, n - 1)) / RisingFactorial(theta, n),
                     Eq(n, Sum((k + 1) * a[k], (k, 0, n - 1)))), (0, True))
    assert density(eds)(a).dummy_eq(den)
Пример #8
0
    def __init__(self, polynomials, variables):
        """
        A class that takes two lists, a list of polynomials and list of
        variables. Returns the Dixon matrix of the multivariate system.

        Parameters
        ----------
        polynomials : list of polynomials
            A  list of m n-degree polynomials
        variables: list
            A list of all n variables
        """
        self.polynomials = polynomials
        self.variables = variables

        self.n = len(self.variables)
        self.m = len(self.polynomials)

        a = IndexedBase("alpha")
        # A list of n alpha variables (the replacing variables)
        self.dummy_variables = [a[i] for i in range(self.n)]

        # A list of the d_max of each variable.
        self.max_degrees = [
            max(degree_list(poly)[i] for poly in self.polynomials)
            for i in range(self.n)
        ]
Пример #9
0
def partial_derivative_as_symbol(expr, name=None, dim=None):
    """Returns a Symbol from a partial derivative expression."""
    if not isinstance(expr, _partial_derivatives):
        raise TypeError('Expecting a partial derivative expression')

    index = get_index_derivatives(expr)
    var = get_atom_derivatives(expr)

    if not isinstance(var, (Symbol, Indexed)):
        print(type(var))
        raise TypeError('Expecting a Symbol, Indexed')

    code = ''
    for k, n in list(index.items()):
        code += k * n

    if var.is_Indexed:
        if name is None:
            name = var.base

        indices = ''.join('{}'.format(i) for i in var.indices)
        name = '{name}_{code}'.format(name=name, code=code)
        shape = None
        if dim:
            shape = [dim]
        return IndexedBase(name, shape=shape)[indices]

    else:
        if name is None:
            name = var.name

        name = '{name}_{code}'.format(name=name, code=code)
        return Symbol(name)
Пример #10
0
def g(v,w,i):
    from sympy import Lambda, Function ,symbols ,IndexedBase,Idx ,Max, Sum
    x = Function('x')
    i, n, j, dim, k =symbols('i, n, j, dim, k')
    v=IndexedBase('v')
    w=IndexedBase('w')
    net = Lambda((i, n, dim, k), Max(0.0, Sum(x(k)*w[n, k, i], (k, 0, dim-1))))
    dim = [10**4]*10
    index =[symbols('i%s'%m) for m in range(len(dim)+1)]
    y = [0]*len(dim)
    new = v[index[0]]
    for n in range(len(dim)):
        y[n] = net(index[n+1], n, dim[n], index[n])
        y[n] = y[n].subs(x(index[n]), new)
        new = y[n]
    return y[-1]
Пример #11
0
def test_Assignment():
    x, y = symbols("x, y")
    A = MatrixSymbol('A', 3, 1)
    mat = Matrix([1, 2, 3])
    B = IndexedBase('B')
    n = symbols("n", integer=True)
    i = Idx("i", n)
    # Here we just do things to show they don't error
    Assignment(x, y)
    Assignment(x, 0)
    Assignment(A, mat)
    Assignment(A[1, 0], 0)
    Assignment(A[1, 0], x)
    Assignment(B[i], x)
    Assignment(B[i], 0)
    a = Assignment(x, y)
    assert a.func(*a.args) == a
    # Here we test things to show that they error
    # Matrix to scalar
    raises(ValueError, lambda: Assignment(B[i], A))
    raises(ValueError, lambda: Assignment(B[i], mat))
    raises(ValueError, lambda: Assignment(x, mat))
    raises(ValueError, lambda: Assignment(x, A))
    raises(ValueError, lambda: Assignment(A[1, 0], mat))
    # Scalar to matrix
    raises(ValueError, lambda: Assignment(A, x))
    raises(ValueError, lambda: Assignment(A, 0))
    # Non-atomic lhs
    raises(TypeError, lambda: Assignment(mat, A))
    raises(TypeError, lambda: Assignment(0, x))
    raises(TypeError, lambda: Assignment(x * x, 1))
    raises(TypeError, lambda: Assignment(A + A, mat))
    raises(TypeError, lambda: Assignment(B, 0))

    assert Relational(x, y, ':=') == Assignment(x, y)
Пример #12
0
def test_qubit_state_bra():
    """Test  sum_i alpha_i <i| for TLS"""
    i = IdxSym('i')
    alpha = IndexedBase('alpha')
    alpha_i = alpha[i]
    hs_tls = LocalSpace('tls', basis=('g', 'e'))

    term = alpha_i * BasisKet(FockIndex(i), hs=hs_tls).dag()

    expr = KetIndexedSum.create(term, ranges=IndexOverFockSpace(i, hs=hs_tls))

    assert IndexOverFockSpace(i, hs=hs_tls) in expr.ket.kwargs['ranges']

    assert ascii(expr) == "Sum_{i in H_tls} alpha_i * <i|^(tls)"

    assert expr.ket.term.free_symbols == set([i, symbols('alpha'), alpha_i])
    assert expr.free_symbols == set([symbols('alpha'), alpha_i])
    assert expr.ket.variables == [i]
    assert expr.space == hs_tls
    assert len(expr.ket.args) == 1
    assert len(expr.ket.operands) == 1
    assert len(expr.ket.kwargs) == 1
    assert expr.ket.args[0] == term.ket
    assert expr.ket.term == term.ket
    assert len(expr.kwargs) == 0
    expr_expand = Bra.create(expr.ket.doit().substitute({
        alpha[0]: alpha['g'],
        alpha[1]: alpha['e']
    }))
    assert expr_expand == (alpha['g'] * BasisKet('g', hs=hs_tls).dag() +
                           alpha['e'] * BasisKet('e', hs=hs_tls).dag())
    assert ascii(expr_expand) == 'alpha_e * <e|^(tls) + alpha_g * <g|^(tls)'
Пример #13
0
def __deltaMContent(expr,
                    D,
                    gamma=IndexedBase('\gamma', integer=True, shape=1)):
    """
    Compute delta M^gamma contribution for the given compartment content expr.

    :param Expr expr: the content of the compartment, comprising Contents, ContentChanges, sums of those, and multiplication by integers
    :param int D: the number of species
    :param Expr gamma: optional symbol to use for gamma
    :return:
    """
    if expr.func == Compartment:
        content = expr.args[0]
        species = __getContentPerSpecies(content, D)
        return __mpow(species, gamma)
    elif expr == EmptySet:
        return 0
    elif expr.func == Integer:
        return expr
    elif expr.func == Add:
        return Add(*[__deltaMContent(i) for i in expr.args])
    elif expr.func == Mul:
        return Mul(*[__deltaMContent(i) for i in expr.args])
    else:
        raise TypeError("Unexpected expression " + str(expr))
def test_Subs_with_Indexed():
    A = IndexedBase("A")
    i, j, k = symbols("i,j,k")
    x, y, z = symbols("x,y,z")
    f = Function("f")

    assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1
    assert Subs(A[i], A[i], x).diff(A[i]) == 0
    assert Subs(A[i], A[i], x).diff(A[j]) == 0
    assert Subs(A[i], A[i], x).diff(x) == 1
    assert Subs(A[i], A[i], x).diff(y) == 0
    assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k)
    assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j)
    assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0
    assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k)
    assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i]
    assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j]

    assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i]
    assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j)
    assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j)
    assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j)
    assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k)
    assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i]

    assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0
    assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0
    assert Subs(A[i]*x, A[j], x).diff(A[i]) == x
    assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j)
    assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0
    assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k)
Пример #15
0
    def __add__(self, value):
        if isinstance(value, block):
            temp_tape = IndexedBase('temp_tape')
            new_computations = {}
            subs0 = [(tape_index, self.shift), (read_index, self.reads)]
            subs = []
            for index, compute in self.computations.items():
                compute = compute.subs(tape, temp_tape)
                if isinstance(compute, assign):
                    subs.append((index, compute.expr))
                else:
                    subs.append((index, compute.expr + index))

            for index, compute in value.computations.items():
                new_compute = compute.subs(subs0).subs(subs).subs(
                    temp_tape, tape)
                new_computations[index.subs(subs0)] = new_compute

            for index, compute in self.computations.items():
                if index not in new_computations:
                    new_computations[index] = compute
                else:
                    new_computations[index] = compute + new_computations[
                        index]  #adding not communitive

            new_shift = self.shift + value.shift - tape_index
            new_reads = self.reads + value.reads - read_index
            new_writes = self.writes + tuple(
                w.subs(subs0).subs(subs).subs(temp_tape, tape)
                for w in value.writes)
            return block(new_computations, new_shift, new_reads, new_writes)
        return NotImplemented
Пример #16
0
def test_Indexed_constructor():
    i, j = symbols('i j', integer=True)
    A = Indexed('A', i, j)
    assert A == Indexed(Symbol('A'), i, j)
    assert A == Indexed(IndexedBase('A'), i, j)
    raises(TypeError, lambda: Indexed(A, i, j))
    raises(IndexException, lambda: Indexed("A"))
Пример #17
0
def test_indexed_idx_sum():
    i = symbols('i', cls=Idx)
    r = Indexed('r', i)
    assert Sum(r,
               (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)])
    assert Product(r, (i, 0, 3)).doit() == prod(
        [r.xreplace({i: j}) for j in range(4)])

    j = symbols('j', integer=True)
    assert Sum(r, (i, j, j + 2)).doit() == sum(
        [r.xreplace({i: Idx(j + k)}) for k in range(3)])
    assert Product(r, (i, j, j + 2)).doit() == prod(
        [r.xreplace({i: Idx(j + k)}) for k in range(3)])

    k = Idx('k', range=(1, 3))
    A = IndexedBase('A')
    assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)])
    assert Product(A[k],
                   k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)])

    raises(ValueError, lambda: Sum(A[k], (k, 1, 4)))
    raises(ValueError, lambda: Sum(A[k], (k, 0, 3)))
    raises(ValueError, lambda: Sum(A[k], (k, 2, oo)))

    raises(ValueError, lambda: Product(A[k], (k, 1, 4)))
    raises(ValueError, lambda: Product(A[k], (k, 0, 3)))
    raises(ValueError, lambda: Product(A[k], (k, 2, oo)))
Пример #18
0
    def get_vev(self,h_tsr: Tensor):
        """Function to evaluate the expectation value of a normal
        ordered tensor 'h_tsr' with respect to the projected BCS
        ground state
            h_tsr = tensor whose VEV is to be evaluated
            Ntot = total number of orbitals available
        Note that here we follow the notation that Np = Number of Fermions and not number of pairs
        """
        ctan = self.cartan
        gam = IndexedBase(r'\gamma')

        def vev_of_term(term):
            """Return the VEV of a given term"""
            vecs = term.vecs
            t_amp = term.amp
            ind_list = []

            if len(vecs) == 0:
                return term
            elif all( v.base==ctan for v in vecs ):
                for i in vecs:
                    if set(i.indices).issubset(set(ind_list)):
                        t_amp = t_amp*2
                        # NOTE: This is only true when evaluating expectation over AGP,
                        # or any other seniority zero state
                    else:
                        ind_list.extend(list(i.indices))
            else:
                return []

            t_amp = t_amp*gam[ind_list]
            return [Term(sums=term.sums, amp = t_amp, vecs=())]

        return h_tsr.bind(vev_of_term)
Пример #19
0
def test_evaluate_symbolic_labels():
    """Test the behavior of the `substitute` method for evaluation of symbolic
    labels"""
    i, j = symbols('i j', cls=IdxSym)
    A = IndexedBase('A')

    lbl = FockIndex(i + j)
    assert lbl.substitute({i: 1, j: 2}) == 3
    assert lbl.substitute({i: 1}) == FockIndex(1 + j)
    assert lbl.substitute({j: 2}) == FockIndex(i + 2)
    assert lbl.substitute({i: 1}).substitute({j: 2}) == 3
    assert lbl.substitute({}) == lbl

    lbl = StrLabel(A[i, j])
    assert lbl.substitute({i: 1, j: 2}) == 'A_12'
    assert lbl.substitute({i: 1}) == StrLabel(A[1, j])
    assert lbl.substitute({j: 2}) == StrLabel(A[i, 2])
    assert lbl.substitute({i: 1}).substitute({j: 2}) == 'A_12'
    assert lbl.substitute({}) == lbl

    hs = SpinSpace('s', spin=3)
    lbl = SpinIndex(i + j, hs)
    assert lbl.substitute({i: 1, j: 2}) == '+3'
    assert lbl.substitute({i: 1}) == SpinIndex(1 + j, hs)
    assert lbl.substitute({j: 2}) == SpinIndex(i + 2, hs)
    assert lbl.substitute({i: 1}).substitute({j: 2}) == '+3'
    assert lbl.substitute({}) == lbl

    hs = SpinSpace('s', spin='3/2')
    lbl = SpinIndex((i + j) / 2, hs=hs)
    assert lbl.substitute({i: 1, j: 2}) == '+3/2'
    assert lbl.substitute({i: 1}) == SpinIndex((1 + j) / 2, hs)
    assert lbl.substitute({j: 2}) == SpinIndex((i + 2) / 2, hs)
    assert lbl.substitute({i: 1}).substitute({j: 2}) == '+3/2'
    assert lbl.substitute({}) == lbl
Пример #20
0
def test_tensors_can_be_substituted_scalars_simultaneously(
        free_alg, full_balance):
    """Test scalar substitution facility for tensors."""

    dr = free_alg
    p = dr.names

    x = IndexedBase('x')
    r = p.R
    i, j = p.R_dumms[:2]

    x_def = dr.define(x[i], dr.sum(2 * x[i]))
    summand = x[i]**2 * x[j]
    orig = dr.sum((i, r), summand)

    # k is free.
    expected = dr.sum((i, r), summand * 2**3)

    # Test different ways to perform the substitution.
    for res in [
            orig.subst(x[i], x_def.rhs, full_balance=full_balance),
            orig.subst_all([x_def], full_balance=full_balance),
            orig.subst_all([(x[i], x_def.rhs)], full_balance=full_balance),
            x_def.act(orig, full_balance=full_balance)
    ]:
        assert res.simplify() == expected.simplify()
Пример #21
0
 def create_restrictions(self, block_endea=0x5fc):
     self.C = []
     self.SP_C = {}
     strlen = Function('strlen')
     mem = IndexedBase('mem')
     memlen = Function('memlen')
     cond = True
     cur_block = self.dcodeblocks.get(block_endea)
     var_SP_id = 0
     printf(cur_block)
     while cur_block is not None:
         for cmd in reversed(cur_block):
             if cmd.name == 'BL':
                 function_name = get_func_name(cmd.operands[0].value)
                 printf(function_name)
                 if function_name == '.strcpy':
                     self.C.append(
                         strlen(arm.X1) < Symbol('STACK_%d' % var_SP_id))
                     self.SP_C['STACK_%d' % var_SP_id] = arm.X0
                     var_SP_id += 1
                 elif function_name == 'bad_code':
                     printf('bad')
                     self.C.append(strlen(arm.X1) < 12)
                     self.C.append(Eq(arm.W0, 12))
             elif cmd.name == 'MOV':
                 op0 = cmd.operands[0].value
                 op1 = cmd.operands[1].value
                 self.subs_restriction(op0, op1)
             elif cmd.name == 'LDR' or cmd.name == 'LDUR':
                 op0 = cmd.operands[0].value
                 op1 = cmd.operands[1].value
                 self.subs_restriction(op0, mem[op1])
             elif cmd.name == 'STR' or cmd.name == 'STUR':
                 op0 = cmd.operands[0].value
                 op1 = cmd.operands[1].value
                 self.subs_restriction(mem[op1], op0)
             elif cmd.name == 'B.NE':
                 if cond:
                     self.C.append(Ne(Symbol('B.NE.0'), Symbol('B.NE.1')))
                 else:
                     self.C.append(Eq(Symbol('B.NE.0'), Symbol('B.NE.1')))
             elif cmd.name == 'CMP':
                 op0 = cmd.operands[0].value
                 op1 = cmd.operands[1].value
                 self.subs_restriction({'B.NE.0': op0, 'B.NE.1': op1})
             elif cmd.name == 'ADD':
                 op0 = cmd.operands[0].value
                 op1 = cmd.operands[1].value
                 op2 = cmd.operands[2].value
                 self.subs_restriction(op0, op1 + op2)
             elif cmd.name == 'SUB':
                 op0 = cmd.operands[0].value
                 op1 = cmd.operands[1].value
                 op2 = cmd.operands[2].value
                 self.subs_restriction(op0, op1 - op2)
         cond, block_endea = cur_block.refs_to_it[0]
         cur_block = self.dcodeblocks.get(block_endea)
     self.simplify_restriction()
     return self.C, self.SP_C
Пример #22
0
    def setFields(self, fields):
        if len(fields) != self.rank:
            print(
                f"Error : please provide this function with exactly {self.rank} fields."
            )
            return

        self.symbs = [IndexedBase(el) for el in fields]
Пример #23
0
def test_einstein_summation(genmb):
    """Test Einstein summation convention."""
    dr = genmb
    p = dr.names
    l = p.L
    a, b, c = p.L_dumms[:3]
    o = IndexedBase('o')
    v = IndexedBase('v')
    c_dag = p.c_dag

    summand = o[a, b] * v[b] * c_dag[a]
    tensor = dr.einst(summand)
    assert tensor == dr.sum((a, l), (b, l), summand)

    summand = conjugate(o[b, a]) * v[b] * c_dag[a]
    tensor = dr.einst(summand)
    assert tensor == dr.sum((a, l), (b, l), summand)
Пример #24
0
def test_Indexed_coeff():
    N = Symbol("N", integer=True)
    len_y = N
    i = Idx("i", len_y - 1)
    y = IndexedBase("y", shape=(len_y,))
    a = (1 / y[i + 1] * y[i]).coeff(y[i])
    b = (y[i] / y[i + 1]).coeff(y[i])
    assert a == b
Пример #25
0
def test_Indexed_constructor():
    i, j = symbols("i j", integer=True)
    A = Indexed("A", i, j)
    assert A == Indexed(Symbol("A"), i, j)
    assert A == Indexed(IndexedBase("A"), i, j)
    raises(TypeError, lambda: Indexed(A, i, j))
    raises(IndexException, lambda: Indexed("A"))
    assert A.free_symbols == {A, A.base.label, i, j}
Пример #26
0
def test_Indexed_coeff():
    N = Symbol('N', integer=True)
    len_y = N
    i = Idx('i', len_y - 1)
    y = IndexedBase('y', shape=(len_y, ))
    a = (1 / y[i + 1] * y[i]).coeff(y[i])
    b = (y[i] / y[i + 1]).coeff(y[i])
    assert a == b
Пример #27
0
def test_3d_block_1():
    print('============== test_3d_block_1 ================')

    x, y, z = symbols('x y z')

    u = IndexedBase('u')
    v = IndexedBase('v')

    a = Lambda((x, y, z, v, u), Dot(Curl(u), Curl(v)) + 0.2 * Dot(u, v))

    # ...  create a finite element space
    p1 = 2
    p2 = 2
    p3 = 2
    ne1 = 2
    ne2 = 2
    ne3 = 2

    print('> Grid   :: [{},{},{}]'.format(ne1, ne2, ne3))
    print('> Degree :: [{},{},{}]'.format(p1, p2, p3))

    grid_1 = linspace(0., 1., ne1 + 1)
    grid_2 = linspace(0., 1., ne2 + 1)
    grid_3 = linspace(0., 1., ne3 + 1)

    V1 = SplineSpace(p1, grid=grid_1)
    V2 = SplineSpace(p2, grid=grid_2)
    V3 = SplineSpace(p3, grid=grid_3)

    W = TensorFemSpace(V1, V2, V3)
    # ...

    # ... vector space
    V = VectorFemSpace(W, W, W)
    # ...

    # ...
    kernel_py = compile_kernel('kernel_block_1', a, V, backend='python')
    kernel_f90 = compile_kernel('kernel_block_1', a, V, backend='fortran')

    M_py = assemble_matrix(V, kernel_py)
    M_f90 = assemble_matrix(V, kernel_f90)
    # ...

    assert_identical_coo(M_py, M_f90)
Пример #28
0
def test_indexed_is_constant():
    A = IndexedBase("A")
    i, j, k = symbols("i,j,k")
    assert not A[i].is_constant()
    assert A[i].is_constant(j)
    assert not A[1 + 2 * i, k].is_constant()
    assert not A[1 + 2 * i, k].is_constant(i)
    assert A[1 + 2 * i, k].is_constant(j)
    assert not A[1 + 2 * i, k].is_constant(k)
Пример #29
0
def test_Indexed():
    # Issue #10934
    if not numpy:
        skip("numpy not installed")

    a = IndexedBase('a')
    i, j = symbols('i j')
    b = numpy.array([[1, 2], [3, 4]])
    assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10
Пример #30
0
def IndexedBases(s):
    """
    declare multiple IndexedBase objects
    :param s: string of names seperated by white space
    returns IndxedBase objects as tuple
    """
    l = s.split()
    bases = [IndexedBase(x) for x in l]
    return tuple(bases)